diff --git a/blockzilla/get-block/src/worker/native_block.rs b/blockzilla/get-block/src/worker/native_block.rs index d226b577..1873d2bd 100644 --- a/blockzilla/get-block/src/worker/native_block.rs +++ b/blockzilla/get-block/src/worker/native_block.rs @@ -303,8 +303,7 @@ fn owned_hot_block( "native transaction regions or signatures have trailing or missing bytes".into(), ); } - // The existing renderer owns these two regions. Copy each once, then move - // the already decoded structured header and consensus fields without clones. + // This renderer owns the lanes and markers. Materialize them at this boundary. Ok(ArchiveV2HotBlockBlob { tx_count: block.tx_count, tx_rows, @@ -312,7 +311,7 @@ fn owned_hot_block( metadata_bytes: block.metadata_bytes.to_vec(), header: block.header, consensus_block_id: block.consensus_block_id, - block_markers: block.block_markers, + block_markers: block.block_markers.to_vec(), }) } diff --git a/crates/reader/blockzilla-read-sdk/assets/archive-v2-message-schema-post-unknown-fallbacks-v1.marker b/crates/compact-v2/blockzilla-archive-v2/assets/archive-v2-message-schema-post-unknown-fallbacks-v1.marker similarity index 100% rename from crates/reader/blockzilla-read-sdk/assets/archive-v2-message-schema-post-unknown-fallbacks-v1.marker rename to crates/compact-v2/blockzilla-archive-v2/assets/archive-v2-message-schema-post-unknown-fallbacks-v1.marker diff --git a/crates/compact-v2/blockzilla-archive-v2/src/v2/mod.rs b/crates/compact-v2/blockzilla-archive-v2/src/v2/mod.rs index d3cd8a4a..3a1d5f47 100644 --- a/crates/compact-v2/blockzilla-archive-v2/src/v2/mod.rs +++ b/crates/compact-v2/blockzilla-archive-v2/src/v2/mod.rs @@ -59,6 +59,23 @@ pub const WINCODE_ARCHIVE_V2_FLAG_FIRST_SEEN_REGISTRY: u32 = 1 << 2; pub const WINCODE_ARCHIVE_V2_FLAG_ALL_PUBKEY_REF_COUNTS: u32 = 1 << 3; pub const ARCHIVE_V2_HOT_TX_ROW_LEN: usize = 28; +/// Manifest marker for the current typed transaction-error encoding. +pub const CURRENT_TYPED_ERRORS_MARKER_FILE: &str = + "archive-v2-metadata-schema-current-typed-errors-v1.marker"; +pub const CURRENT_TYPED_ERRORS_MARKER_BYTES: &[u8] = + b"blockzilla/archive-v2-metadata-schema/current-typed-errors/v1\n"; +pub const CURRENT_TYPED_ERRORS_MARKER_SIZE: u64 = CURRENT_TYPED_ERRORS_MARKER_BYTES.len() as u64; +pub const CURRENT_TYPED_ERRORS_MARKER_SHA256: &str = + "f49c05f2021856a66542da4b84e31b2567b653a113acd05e0a0791cd620f0305"; + +/// Manifest marker for the message grammar with unknown System and Vote fallbacks. +pub const ARCHIVE_V2_POST_UNKNOWN_FALLBACKS_MARKER_FILE: &str = + "archive-v2-message-schema-post-unknown-fallbacks-v1.marker"; +pub const ARCHIVE_V2_POST_UNKNOWN_FALLBACKS_MARKER_BYTES: &[u8] = + include_bytes!("../../assets/archive-v2-message-schema-post-unknown-fallbacks-v1.marker"); +pub const ARCHIVE_V2_POST_UNKNOWN_FALLBACKS_MARKER_SHA256: &str = + "c870c4b0940b05b7bd18a134fba496c5c376f539ef7668f137112526d5c61edd"; + /// Header for the log-only wincode benchmark format. /// /// This is intentionally not a CAR-equivalent archive header. It only describes @@ -430,11 +447,11 @@ impl From for ArchiveV2HotBlockBlob { pub struct BorrowedArchiveV2HotBlockBlob<'a> { pub header: ArchiveV2HotBlockHeader, pub tx_count: u32, - tx_rows: &'a [[u8; ARCHIVE_V2_HOT_TX_ROW_LEN]], + tx_rows: &'a [ArchiveV2HotTxRowWire], pub message_bytes: &'a [u8], pub metadata_bytes: &'a [u8], pub consensus_block_id: Option<[u8; 32]>, - pub block_markers: Vec>, + pub block_markers: BorrowedArchiveV2BlockMarkers<'a>, } /// Replay-oriented zero-copy view of a current hot block. @@ -447,14 +464,51 @@ pub struct BorrowedArchiveV2HotBlockBlob<'a> { pub struct BorrowedArchiveV2HotBlockBlobWithoutRewards<'a> { pub header: ArchiveV2HotBlockHeader, pub tx_count: u32, - tx_rows: &'a [[u8; ARCHIVE_V2_HOT_TX_ROW_LEN]], + tx_rows: &'a [ArchiveV2HotTxRowWire], pub message_bytes: &'a [u8], pub metadata_bytes: &'a [u8], rewards_field_bytes: &'a [u8], pub consensus_block_id: Option<[u8; 32]>, - pub block_markers: Vec>, + pub block_markers: BorrowedArchiveV2BlockMarkers<'a>, +} + +/// Validated marker records that borrow their exact bytes from one hot block. +#[derive(Debug, Clone, Copy, Default)] +pub struct BorrowedArchiveV2BlockMarkers<'a> { + records: &'a [u8], + count: usize, +} + +impl<'a> BorrowedArchiveV2BlockMarkers<'a> { + pub fn len(&self) -> usize { + self.count + } + + pub fn is_empty(&self) -> bool { + self.count == 0 + } + + pub fn iter(&self) -> impl ExactSizeIterator { + let mut records = self.records; + (0..self.count).map(move |_| { + read_block_marker::(&mut records) + .expect("validated block marker") + }) + } + + pub fn to_vec(&self) -> Vec> { + self.iter().map(<[u8]>::to_vec).collect() + } +} + +impl PartialEq for BorrowedArchiveV2BlockMarkers<'_> { + fn eq(&self, other: &Self) -> bool { + self.iter().eq(other.iter()) + } } +impl Eq for BorrowedArchiveV2BlockMarkers<'_> {} + impl BorrowedArchiveV2HotBlockBlobWithoutRewards<'_> { #[inline] pub fn tx_rows_len(&self) -> usize { @@ -492,7 +546,7 @@ impl BorrowedArchiveV2HotBlockBlob<'_> { /// Exact iterator over borrowed hot-block transaction-row wire records. #[derive(Debug, Clone)] pub struct ArchiveV2HotTxRowIter<'a> { - rows: core::slice::Iter<'a, [u8; ARCHIVE_V2_HOT_TX_ROW_LEN]>, + rows: core::slice::Iter<'a, ArchiveV2HotTxRowWire>, } impl Iterator for ArchiveV2HotTxRowIter<'_> { @@ -500,7 +554,7 @@ impl Iterator for ArchiveV2HotTxRowIter<'_> { #[inline] fn next(&mut self) -> Option { - self.rows.next().map(ArchiveV2HotTxRow::from_wire_bytes) + self.rows.next().map(ArchiveV2HotTxRow::from) } #[inline] @@ -512,9 +566,7 @@ impl Iterator for ArchiveV2HotTxRowIter<'_> { impl DoubleEndedIterator for ArchiveV2HotTxRowIter<'_> { #[inline] fn next_back(&mut self) -> Option { - self.rows - .next_back() - .map(ArchiveV2HotTxRow::from_wire_bytes) + self.rows.next_back().map(ArchiveV2HotTxRow::from) } } @@ -670,7 +722,7 @@ pub fn deserialize_archive_v2_hot_block_blob(bytes: &[u8]) -> ReadResult( @@ -727,7 +779,7 @@ fn read_borrowed_hot_block<'a, C: Config>( <( ArchiveV2HotBlockHeader, u32, - &[[u8; ARCHIVE_V2_HOT_TX_ROW_LEN]], + &[ArchiveV2HotTxRowWire], &[u8], &[u8], ) as SchemaRead>::get(remaining.by_ref())?; @@ -808,10 +860,10 @@ pub fn deserialize_archive_v2_hot_block_blob_borrowed_current_without_rewards( let (tx_count, tx_rows, message_bytes, metadata_bytes): ( u32, - &[[u8; ARCHIVE_V2_HOT_TX_ROW_LEN]], + &[ArchiveV2HotTxRowWire], &[u8], &[u8], - ) = <(u32, &[[u8; ARCHIVE_V2_HOT_TX_ROW_LEN]], &[u8], &[u8]) as SchemaRead< + ) = <(u32, &[ArchiveV2HotTxRowWire], &[u8], &[u8]) as SchemaRead< HistoricalSourceWincodeLeb128Config, >>::get(remaining.by_ref())?; let (consensus_block_id, block_markers) = @@ -841,13 +893,26 @@ pub fn deserialize_archive_v2_hot_block_blob_borrowed_current_without_rewards( fn read_optional_consensus_tail<'a, C: Config>( bytes: &mut &'a [u8], -) -> ReadResult<(Option<[u8; 32]>, Vec>)> { +) -> ReadResult<(Option<[u8; 32]>, BorrowedArchiveV2BlockMarkers<'a>)> { if bytes.is_empty() { - return Ok((None, Vec::new())); + return Ok((None, BorrowedArchiveV2BlockMarkers::default())); } let consensus_block_id = as SchemaRead<'a, C>>::get(bytes.by_ref())?; - let block_markers = > as SchemaRead<'a, C>>::get(bytes.by_ref())?; - Ok((consensus_block_id, block_markers)) + let count = C::LengthEncoding::read_prealloc_check::>(bytes.by_ref())?; + let start = *bytes; + for _ in 0..count { + read_block_marker::(bytes)?; + } + let records = &start[..start.len() - bytes.len()]; + Ok(( + consensus_block_id, + BorrowedArchiveV2BlockMarkers { records, count }, + )) +} + +fn read_block_marker<'a, C: Config>(bytes: &mut &'a [u8]) -> ReadResult<&'a [u8]> { + let len = C::LengthEncoding::read_prealloc_check::(bytes.by_ref())?; + Ok(bytes.take_borrowed(len)?) } #[cfg(test)] @@ -924,7 +989,7 @@ mod hot_block_slot_time_tests { assert_eq!(replay.message_bytes, owned.message_bytes); assert_eq!(replay.metadata_bytes, owned.metadata_bytes); assert_eq!(replay.consensus_block_id, owned.consensus_block_id); - assert_eq!(replay.block_markers, owned.block_markers); + assert_eq!(replay.block_markers.to_vec(), owned.block_markers); } fn assert_exact_rewards_field(block: ArchiveV2HotBlockBlob) { @@ -993,18 +1058,22 @@ mod hot_block_slot_time_tests { assert_eq!(decoded.tx_count, block.tx_count); let borrowed = deserialize_archive_v2_hot_block_blob_borrowed_current(&bytes).unwrap(); assert_eq!(borrowed.consensus_block_id, Some([0x21; 32])); - assert_eq!(borrowed.block_markers, block.block_markers); + assert_eq!(borrowed.block_markers.to_vec(), block.block_markers); + for marker in borrowed.block_markers.iter() { + assert!(marker.as_ptr() >= bytes.as_ptr()); + assert!(marker.as_ptr_range().end <= bytes.as_ptr_range().end); + } let replay = deserialize_archive_v2_hot_block_blob_borrowed_current_without_rewards(&bytes).unwrap(); assert_eq!(replay.consensus_block_id, Some([0x21; 32])); - assert_eq!(replay.block_markers, block.block_markers); + assert_eq!(replay.block_markers.to_vec(), block.block_markers); let exact = deserialize_archive_v2_hot_block_blob_borrowed_current_with_preallocation_limit::< { ARCHIVE_V2_DECODE_PREALLOCATION_LIMIT_BYTES }, >(&bytes) .unwrap(); assert_eq!(exact.consensus_block_id, Some([0x21; 32])); - assert_eq!(exact.block_markers, block.block_markers); + assert_eq!(exact.block_markers.to_vec(), block.block_markers); let tail = wincode::config::serialize( &(block.consensus_block_id, block.block_markers.clone()), historical_source_wincode_leb128_config(), @@ -1563,18 +1632,35 @@ pub struct ArchiveV2HotTxRow { pub reserved: [u8; 3], } -impl ArchiveV2HotTxRow { +#[repr(C)] +#[derive(Debug, SchemaRead, SchemaWrite)] +#[wincode(assert_zero_copy)] +struct ArchiveV2HotTxRowWire { + tx_index: [u8; 4], + flags: [u8; 4], + message_offset: [u8; 4], + message_len: [u8; 4], + metadata_offset: [u8; 4], + metadata_len: [u8; 4], + signature_count: u8, + reserved: [u8; 3], +} + +const _: () = assert!(core::mem::size_of::() == ARCHIVE_V2_HOT_TX_ROW_LEN); +const _: () = assert!(core::mem::align_of::() == 1); + +impl From<&ArchiveV2HotTxRowWire> for ArchiveV2HotTxRow { #[inline] - fn from_wire_bytes(bytes: &[u8; ARCHIVE_V2_HOT_TX_ROW_LEN]) -> Self { + fn from(wire: &ArchiveV2HotTxRowWire) -> Self { Self { - tx_index: u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]), - flags: u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]), - message_offset: u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]), - message_len: u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]), - metadata_offset: u32::from_le_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]), - metadata_len: u32::from_le_bytes([bytes[20], bytes[21], bytes[22], bytes[23]]), - signature_count: bytes[24], - reserved: [bytes[25], bytes[26], bytes[27]], + tx_index: u32::from_le_bytes(wire.tx_index), + flags: u32::from_le_bytes(wire.flags), + message_offset: u32::from_le_bytes(wire.message_offset), + message_len: u32::from_le_bytes(wire.message_len), + metadata_offset: u32::from_le_bytes(wire.metadata_offset), + metadata_len: u32::from_le_bytes(wire.metadata_len), + signature_count: wire.signature_count, + reserved: wire.reserved, } } } @@ -1605,9 +1691,12 @@ unsafe impl<'de, C: wincode::config::ConfigCore> SchemaRead<'de, C> for ArchiveV type Dst = Self; #[inline] - fn read(mut reader: impl Reader<'de>, dst: &mut MaybeUninit) -> ReadResult<()> { - let bytes = reader.take_array::()?; - dst.write(Self::from_wire_bytes(&bytes)); + fn read(reader: impl Reader<'de>, dst: &mut MaybeUninit) -> ReadResult<()> { + // The wire struct contains only bytes and byte arrays. + let wire = >::get( + reader, + )?; + dst.write(Self::from(&wire)); Ok(()) } } diff --git a/crates/compact-v2/blockzilla-archive-v2/src/v2/wire_rewrite.rs b/crates/compact-v2/blockzilla-archive-v2/src/v2/wire_rewrite.rs index ce670329..93fead72 100644 --- a/crates/compact-v2/blockzilla-archive-v2/src/v2/wire_rewrite.rs +++ b/crates/compact-v2/blockzilla-archive-v2/src/v2/wire_rewrite.rs @@ -22,6 +22,9 @@ type ArchiveV2WireBoundedConfig = wincode::config::Configuration< wincode::int_encoding::LittleEndian, blockzilla_primitives::Leb128, >; +type HistoricalMetadataConfig = blockzilla_primitives::BoundedHistoricalSourceWincodeLeb128Config< + { crate::ARCHIVE_V2_DECODE_PREALLOCATION_LIMIT_BYTES }, +>; /// Default maximum accepted or produced size for one hot block payload. pub const ARCHIVE_V2_WIRE_REWRITE_MAX_FRAME_BYTES: usize = 512 << 20; @@ -313,18 +316,56 @@ pub fn canonicalize_archive_v2_metadata_owned( pub fn normalize_archive_v2_historical_source_metadata_owned( input: &[u8], ) -> anyhow::Result<(Vec, ArchiveV2WireMetadataErrorSchema)> { - normalize_metadata_owned_with_config( - input, - blockzilla_primitives::bounded_historical_source_wincode_leb128_config::< - { crate::ARCHIVE_V2_DECODE_PREALLOCATION_LIMIT_BYTES }, - >(), - ) + normalize_metadata_owned_with_config(input, HistoricalMetadataConfig::new()) +} + +/// Decode a historical source record with the same ambiguity checks as +/// [normalize_archive_v2_historical_source_metadata_owned]. +/// +/// Readers that need the metadata value can use it directly, without +/// serializing it to current-schema bytes and decoding those bytes again. +pub fn decode_archive_v2_historical_source_metadata_owned( + input: &[u8], +) -> anyhow::Result<( + blockzilla_compact::CompactMetaV1, + ArchiveV2WireMetadataErrorSchema, +)> { + decode_metadata_owned_with_config(input, HistoricalMetadataConfig::new()) +} + +/// Check whether a present transaction error can be read as current typed +/// metadata without trying the legacy grammar. +/// +/// The legacy prefix must be impossible. The caller must still validate the +/// complete record under the current grammar, including the error itself. +/// A false result requires the usual historical schema selection. +pub fn archive_v2_historical_source_metadata_can_try_current_only(input: &[u8]) -> bool { + input.len() <= crate::ARCHIVE_V2_DECODE_PREALLOCATION_LIMIT_BYTES + && input.first() == Some(&1) + && !possible_owned_legacy_error::(input) } fn normalize_metadata_owned_with_config( input: &[u8], config: C, ) -> anyhow::Result<(Vec, ArchiveV2WireMetadataErrorSchema)> { + let (value, schema) = decode_metadata_owned_with_config(input, config)?; + let output = + wincode::config::serialize(&value, blockzilla_primitives::wincode_leb128_config())?; + anyhow::ensure!( + output.len() <= crate::ARCHIVE_V2_DECODE_PREALLOCATION_LIMIT_BYTES, + "canonical metadata output exceeds the Archive V2 owned-fallback limit" + ); + Ok((output, schema)) +} + +fn decode_metadata_owned_with_config( + input: &[u8], + config: C, +) -> anyhow::Result<( + blockzilla_compact::CompactMetaV1, + ArchiveV2WireMetadataErrorSchema, +)> { anyhow::ensure!( input.len() <= crate::ARCHIVE_V2_DECODE_PREALLOCATION_LIMIT_BYTES, "metadata input exceeds the Archive V2 owned-fallback limit" @@ -347,9 +388,11 @@ fn normalize_metadata_owned_with_config( ) }; - let (value, schema) = match (current, legacy) { - (Ok(current), None | Some(Err(_))) => (current, ArchiveV2WireMetadataErrorSchema::Current), - (Err(_), Some(Ok(legacy))) => (legacy, ArchiveV2WireMetadataErrorSchema::Legacy), + match (current, legacy) { + (Ok(current), None | Some(Err(_))) => { + Ok((current, ArchiveV2WireMetadataErrorSchema::Current)) + } + (Err(_), Some(Ok(legacy))) => Ok((legacy, ArchiveV2WireMetadataErrorSchema::Legacy)), (Ok(current), Some(Ok(legacy))) => { let current_bytes = wincode::config::serialize( ¤t, @@ -363,22 +406,13 @@ fn normalize_metadata_owned_with_config( current_bytes == legacy_bytes, "ambiguous compact metadata decodes as different current and legacy values" ); - return Ok((current_bytes, ArchiveV2WireMetadataErrorSchema::Current)); - } - (Err(current), Some(Err(legacy))) => { - return Err(anyhow!( - "compact metadata is neither current nor legacy: current={current}; legacy={legacy}" - )); + Ok((current, ArchiveV2WireMetadataErrorSchema::Current)) } + (Err(current), Some(Err(legacy))) => Err(anyhow!( + "compact metadata is neither current nor legacy: current={current}; legacy={legacy}" + )), (Err(_), None) => unreachable!("legacy probe is skipped only for valid current metadata"), - }; - let output = - wincode::config::serialize(&value, blockzilla_primitives::wincode_leb128_config())?; - anyhow::ensure!( - output.len() <= crate::ARCHIVE_V2_DECODE_PREALLOCATION_LIMIT_BYTES, - "canonical metadata output exceeds the Archive V2 owned-fallback limit" - ); - Ok((output, schema)) + } } fn possible_owned_legacy_error(input: &[u8]) -> bool { @@ -388,8 +422,17 @@ fn possible_owned_legacy_error(input: &[u8]) -> bool let Ok(len) = C::LengthEncoding::read_prealloc_check::(&mut tail) else { return false; }; + // Stored errors use a four-byte enum tag. An indexed error adds one + // byte. InstructionError adds an index and another four-byte enum tag, + // with four more bytes for Custom or at least eight for a Borsh string. + // Historical unit BorshIoError also fits the nine-byte case. + if !matches!(len, 4 | 5 | 9 | 13 | 17..) { + return false; + } tail.get(..len).is_some_and(|stored| { - blockzilla_compact::CompactTransactionError::from_stored_wincode_bytes(stored).is_ok() + stored[1..4] == [0, 0, 0] + && blockzilla_compact::CompactTransactionError::from_stored_wincode_bytes(stored) + .is_ok() }) } @@ -3204,6 +3247,9 @@ mod tests { let source = [ 1, 4, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]; + assert!(!archive_v2_historical_source_metadata_can_try_current_only( + &source + )); let current: CompactMetaV1 = wincode::config::deserialize_exact(&source, wincode_leb128_config()).unwrap(); let legacy: LegacyArchiveV2CompactMetaV1 = @@ -3227,6 +3273,12 @@ mod tests { ); let mut padded = source.to_vec(); padded.splice(7..8, [0x82, 0]); + assert!( + decode_archive_v2_historical_source_metadata_owned(&padded) + .unwrap_err() + .to_string() + .contains("ambiguous") + ); assert!( normalize_archive_v2_historical_source_metadata_owned(&padded) .unwrap_err() @@ -3250,6 +3302,9 @@ mod tests { .len(); let mut source = canonical.clone(); source.splice(4..5, [canonical[4] | 0x80, 0]); + assert!(archive_v2_historical_source_metadata_can_try_current_only( + &source + )); let selected = validate_archive_v2_historical_source_metadata_error_prefix_for_selected_schema( &source, @@ -3279,6 +3334,13 @@ mod tests { .0, canonical ); + let (decoded, schema) = + decode_archive_v2_historical_source_metadata_owned(&source).unwrap(); + assert_eq!(schema, ArchiveV2WireMetadataErrorSchema::Current); + assert_eq!( + wincode::config::serialize(&decoded, wincode_leb128_config()).unwrap(), + canonical + ); let mut output = Vec::new(); assert!( rewrite_archive_v2_current_metadata_wire( @@ -3335,12 +3397,27 @@ mod tests { (current, ArchiveV2WireMetadataErrorSchema::Current) ); - let stored = wincode::serialize(&StoredTransactionError::AccountInUse).unwrap(); - let legacy_prefix = - wincode::config::serialize(&Some(stored), wincode_leb128_config()).unwrap(); - assert!(possible_owned_legacy_error::( - &legacy_prefix - )); + for stored in [ + wincode::serialize(&StoredTransactionError::AccountInUse).unwrap(), + wincode::serialize(&StoredTransactionError::DuplicateInstruction(0)).unwrap(), + wincode::serialize(&StoredTransactionError::InstructionError( + 0, + StoredInstructionError::Custom(42), + )) + .unwrap(), + wincode::serialize(&StoredTransactionError::InstructionError( + 0, + StoredInstructionError::BorshIoError(String::new()), + )) + .unwrap(), + vec![8, 0, 0, 0, 0, 44, 0, 0, 0], // Historical unit BorshIoError. + ] { + let legacy_prefix = + wincode::config::serialize(&Some(stored), wincode_leb128_config()).unwrap(); + assert!(!archive_v2_historical_source_metadata_can_try_current_only( + &legacy_prefix + )); + } let error = normalize_archive_v2_historical_source_metadata_owned(&[1]).unwrap_err(); assert!(error.to_string().contains("current=")); assert!(error.to_string().contains("legacy=")); @@ -3359,6 +3436,9 @@ mod tests { let mut source = vec![1, stored.len() as u8 | 0x80, 0]; source.extend(&stored); source.extend(&successful[1..]); + assert!(!archive_v2_historical_source_metadata_can_try_current_only( + &source + )); let selected = validate_archive_v2_historical_source_metadata_error_prefix_for_selected_schema( &source, @@ -3383,11 +3463,17 @@ mod tests { blockzilla_compact::CompactInstructionError::BorshIoError("x".repeat(96)), ), ); + let canonical = wincode::config::serialize(&expected, wincode_leb128_config()).unwrap(); assert_eq!( - normalize_archive_v2_historical_source_metadata_owned(&source) - .unwrap() - .0, - wincode::config::serialize(&expected, wincode_leb128_config()).unwrap() + normalize_archive_v2_historical_source_metadata_owned(&source).unwrap(), + (canonical.clone(), ArchiveV2WireMetadataErrorSchema::Legacy) + ); + let (decoded, schema) = + decode_archive_v2_historical_source_metadata_owned(&source).unwrap(); + assert_eq!(schema, ArchiveV2WireMetadataErrorSchema::Legacy); + assert_eq!( + wincode::config::serialize(&decoded, wincode_leb128_config()).unwrap(), + canonical ); } diff --git a/crates/compact-v2/blockzilla-compact-v2-reader/src/message_schema.rs b/crates/compact-v2/blockzilla-compact-v2-reader/src/message_schema.rs index 24a917ea..022d6cb8 100644 --- a/crates/compact-v2/blockzilla-compact-v2-reader/src/message_schema.rs +++ b/crates/compact-v2/blockzilla-compact-v2-reader/src/message_schema.rs @@ -5,10 +5,11 @@ //! exact enum order. Readers must never infer this choice from message data. use blockzilla_archive_v2::{ - ArchiveV2ComputeBudgetInstructionData, ArchiveV2HotInstruction, ArchiveV2HotInstructionData, - ArchiveV2HotLegacyMessage, ArchiveV2HotMessagePayload, ArchiveV2HotV0Message, - ArchiveV2SystemInstructionData, ArchiveV2VoteHashRef, ArchiveV2VoteStateUpdate, - ArchiveV2VoteTowerSync, + ARCHIVE_V2_POST_UNKNOWN_FALLBACKS_MARKER_BYTES, ARCHIVE_V2_POST_UNKNOWN_FALLBACKS_MARKER_FILE, + ARCHIVE_V2_POST_UNKNOWN_FALLBACKS_MARKER_SHA256, ArchiveV2ComputeBudgetInstructionData, + ArchiveV2HotInstruction, ArchiveV2HotInstructionData, ArchiveV2HotLegacyMessage, + ArchiveV2HotMessagePayload, ArchiveV2HotV0Message, ArchiveV2SystemInstructionData, + ArchiveV2VoteHashRef, ArchiveV2VoteStateUpdate, ArchiveV2VoteTowerSync, }; use blockzilla_compact::{ CompactMessageHeader, OwnedCompactAddressTableLookup, OwnedCompactRecentBlockhash, @@ -193,8 +194,8 @@ pub enum CompactV2MessageSchemaError { /// Select one grammar from a published generation manifest and its bytes. /// -/// Exactly one present marker is effective only when the manifest binds its -/// exact name, size, and digest. The object bytes are checked independently. +/// A marker is effective when the manifest binds its exact name, size, and +/// digest. The object bytes are checked independently. pub fn select_compact_v2_message_schema( source: &S, manifest: &GenerationManifest, @@ -230,6 +231,8 @@ fn select_message_schema( manifest.and_then(|manifest| manifest.file(COMPACT_V2_MAY24_MESSAGE_SCHEMA_MARKER_FILE)); let current_binding = manifest.and_then(|manifest| manifest.file(COMPACT_V2_CURRENT_MESSAGE_SCHEMA_MARKER_FILE)); + let post_binding = + manifest.and_then(|manifest| manifest.file(ARCHIVE_V2_POST_UNKNOWN_FALLBACKS_MARKER_FILE)); let may24_active = validate_marker_presence( manifest.is_some(), @@ -244,7 +247,7 @@ fn select_message_schema( current_binding, )?; - if may24_active && current_active { + if may24_active && (current_active || post_binding.is_some()) { return Err(CompactV2MessageSchemaError::MessageSchemaMarkerConflict); } if may24_active { @@ -269,6 +272,22 @@ fn select_message_schema( COMPACT_V2_CURRENT_MESSAGE_SCHEMA_MARKER_SHA256, COMPACT_V2_CURRENT_MESSAGE_SCHEMA_MARKER_BYTES, )?; + } + if let Some(binding) = post_binding { + let size = source + .size(ARCHIVE_V2_POST_UNKNOWN_FALLBACKS_MARKER_FILE)? + .ok_or(CompactV2MessageSchemaError::BoundCurrentMarkerMissing)?; + validate_marker_object( + source, + size, + binding, + ARCHIVE_V2_POST_UNKNOWN_FALLBACKS_MARKER_FILE, + ARCHIVE_V2_POST_UNKNOWN_FALLBACKS_MARKER_BYTES.len() as u64, + ARCHIVE_V2_POST_UNKNOWN_FALLBACKS_MARKER_SHA256, + ARCHIVE_V2_POST_UNKNOWN_FALLBACKS_MARKER_BYTES, + )?; + } + if current_active || post_binding.is_some() { return Ok(CompactV2MessageSchema::Current); } if cluster_id == "mainnet-beta" && MAY24_MAINNET_EPOCHS.contains(&epoch) { diff --git a/crates/compact-v2/blockzilla-compact-v2-reader/src/metadata_schema.rs b/crates/compact-v2/blockzilla-compact-v2-reader/src/metadata_schema.rs index 051516c4..cd4ece6f 100644 --- a/crates/compact-v2/blockzilla-compact-v2-reader/src/metadata_schema.rs +++ b/crates/compact-v2/blockzilla-compact-v2-reader/src/metadata_schema.rs @@ -6,6 +6,10 @@ //! decoder must not infer the grammar from an individual metadata record: //! records with `err == None` have the same bytes in both grammars. +use blockzilla_archive_v2::{ + CURRENT_TYPED_ERRORS_MARKER_BYTES, CURRENT_TYPED_ERRORS_MARKER_FILE, + CURRENT_TYPED_ERRORS_MARKER_SHA256, CURRENT_TYPED_ERRORS_MARKER_SIZE, +}; use blockzilla_compact::{ CompactInnerInstructions, CompactLogStream, CompactMetaV1, CompactReturnData, CompactReward, CompactTokenBalance, CompactTransactionError, @@ -115,8 +119,8 @@ pub enum CompactV2MetadataSchemaError { /// Select one metadata grammar from a published generation manifest. /// -/// A missing marker selects the current typed-error grammar. A present marker -/// is effective only when the manifest binds its exact name, size, and digest. +/// A missing marker preserves the current typed-error default. A declared +/// marker must match the exact manifest binding and object bytes. pub fn select_compact_v2_metadata_schema( source: &S, manifest: &GenerationManifest, @@ -144,6 +148,12 @@ fn select_metadata_schema( let source_size = source.size(COMPACT_V2_LEGACY_METADATA_SCHEMA_MARKER_FILE)?; let binding = manifest.and_then(|manifest| manifest.file(COMPACT_V2_LEGACY_METADATA_SCHEMA_MARKER_FILE)); + let current = manifest.and_then(|manifest| manifest.file(CURRENT_TYPED_ERRORS_MARKER_FILE)); + if binding.is_some() && current.is_some() { + return Err(CompactV2MetadataSchemaError::InvalidManifest( + "conflicting Compact V2 metadata-schema markers".into(), + )); + } match (source_size, binding) { (Some(_), None) if manifest.is_some() => { @@ -153,7 +163,25 @@ fn select_metadata_schema( return Err(CompactV2MetadataSchemaError::UnpublishedHistoricalMarker); } (None, Some(_)) => return Err(CompactV2MetadataSchemaError::BoundMarkerMissing), - (None, None) => return Ok(CompactV2MetadataSchema::CurrentTypedError), + (None, None) => { + if let Some(marker) = current { + if marker.size != CURRENT_TYPED_ERRORS_MARKER_SIZE + || marker.sha256 != CURRENT_TYPED_ERRORS_MARKER_SHA256 + { + return Err(CompactV2MetadataSchemaError::InvalidManifest(format!( + "invalid manifest binding for {CURRENT_TYPED_ERRORS_MARKER_FILE}" + ))); + } + let bytes = source.read_all_bounded( + CURRENT_TYPED_ERRORS_MARKER_FILE, + CURRENT_TYPED_ERRORS_MARKER_SIZE as usize, + )?; + if bytes.as_slice() != CURRENT_TYPED_ERRORS_MARKER_BYTES { + return Err(CompactV2MetadataSchemaError::MarkerObjectBytes); + } + } + return Ok(CompactV2MetadataSchema::CurrentTypedError); + } (Some(source_size), Some(binding)) => { if binding.size != COMPACT_V2_LEGACY_METADATA_SCHEMA_MARKER_SIZE { return Err(CompactV2MetadataSchemaError::MarkerManifestSize { @@ -352,6 +380,30 @@ mod tests { ); } + #[test] + fn bound_current_metadata_marker_checks_object_bytes() { + let dir = TempDir::new().unwrap(); + let source = LocalRangeSource::new(dir.path()); + let path = dir.path().join(CURRENT_TYPED_ERRORS_MARKER_FILE); + let manifest = manifest(Some(GenerationFile { + name: CURRENT_TYPED_ERRORS_MARKER_FILE.to_owned(), + size: CURRENT_TYPED_ERRORS_MARKER_SIZE, + sha256: CURRENT_TYPED_ERRORS_MARKER_SHA256.to_owned(), + })); + std::fs::write(&path, CURRENT_TYPED_ERRORS_MARKER_BYTES).unwrap(); + assert_eq!( + select_compact_v2_metadata_schema(&source, &manifest).unwrap(), + CompactV2MetadataSchema::CurrentTypedError + ); + let mut altered = CURRENT_TYPED_ERRORS_MARKER_BYTES.to_vec(); + altered[0] ^= 1; + std::fs::write(path, altered).unwrap(); + assert!(matches!( + select_compact_v2_metadata_schema(&source, &manifest), + Err(CompactV2MetadataSchemaError::MarkerObjectBytes) + )); + } + #[test] fn legacy_metadata_marker_must_be_manifest_bound() { let dir = TempDir::new().unwrap(); diff --git a/crates/compact-v2/blockzilla-compact-v2-reader/src/reader.rs b/crates/compact-v2/blockzilla-compact-v2-reader/src/reader.rs index be47747e..8eb0230d 100644 --- a/crates/compact-v2/blockzilla-compact-v2-reader/src/reader.rs +++ b/crates/compact-v2/blockzilla-compact-v2-reader/src/reader.rs @@ -738,7 +738,7 @@ impl BorrowedDecodedBlock<'_> { message_bytes, metadata_bytes, consensus_block_id: block.consensus_block_id, - block_markers: block.block_markers, + block_markers: block.block_markers.to_vec(), } } BorrowedDecodedBlockPayload::CurrentWithoutRewards(_) => { diff --git a/crates/reader/blockzilla-read-sdk/src/metadata_wire_profile.rs b/crates/reader/blockzilla-read-sdk/src/metadata_wire_profile.rs index 2518519c..dc850343 100644 --- a/crates/reader/blockzilla-read-sdk/src/metadata_wire_profile.rs +++ b/crates/reader/blockzilla-read-sdk/src/metadata_wire_profile.rs @@ -14,6 +14,10 @@ use blockzilla_archive_v2::{ ArchiveV2WireIdentityVisitor, ArchiveV2WireRewriteLimits, rewrite_archive_v2_successful_metadata_wire, }; +pub use blockzilla_archive_v2::{ + CURRENT_TYPED_ERRORS_MARKER_BYTES, CURRENT_TYPED_ERRORS_MARKER_FILE, + CURRENT_TYPED_ERRORS_MARKER_SHA256, CURRENT_TYPED_ERRORS_MARKER_SIZE, +}; use blockzilla_compact::{ CompactInnerInstructions, CompactLogStream, CompactMetaV1, CompactReturnData, CompactReward, CompactTokenBalance, CompactTransactionError, @@ -27,15 +31,7 @@ use crate::{ manifest::{GenerationFile, GenerationManifest}, }; -/// The only metadata schema marker emitted by current producers. -pub const CURRENT_TYPED_ERRORS_MARKER_FILE: &str = - "archive-v2-metadata-schema-current-typed-errors-v1.marker"; const METADATA_SCHEMA_MARKER_PREFIX: &str = "archive-v2-metadata-schema-"; -pub const CURRENT_TYPED_ERRORS_MARKER_BYTES: &[u8] = - b"blockzilla/archive-v2-metadata-schema/current-typed-errors/v1\n"; -pub const CURRENT_TYPED_ERRORS_MARKER_SIZE: u64 = 62; -pub const CURRENT_TYPED_ERRORS_MARKER_SHA256: &str = - "f49c05f2021856a66542da4b84e31b2567b653a113acd05e0a0791cd620f0305"; /// The metadata error grammar selected for one complete generation. /// diff --git a/crates/reader/blockzilla-read-sdk/src/reader.rs b/crates/reader/blockzilla-read-sdk/src/reader.rs index 13551bbf..db12c2ad 100644 --- a/crates/reader/blockzilla-read-sdk/src/reader.rs +++ b/crates/reader/blockzilla-read-sdk/src/reader.rs @@ -24,9 +24,9 @@ use blockzilla_archive_v2::{ WINCODE_ARCHIVE_V2_FLAG_ALL_PUBKEY_REF_COUNTS, WINCODE_ARCHIVE_V2_FLAG_FIRST_SEEN_REGISTRY, WINCODE_ARCHIVE_V2_FLAG_LEB128, WINCODE_ARCHIVE_V2_FLAG_NO_REGISTRY, WINCODE_ARCHIVE_V2_HOT_BLOCK_VERSION, WincodeArchiveV2Footer, WincodeArchiveV2Genesis, - deserialize_archive_v2_hot_block_blob, deserialize_archive_v2_hot_block_blob_borrowed_current, + decode_archive_v2_historical_source_metadata_owned, deserialize_archive_v2_hot_block_blob, + deserialize_archive_v2_hot_block_blob_borrowed_current, deserialize_archive_v2_hot_block_blob_borrowed_current_without_rewards, - normalize_archive_v2_historical_source_metadata_owned, }; use blockzilla_compact::CompactMetaV1; use blockzilla_primitives::{CompactPubkey, bounded_historical_source_wincode_leb128_config}; @@ -4325,33 +4325,28 @@ fn metadata_state( row.tx_index, slot, )?; - let canonical = match metadata_wire_profile { - ArchiveV2MetadataWireProfile::CurrentTypedErrorsV1 => None, + let metadata = match metadata_wire_profile { ArchiveV2MetadataWireProfile::UnmarkedHistoricalCompatibility - if bytes.first() == Some(&0) => + if bytes.first() != Some(&0) => { - None - } - ArchiveV2MetadataWireProfile::UnmarkedHistoricalCompatibility => Some( - normalize_archive_v2_historical_source_metadata_owned(bytes) + decode_archive_v2_historical_source_metadata_owned(bytes) .map_err(|error| Error::InvalidBlock { slot, message: format!("select metadata schema for tx {}: {error}", row.tx_index), })? - .0, - ), + .0 + } + _ => wincode::config::deserialize_exact( + bytes, + bounded_historical_source_wincode_leb128_config::< + ARCHIVE_V2_DECODE_PREALLOCATION_LIMIT_BYTES, + >(), + ) + .map_err(|error| Error::InvalidBlock { + slot, + message: format!("decode metadata for tx {}: {error}", row.tx_index), + })?, }; - let decode_bytes = canonical.as_deref().unwrap_or(bytes); - let metadata = wincode::config::deserialize_exact( - decode_bytes, - bounded_historical_source_wincode_leb128_config::< - ARCHIVE_V2_DECODE_PREALLOCATION_LIMIT_BYTES, - >(), - ) - .map_err(|error| Error::InvalidBlock { - slot, - message: format!("decode metadata for tx {}: {error}", row.tx_index), - })?; Ok(MetadataState::Decoded(Box::new(metadata))) } diff --git a/crates/reader/blockzilla-read-sdk/src/selective_metadata.rs b/crates/reader/blockzilla-read-sdk/src/selective_metadata.rs index 2d21304e..8c65d496 100644 --- a/crates/reader/blockzilla-read-sdk/src/selective_metadata.rs +++ b/crates/reader/blockzilla-read-sdk/src/selective_metadata.rs @@ -7,6 +7,7 @@ use blockzilla_archive_v2::{ ArchiveV2WireMetadataErrorIndex, ArchiveV2WireMetadataErrorSchema, + archive_v2_historical_source_metadata_can_try_current_only, normalize_archive_v2_historical_source_metadata_owned, validate_archive_v2_historical_source_metadata_error_prefix_for_selected_schema, }; @@ -2275,16 +2276,22 @@ pub fn validate_archive_v2_metadata_exact( limits: ArchiveV2MetadataProjectionLimits, registry_entries: u32, ) -> ReadResult { - if bytes.first() != Some(&0) { - let (normalized, _schema) = normalize_archive_v2_historical_source_metadata_owned(bytes) - .map_err(|_| { - wincode::error::invalid_value( - "transaction metadata is neither one unambiguous current nor legacy record", - ) - })?; - return validate_archive_v2_current_metadata_exact(&normalized, limits, registry_entries); + if bytes.first() == Some(&0) { + return validate_archive_v2_current_metadata_exact(bytes, limits, registry_entries); + } + if archive_v2_historical_source_metadata_can_try_current_only(bytes) + && let Ok(projected) = + validate_archive_v2_current_metadata_exact(bytes, limits, registry_entries) + { + return Ok(projected); } - validate_archive_v2_current_metadata_exact(bytes, limits, registry_entries) + let (normalized, _schema) = normalize_archive_v2_historical_source_metadata_owned(bytes) + .map_err(|_| { + wincode::error::invalid_value( + "transaction metadata is neither one unambiguous current nor legacy record", + ) + })?; + validate_archive_v2_current_metadata_exact(&normalized, limits, registry_entries) } /// Validate one complete current typed-error metadata record. This function @@ -2952,6 +2959,33 @@ mod tests { assert!(projected.has_error); } + #[test] + fn exact_metadata_validation_borrows_unambiguous_current_errors() { + let mut value = metadata(None); + value.err = Some(CompactTransactionError::InstructionError( + 0, + blockzilla_compact::CompactInstructionError::Custom(42), + )); + value.loaded_writable_addresses.clear(); + value.loaded_readonly_addresses.clear(); + let bytes = wincode::config::serialize(&value, wincode_leb128_config()).unwrap(); + assert_eq!(&bytes[..2], &[1, 8]); + let (projected, allocations) = + crate::test_allocations::count_current_thread_allocations(|| { + validate_archive_v2_metadata_exact( + &bytes, + ArchiveV2MetadataProjectionLimits { + total_message_accounts: 3, + top_level_instruction_count: 1, + }, + 100, + ) + .unwrap() + }); + assert!(projected.has_error); + assert_eq!(allocations, 0); + } + #[test] fn exact_metadata_validation_rejects_invalid_references() { let limits = ArchiveV2MetadataProjectionLimits { diff --git a/crates/reader/blockzilla-read-sdk/src/wire_profile.rs b/crates/reader/blockzilla-read-sdk/src/wire_profile.rs index c98c407f..2d152330 100644 --- a/crates/reader/blockzilla-read-sdk/src/wire_profile.rs +++ b/crates/reader/blockzilla-read-sdk/src/wire_profile.rs @@ -12,6 +12,15 @@ use std::{fmt, str::FromStr}; use serde::{Deserialize, Serialize}; +use blockzilla_archive_v2::ARCHIVE_V2_POST_UNKNOWN_FALLBACKS_MARKER_BYTES as POST_UNKNOWN_INSTRUCTION_FALLBACKS_MARKER_BYTES; +pub use blockzilla_archive_v2::{ + ARCHIVE_V2_POST_UNKNOWN_FALLBACKS_MARKER_FILE as POST_UNKNOWN_INSTRUCTION_FALLBACKS_MARKER_FILE, + ARCHIVE_V2_POST_UNKNOWN_FALLBACKS_MARKER_SHA256 as POST_UNKNOWN_INSTRUCTION_FALLBACKS_MARKER_SHA256, +}; + +pub const POST_UNKNOWN_INSTRUCTION_FALLBACKS_MARKER_SIZE: u64 = + POST_UNKNOWN_INSTRUCTION_FALLBACKS_MARKER_BYTES.len() as u64; + use crate::{ Error, Result, manifest::{GenerationFile, GenerationManifest}, @@ -28,18 +37,8 @@ pub const PRE_UNKNOWN_INSTRUCTION_FALLBACKS_MARKER_SIZE: u64 = 87; pub const PRE_UNKNOWN_INSTRUCTION_FALLBACKS_MARKER_SHA256: &str = "2a3aa5808085bc7b869c7536508227f19e6b9d9e3f5fb34b65ebda9936bf0206"; -/// Explicit binding for the post-fallback message grammar. New producers -/// should publish this object instead of relying on the legacy no-marker rule. -pub const POST_UNKNOWN_INSTRUCTION_FALLBACKS_MARKER_FILE: &str = - "archive-v2-message-schema-post-unknown-fallbacks-v1.marker"; -pub const POST_UNKNOWN_INSTRUCTION_FALLBACKS_MARKER_SIZE: u64 = 77; -pub const POST_UNKNOWN_INSTRUCTION_FALLBACKS_MARKER_SHA256: &str = - "c870c4b0940b05b7bd18a134fba496c5c376f539ef7668f137112526d5c61edd"; - const PRE_UNKNOWN_INSTRUCTION_FALLBACKS_MARKER_BYTES: &[u8] = include_bytes!("../assets/archive-v2-message-schema-may24-pre-unknown-fallbacks-v1.marker"); -const POST_UNKNOWN_INSTRUCTION_FALLBACKS_MARKER_BYTES: &[u8] = - include_bytes!("../assets/archive-v2-message-schema-post-unknown-fallbacks-v1.marker"); /// Return the exact object bytes a producer must publish for `profile`. ///