Skip to main content

thru_base/
block_parser.rs

1use crate::tn_public_address::tn_pubkey_to_address_string;
2use crate::tn_signature_encoding::tn_signature_to_string;
3use crate::txn_lib::{self, Transaction, WireTxnHdrV1};
4use blake3;
5use std::{collections::HashSet, mem};
6use tracing::{debug, error, warn};
7// use base64::prelude::*;
8
9
10/// Block format structures (mirror the on-wire block layout defined in C)
11pub type FdPubkey = [u8; 32];
12pub type FdSignature = [u8; 64];
13pub type FdBlake3Hash = [u8; 32];
14
15/// Result structure for block parsing with cryptographic verification
16#[derive(Debug, Clone)]
17pub struct BlockParseResult {
18    pub block_hash: [u8; 32],       // 256-bit Blake3 hash (first 32 bytes)
19    pub block_producer: [u8; 32],   // Block producer's public key
20    pub transactions: Vec<Vec<u8>>, // Existing transaction data
21}
22
23/// Comprehensive error handling for block parsing and cryptographic verification
24#[derive(Debug, thiserror::Error)]
25pub enum BlockParseError {
26    #[error("Invalid block structure: {0}")]
27    InvalidBlockStructure(String),
28    #[error("Blake3 hash computation failed: {0}")]
29    HashComputationFailed(String),
30    #[error("Header signature verification failed: {0}")]
31    HeaderSignatureInvalid(String),
32    #[error("Block signature verification failed: {0}")]
33    BlockSignatureInvalid(String),
34    #[error("Ed25519 key error: {0}")]
35    Ed25519KeyError(String),
36    #[error("Account extraction failed: {0}")]
37    AccountExtractionFailed(String),
38}
39
40#[repr(C)]
41#[derive(Clone, Copy, Debug)]
42pub struct TnBlockHeader {
43    pub block_header_sig: FdSignature,
44    pub body: TnBlockHeaderBody,
45}
46
47#[repr(C)]
48#[derive(Clone, Copy, Debug)]
49pub struct TnBlockHeaderBody {
50    pub block_version: u8,
51    pub padding: [u8; 5],
52    pub chain_id: u16,
53    pub block_producer: FdPubkey,
54    pub bond_amount_lock_up: u64,
55    pub expiry_timestamp: u64,
56    pub start_slot: u64,
57    pub expiry_after: u32,
58    pub max_block_size: u32,
59    pub max_compute_units: u64,
60    pub max_state_units: u32,
61    pub reserved: [u8; 4],
62    pub weight_slot: u64,
63    pub block_time_ns: u64,
64}
65
66/// Domain prefix for the block-commitment hash, exactly the 19 bytes of
67/// "tn-block-commitment" with no trailing NUL (matches C
68/// TN_BLOCK_COMMITMENT_DOMAIN).
69pub const BLOCK_COMMITMENT_DOMAIN: &[u8] = b"tn-block-commitment";
70
71/// Compute the canonical block-commitment hash (Reward Check Plan A):
72///
73/// ```text
74/// txn_data_hash = blake3(txn_region)
75/// commitment    = header_body || u64le(txn_region.len()) || txn_data_hash || footer_body
76/// block_hash    = blake3("tn-block-commitment" || commitment)
77/// ```
78///
79/// `header_body` is the verbatim 104-byte serialized header body (excluding the
80/// header signature) and `footer_body` is the verbatim 8-byte serialized footer
81/// body, matching the C `tn_block_commitment_t` byte layout.  This is the single
82/// Rust source of truth shared by the block-builder and stress block-wire paths.
83pub fn compute_commitment_hash(header_body: &[u8], txn_region: &[u8], footer_body: &[u8]) -> [u8; 32] {
84    let txn_data_hash = blake3::hash(txn_region);
85
86    let mut commitment = Vec::with_capacity(header_body.len() + 8 + 32 + footer_body.len());
87    commitment.extend_from_slice(header_body);
88    commitment.extend_from_slice(&(txn_region.len() as u64).to_le_bytes());
89    commitment.extend_from_slice(txn_data_hash.as_bytes());
90    commitment.extend_from_slice(footer_body);
91
92    let mut hasher = blake3::Hasher::new();
93    hasher.update(BLOCK_COMMITMENT_DOMAIN);
94    hasher.update(&commitment);
95    *hasher.finalize().as_bytes()
96}
97
98#[repr(C)]
99#[derive(Clone, Copy, Debug)]
100pub struct TnBlockFooter {
101    pub body: TnBlockFooterBody,
102    pub block_hash: FdBlake3Hash,
103    pub block_sig: FdSignature,
104}
105
106#[repr(C)]
107#[derive(Clone, Copy, Debug)]
108pub struct TnBlockFooterBody {
109    pub attestor_payment: u64,
110}
111
112/// Block parser for extracting transactions from UDS block data
113pub struct BlockParser;
114
115impl BlockParser {
116    /// Parse block data with cryptographic verification and extract transactions
117    pub fn parse_block(data: &[u8]) -> Result<BlockParseResult, BlockParseError> {
118        if data.is_empty() {
119            return Ok(BlockParseResult {
120                block_hash: [0u8; 32],
121                block_producer: [0u8; 32],
122                transactions: Vec::new(),
123            });
124        }
125
126        debug!(
127            "Parsing block data of {} bytes with cryptographic verification",
128            data.len()
129        );
130
131        // Block format: TnBlockHeader + Transactions + TnBlockFooter
132        let header_size = mem::size_of::<TnBlockHeader>();
133        let footer_size = mem::size_of::<TnBlockFooter>();
134
135        if data.len() < header_size + footer_size {
136            return Err(BlockParseError::InvalidBlockStructure(format!(
137                "Block too small: {} bytes, need at least {}",
138                data.len(),
139                header_size + footer_size
140            )));
141        }
142
143        // Parse TnBlockHeader from the beginning
144        let header = Self::parse_header_verified(&data[..header_size])?;
145        debug!(
146            "Parsed block header: version={}, start_slot={}, producer={}",
147            header.body.block_version,
148            header.body.start_slot,
149            tn_pubkey_to_address_string(&header.body.block_producer)
150        );
151
152        // Verify header signature first (fail fast optimization)
153        Self::verify_header_signature(&header)?;
154        debug!("Block header signature verified successfully");
155
156        // Compute block hash (excluding block signature)
157        let block_hash = Self::compute_block_hash(data)?;
158        debug!("Block hash computed successfully");
159
160        // Parse TnBlockFooter from the end
161        let footer_start = data.len() - footer_size;
162        let footer = Self::parse_footer_verified(&data[footer_start..])?;
163        debug!(
164            "Parsed block footer: attestor_payment={}",
165            footer.body.attestor_payment
166        );
167
168        // Verify block signature against computed hash
169        Self::verify_block_signature(&block_hash, &footer, &header.body.block_producer)?;
170        debug!("Block signature verified successfully");
171
172        // Extract transaction data between header and footer
173        let transactions_data = &data[header_size..footer_start];
174        debug!(
175            "Transaction data section: {} bytes",
176            transactions_data.len()
177        );
178
179        // Parse individual transactions from the middle section
180        let transactions = if transactions_data.is_empty() {
181            debug!("No transaction data in block");
182            Vec::new()
183        } else {
184            Self::parse_transactions(transactions_data)
185                .map_err(|e| BlockParseError::InvalidBlockStructure(e))?
186        };
187
188        debug!("Extracted {} transactions from block", transactions.len());
189
190        Ok(BlockParseResult {
191            block_hash,
192            block_producer: header.body.block_producer,
193            transactions,
194        })
195    }
196
197    /// Compute 256-bit Blake3 hash of block data excluding block signature and block hash
198    /// Matches C implementation: fd_blake3_append(&hasher, block_data, block_size - sizeof(fd_signature_t) - BLOCK_HASH_SIZE)
199    fn compute_block_hash(data: &[u8]) -> Result<[u8; 32], BlockParseError> {
200        let footer_size = mem::size_of::<TnBlockFooter>();
201
202        if data.len() < footer_size {
203            return Err(BlockParseError::HashComputationFailed(
204                "Block too small to contain footer".to_string(),
205            ));
206        }
207
208        // Hash all data except the final 64 bytes (block_sig) and 32 bytes (block_hash)
209        // This matches the C implementation which excludes sizeof(fd_signature_t) + BLOCK_HASH_SIZE
210        let sig_size = mem::size_of::<FdSignature>();
211        let hash_size = mem::size_of::<FdBlake3Hash>();
212        let hash_data_end = data.len() - sig_size - hash_size;
213        let hash_data = &data[..hash_data_end];
214
215        debug!(
216            "Computing Blake3 hash over {} bytes (excluding {} byte signature and {} byte hash)",
217            hash_data.len(),
218            sig_size,
219            hash_size
220        );
221
222        // Use Blake3 256-bit output and truncate to 32 bytes
223        let mut hasher = blake3::Hasher::new();
224        hasher.update(hash_data);
225
226        let hash_output = *hasher.finalize().as_bytes();
227
228        debug!("Blake3 hash computation completed successfully");
229        Ok(hash_output)
230    }
231
232    /// Verify block header signature using ed25519
233    /// Matches C implementation: signs/verifies only the header body, not the signature field
234    fn verify_header_signature(header: &TnBlockHeader) -> Result<(), BlockParseError> {
235        debug!("Starting header signature verification");
236
237        // Check if signature is all zeros (unsigned/test data)
238        if header.block_header_sig.iter().all(|&b| b == 0) {
239            debug!("Header signature is all zeros - treating as unsigned block");
240            return Err(BlockParseError::HeaderSignatureInvalid(
241                "Block header is not signed (all-zero signature)".to_string(),
242            ));
243        }
244
245        // Mirror C consensus (src/thru/block/tn_block.c): the block-header body's
246        // padding[5] and reserved[4] fields are part of the signed region and
247        // MUST be zero. A non-zero value would make the C node reject the block
248        // while accepting it here would silently split client and node views.
249        if header.body.padding.iter().any(|&b| b != 0) {
250            return Err(BlockParseError::HeaderSignatureInvalid(
251                "non-zero header body padding".to_string(),
252            ));
253        }
254        if header.body.reserved.iter().any(|&b| b != 0) {
255            return Err(BlockParseError::HeaderSignatureInvalid(
256                "non-zero header body reserved".to_string(),
257            ));
258        }
259
260        // Sign/verify only the header body, excluding the signature field
261        // This matches C implementation: fd_ed25519_verify((uchar const *)&header->body, ...)
262        let body_size = mem::size_of::<TnBlockHeaderBody>();
263
264        // Convert header body to bytes for verification
265        let body_bytes =
266            unsafe { std::slice::from_raw_parts(&header.body as *const _ as *const u8, body_size) };
267
268        debug!(
269            "Verifying header signature over {} bytes of header body data",
270            body_bytes.len()
271        );
272
273        // Verify the header-body signature under the standardized block-header
274        // domain: M = DST_blkhdr ‖ header_body, strict/canonical Ed25519.
275        crate::tn_signature::verify(
276            crate::tn_signature::SignatureDomain::BlockHeader,
277            body_bytes,
278            &header.block_header_sig,
279            &header.body.block_producer,
280        )
281        .map_err(|e| {
282            error!("Header signature verification failed: {}", e);
283            BlockParseError::HeaderSignatureInvalid(format!("Verification failed: {}", e))
284        })?;
285
286        debug!("Header signature verification successful");
287        Ok(())
288    }
289
290    /// Verify block signature against computed hash using producer's public key
291    fn verify_block_signature(
292        block_hash: &[u8; 32],
293        footer: &TnBlockFooter,
294        producer_key: &[u8; 32],
295    ) -> Result<(), BlockParseError> {
296        debug!("Starting block signature verification");
297
298        // Check if signature is all zeros (unsigned/test data)
299        if footer.block_sig.iter().all(|&b| b == 0) {
300            debug!("Block signature is all zeros - treating as unsigned block");
301            return Err(BlockParseError::BlockSignatureInvalid(
302                "Block is not signed (all-zero signature)".to_string(),
303            ));
304        }
305
306        debug!("Verifying block signature against computed hash");
307
308        // Verify the block signature under the standardized block domain:
309        // M = DST_block ‖ block_hash, strict/canonical Ed25519.
310        crate::tn_signature::verify(
311            crate::tn_signature::SignatureDomain::Block,
312            block_hash,
313            &footer.block_sig,
314            producer_key,
315        )
316        .map_err(|e| {
317            error!("Block signature verification failed: {}", e);
318            BlockParseError::BlockSignatureInvalid(format!("Verification failed: {}", e))
319        })?;
320
321        debug!("Block signature verification successful");
322        Ok(())
323    }
324
325    /// Parse block header from data with error conversion
326    fn parse_header_verified(data: &[u8]) -> Result<TnBlockHeader, BlockParseError> {
327        Self::parse_header(data).map_err(|e| BlockParseError::InvalidBlockStructure(e))
328    }
329
330    /// Parse block footer from data with error conversion
331    fn parse_footer_verified(data: &[u8]) -> Result<TnBlockFooter, BlockParseError> {
332        Self::parse_footer(data).map_err(|e| BlockParseError::InvalidBlockStructure(e))
333    }
334
335    /// Parse block header from data
336    fn parse_header(data: &[u8]) -> Result<TnBlockHeader, String> {
337        if data.len() < mem::size_of::<TnBlockHeader>() {
338            return Err("Insufficient data for block header".to_string());
339        }
340
341        // We'll do a simple byte copy since we're dealing with repr(C) structs
342        let header = unsafe { std::ptr::read(data.as_ptr() as *const TnBlockHeader) };
343
344        debug!(
345            "Block header: version={}, producer={:?}",
346            header.body.block_version,
347            tn_pubkey_to_address_string(&header.body.block_producer)
348        );
349        Ok(header)
350    }
351
352    /// Parse block footer from data
353    fn parse_footer(data: &[u8]) -> Result<TnBlockFooter, String> {
354        if data.len() < mem::size_of::<TnBlockFooter>() {
355            return Err("Insufficient data for block footer".to_string());
356        }
357
358        let footer = unsafe { std::ptr::read(data.as_ptr() as *const TnBlockFooter) };
359
360        debug!(
361            "Block footer: attestor_payment={}",
362            footer.body.attestor_payment
363        );
364        Ok(footer)
365    }
366
367    /// Parse transactions from the middle section of block data
368    fn parse_transactions(data: &[u8]) -> Result<Vec<Vec<u8>>, String> {
369        let mut transactions = Vec::new();
370        let mut offset = 0;
371
372        // Parse individual transactions using Transaction::from_wire
373        while offset < data.len() {
374            // Check if we have enough data for the minimum transaction header
375            let wire_header_size = mem::size_of::<WireTxnHdrV1>();
376            if offset + wire_header_size > data.len() {
377                debug!(
378                    "Remaining data too small for transaction header: {} bytes",
379                    data.len() - offset
380                );
381                break;
382            }
383
384            let remaining_data = &data[offset..];
385
386            // Try to parse the transaction using Transaction::from_wire
387            // We need to find the actual transaction size by attempting to parse it
388            match Self::try_parse_transaction_at_offset(remaining_data) {
389                Ok((transaction_size, transaction_data)) => {
390                    transactions.push(transaction_data);
391                    debug!(
392                        "Parsed transaction {} of size {} bytes",
393                        transactions.len(),
394                        transaction_size
395                    );
396                    offset += transaction_size;
397                }
398                Err(parse_error) => {
399                    warn!(
400                        "Failed to parse transaction at offset {}: {}",
401                        offset, parse_error
402                    );
403                    return Err(parse_error);
404                }
405            }
406        }
407
408        Ok(transactions)
409    }
410
411    /// Try to parse a transaction at the given offset, returning the transaction size and data
412    fn try_parse_transaction_at_offset(data: &[u8]) -> Result<(usize, Vec<u8>), String> {
413        // We need to determine the transaction size by parsing the header and variable-length data
414        let wire_header_size = mem::size_of::<WireTxnHdrV1>();
415
416        if data.len() < wire_header_size {
417            return Err("Not enough data for transaction header".to_string());
418        }
419
420        // Calculate total transaction size
421        let total_size = txn_lib::tn_txn_size(data).map_err(|e| e.to_string())?;
422
423        if data.len() < total_size {
424            return Err(format!(
425                "Not enough data for complete transaction: need {} bytes, have {}",
426                total_size,
427                data.len()
428            ));
429        }
430        // Extract the transaction data
431        let transaction_data = data[..total_size].to_vec();
432
433        // Verify the transaction can be parsed with Transaction::from_wire
434        if Transaction::from_wire(&transaction_data).is_none() {
435            return Err("Transaction::from_wire failed to parse transaction".to_string());
436        }
437        Ok((total_size, transaction_data))
438    }
439
440    /// Extract transaction signature from transaction data and convert to ts... format
441    /// The signature is at the END of the transaction (last 64 bytes).
442    pub fn extract_transaction_signature(tx_data: &[u8]) -> Result<String, String> {
443        if tx_data.len() < txn_lib::TN_TXN_SIGNATURE_SZ {
444            return Err("Transaction too short to contain a signature".to_string());
445        }
446
447        // The signature is at the end   of the transaction (last 64 bytes)
448        let sig_start = tx_data.len() - txn_lib::TN_TXN_SIGNATURE_SZ;
449        let signature_bytes = &tx_data[sig_start..];
450
451        // Convert to fixed-size array for signature utilities
452        let mut sig_array = [0u8; 64];
453        sig_array.copy_from_slice(signature_bytes);
454
455        // Convert to ts... format using existing utilities
456        let signature = tn_signature_to_string(&sig_array);
457
458        debug!("Extracted signature: {}", signature);
459        Ok(signature)
460    }
461
462    /// Extract all account mentions from block transactions
463    /// Returns a HashSet of base64-encoded account addresses
464    pub fn extract_account_mentions(
465        transactions: &[Vec<u8>],
466    ) -> Result<HashSet<String>, BlockParseError> {
467        let mut accounts = HashSet::new();
468
469        debug!(
470            "Extracting account mentions from {} transactions",
471            transactions.len()
472        );
473
474        for (i, tx_data) in transactions.iter().enumerate() {
475            match Self::extract_transaction_accounts(tx_data) {
476                Ok(tx_accounts) => {
477                    debug!(
478                        "Transaction {} contains {} account references: {:?}",
479                        i,
480                        tx_accounts.len(),
481                        tx_accounts
482                    );
483                    accounts.extend(tx_accounts);
484                }
485                Err(e) => {
486                    warn!("Failed to extract accounts from transaction {}: {}", i, e);
487                    // Continue processing other transactions
488                }
489            }
490        }
491
492        debug!(
493            "Extracted {} unique account addresses from block: {:?}",
494            accounts.len(),
495            accounts
496        );
497        Ok(accounts)
498    }
499
500    /// Extract account addresses from a single transaction
501    /// Returns ta... formatted account addresses found in the transaction
502    fn extract_transaction_accounts(tx_data: &[u8]) -> Result<Vec<String>, BlockParseError> {
503        // Minimum size: 112-byte header + 64-byte trailing signature = 176 bytes
504        let header_size = 112;
505        let signature_size = txn_lib::TN_TXN_SIGNATURE_SZ;
506        let min_txn_size = header_size + signature_size;
507        if tx_data.len() < min_txn_size {
508            return Err(BlockParseError::AccountExtractionFailed(format!(
509                "Transaction too small: {} bytes, need at least {} (header={}, signature={})",
510                tx_data.len(),
511                min_txn_size,
512                header_size,
513                signature_size
514            )));
515        }
516
517        debug!(
518            "Extracting accounts from transaction of {} bytes",
519            tx_data.len()
520        );
521        let mut accounts = Vec::new();
522
523        // Extract fee_payer_pubkey (offset 48, 32 bytes)
524        let fee_payer_offset = 48;
525        if tx_data.len() >= fee_payer_offset + 32 {
526            let fee_payer_pubkey: [u8; 32] = tx_data[fee_payer_offset..fee_payer_offset + 32]
527                .try_into()
528                .map_err(|_| {
529                    BlockParseError::AccountExtractionFailed(
530                        "Failed to convert fee_payer_pubkey to [u8; 32]".to_string(),
531                    )
532                })?;
533            let fee_payer_address = tn_pubkey_to_address_string(&fee_payer_pubkey);
534            debug!(
535                "Extracted fee_payer at offset {}: {:?} -> {}",
536                fee_payer_offset,
537                &fee_payer_pubkey[..8],
538                fee_payer_address
539            );
540            accounts.push(fee_payer_address);
541        }
542
543        // Extract program_pubkey (offset 80, 32 bytes)
544        let program_offset = 80;
545        if tx_data.len() >= program_offset + 32 {
546            let program_pubkey: [u8; 32] = tx_data[program_offset..program_offset + 32]
547                .try_into()
548                .map_err(|_| {
549                    BlockParseError::AccountExtractionFailed(
550                        "Failed to convert program_pubkey to [u8; 32]".to_string(),
551                    )
552                })?;
553            let program_address = tn_pubkey_to_address_string(&program_pubkey);
554            debug!(
555                "Extracted program at offset {}: {:?} -> {}",
556                program_offset,
557                &program_pubkey[..8],
558                program_address
559            );
560            accounts.push(program_address);
561        }
562
563        // Extract additional account addresses from variable section
564        // This comes after the fixed header (112 bytes total for WireTxnHdrV1)
565        let header_size = 112;
566        if tx_data.len() > header_size {
567            // Get account counts from header
568            let readwrite_accounts_cnt = u16::from_le_bytes([tx_data[2], tx_data[3]]);
569            let readonly_accounts_cnt = u16::from_le_bytes([tx_data[4], tx_data[5]]);
570
571            debug!(
572                "Transaction has {} readwrite and {} readonly accounts",
573                readwrite_accounts_cnt, readonly_accounts_cnt
574            );
575
576            // Extract additional account addresses (32 bytes each)
577            let additional_accounts_count =
578                (readwrite_accounts_cnt + readonly_accounts_cnt) as usize;
579            let additional_accounts_size = additional_accounts_count * 32;
580
581            if tx_data.len() >= header_size + additional_accounts_size {
582                for i in 0..additional_accounts_count {
583                    let account_offset = header_size + (i * 32);
584                    let account_pubkey: [u8; 32] = tx_data[account_offset..account_offset + 32]
585                        .try_into()
586                        .map_err(|_| {
587                            BlockParseError::AccountExtractionFailed(format!(
588                                "Failed to convert account_pubkey {} to [u8; 32]",
589                                i
590                            ))
591                        })?;
592                    let account_address = tn_pubkey_to_address_string(&account_pubkey);
593                    accounts.push(account_address);
594                }
595            }
596        }
597
598        Ok(accounts)
599    }
600}
601
602#[cfg(test)]
603mod tests {
604    use super::*;
605
606    #[test]
607    fn test_block_header_body_chain_id_layout() {
608        let body = TnBlockHeaderBody {
609            block_version: 1,
610            padding: [0; 5],
611            chain_id: 0x1234,
612            block_producer: [0; 32],
613            bond_amount_lock_up: 0,
614            expiry_timestamp: 0,
615            start_slot: 0,
616            expiry_after: 0,
617            max_block_size: 0,
618            max_compute_units: 0,
619            max_state_units: 0,
620            reserved: [0; 4],
621            weight_slot: 0,
622            block_time_ns: 0,
623        };
624
625        let base = &body as *const _ as usize;
626        let chain_id = &body.chain_id as *const _ as usize;
627        assert_eq!(chain_id - base, 6);
628        assert_eq!(body.chain_id, 0x1234);
629        assert_eq!(std::mem::size_of::<TnBlockHeaderBody>(), 104);
630    }
631
632    #[test]
633    fn test_extract_transaction_signature() {
634        // Create a mock transaction with 64 bytes of signature data at the END
635        let mut transaction_data = vec![0u8; 100];
636        // Set some recognizable pattern in the signature bytes (last 64 bytes)
637        let sig_start = transaction_data.len() - 64;
638        for i in 0..64 {
639            transaction_data[sig_start + i] = (i % 256) as u8;
640        }
641
642        let result = BlockParser::extract_transaction_signature(&transaction_data);
643        assert!(result.is_ok());
644
645        let signature = result.unwrap();
646        assert!(!signature.is_empty());
647        // Verify it's in ts... format (90 characters starting with "ts")
648        assert_eq!(
649            signature.len(),
650            90,
651            "Signature should be 90 characters in ts... format"
652        );
653        assert!(
654            signature.starts_with("ts"),
655            "Signature should start with 'ts'"
656        );
657    }
658
659    #[test]
660    fn test_extract_transaction_signature_too_short() {
661        let transaction_data = vec![0u8; 32]; // Too short
662        let result = BlockParser::extract_transaction_signature(&transaction_data);
663        assert!(result.is_err());
664        assert_eq!(
665            result.unwrap_err(),
666            "Transaction too short to contain a signature"
667        );
668    }
669
670    #[test]
671    fn test_parse_empty_block() {
672        let empty_data = vec![];
673        let result = BlockParser::parse_block(&empty_data);
674        assert!(result.is_ok());
675        let block_result = result.unwrap();
676        assert_eq!(block_result.transactions.len(), 0);
677        assert_eq!(block_result.block_hash, [0u8; 32]);
678        assert_eq!(block_result.block_producer, [0u8; 32]);
679    }
680
681    #[test]
682    fn test_parse_block_too_small() {
683        let small_data = vec![0u8; 50]; // Too small for header + footer
684        let result = BlockParser::parse_block(&small_data);
685        assert!(result.is_err());
686        let error_msg = format!("{}", result.unwrap_err());
687        assert!(error_msg.contains("Block too small"));
688    }
689
690    #[test]
691    fn test_parse_block_header_footer_only() {
692        // Test with a block that has valid structure but invalid signatures
693        let header_size = std::mem::size_of::<TnBlockHeader>();
694        let footer_size = std::mem::size_of::<TnBlockFooter>();
695        let mut block_data = vec![0u8; header_size + footer_size];
696
697        // Set block version in header
698        block_data[0] = 1; // block_version
699
700        let result = BlockParser::parse_block(&block_data);
701
702        // The result depends on whether all-zero signatures are considered valid
703        // Let's test both cases and verify we get a reasonable result
704        match result {
705            Ok(block_result) => {
706                // If it succeeds, verify the structure is correct
707                assert_eq!(block_result.transactions.len(), 0);
708                assert_eq!(block_result.block_producer, [0u8; 32]);
709                assert_eq!(block_result.block_hash.len(), 32);
710            }
711            Err(error) => {
712                // If it fails, it should be due to cryptographic verification
713                let error_msg = format!("{}", error);
714                assert!(
715                    error_msg.contains("signature")
716                        || error_msg.contains("key")
717                        || error_msg.contains("Invalid")
718                );
719            }
720        }
721    }
722
723    #[test]
724    fn test_try_parse_transaction_at_offset() {
725        // Create a minimal valid transaction structure for testing
726        // wire format: 112-byte header (no signature prefix) + 64-byte trailing signature
727        // Transaction layout:
728        //   [0,1)   transaction_version
729        //   [1,2)   flags
730        //   [2,4)   readwrite_accounts_cnt
731        //   [4,6)   readonly_accounts_cnt
732        //   [6,8)   instr_data_sz
733        //   ... other fields ...
734        //   [last 64 bytes] signature at END
735        let header_size = 112;
736        let signature_size = 64;
737        let min_txn_size = header_size + signature_size;
738        let mut tx_data = vec![0u8; min_txn_size];
739
740        // Set transaction version to 1 at offset 0 (no signature prefix in new format)
741        tx_data[0] = 1; // transaction_version
742
743        // Set all account counts and instruction size to 0 (minimal transaction)
744        // readwrite_accounts_cnt at offset 2-3
745        tx_data[2] = 0;
746        tx_data[3] = 0;
747        // readonly_accounts_cnt at offset 4-5
748        tx_data[4] = 0;
749        tx_data[5] = 0;
750        // instr_data_sz at offset 6-7
751        tx_data[6] = 0;
752        tx_data[7] = 0;
753
754        // Test the helper function directly
755        let result = BlockParser::try_parse_transaction_at_offset(&tx_data);
756        // This might fail due to Transaction::from_wire validation, which is expected
757        // The important thing is that the function doesn't panic and handles the data correctly
758        match result {
759            Ok((size, data)) => {
760                assert_eq!(size, min_txn_size);
761                assert_eq!(data.len(), min_txn_size);
762            }
763            Err(_) => {
764                // This is expected for invalid transaction data
765                // The test verifies the function handles invalid data gracefully
766            }
767        }
768    }
769
770    #[test]
771    fn test_parse_transactions_empty_data() {
772        let empty_data = vec![];
773        let result = BlockParser::parse_transactions(&empty_data);
774        assert!(result.is_ok());
775        assert_eq!(result.unwrap().len(), 0);
776    }
777
778    #[test]
779    fn test_parse_transactions_insufficient_data() {
780        let short_data = vec![0u8; 32]; // Too short for transaction header
781        let result = BlockParser::parse_transactions(&short_data);
782        assert!(result.is_ok());
783        assert_eq!(result.unwrap().len(), 0); // Should return empty list, not error
784    }
785}
786
787#[cfg(test)]
788mod commitment_tests {
789    use super::*;
790    use std::mem;
791
792    /// Canonical commitment-hash fixture, computed by the C reference (fd_blake3)
793    /// and verified byte-for-byte against the SDK BLAKE3 port.  C, Go, and Rust
794    /// must all produce this value (Reward Check Plan A).
795    const CANONICAL_TXN_DATA_HASH: &str =
796        "1bfa6706ab80c3557f525aba41900ecf793737dde6c18b6d62dc480de67597eb";
797    const CANONICAL_COMMITMENT_HASH: &str =
798        "d19fd7b41d7a525e744c17802f422dafae3a275fb2c1f2b799af073406008b55";
799
800    fn fixture() -> (Vec<u8>, Vec<u8>, Vec<u8>) {
801        let header_body: Vec<u8> = (0..104u32).map(|i| ((i * 7 + 1) & 0xff) as u8).collect();
802        let txn_region: Vec<u8> = (0..50u32).map(|i| ((i * 3 + 5) & 0xff) as u8).collect();
803        let footer_body = 4242u64.to_le_bytes().to_vec();
804        (header_body, txn_region, footer_body)
805    }
806
807    #[test]
808    fn commitment_hash_matches_canonical_vector() {
809        let (header_body, txn_region, footer_body) = fixture();
810
811        let txn_data_hash = blake3::hash(&txn_region);
812        assert_eq!(hex::encode(txn_data_hash.as_bytes()), CANONICAL_TXN_DATA_HASH);
813
814        let h = compute_commitment_hash(&header_body, &txn_region, &footer_body);
815        assert_eq!(hex::encode(h), CANONICAL_COMMITMENT_HASH);
816    }
817
818    #[test]
819    fn commitment_domain_has_no_trailing_nul() {
820        assert_eq!(BLOCK_COMMITMENT_DOMAIN.len(), 19);
821        assert_eq!(BLOCK_COMMITMENT_DOMAIN, b"tn-block-commitment");
822    }
823
824    #[test]
825    fn header_body_layout_matches_c() {
826        // sizeof(tn_block_header_body_t) == 104.
827        assert_eq!(mem::size_of::<TnBlockHeaderBody>(), 104);
828
829        let body = TnBlockHeaderBody {
830            block_version: 1,
831            padding: [0u8; 5],
832            chain_id: 0xBEEF,
833            block_producer: [0xAA; 32],
834            bond_amount_lock_up: 0,
835            expiry_timestamp: 0,
836            start_slot: 0,
837            expiry_after: 0,
838            max_block_size: 0,
839            max_compute_units: 0,
840            max_state_units: 0,
841            reserved: [0u8; 4],
842            weight_slot: 0x1122_3344_5566_7788,
843            block_time_ns: 0x99AA_BBCC_DDEE_FF00,
844        };
845        let bytes = unsafe {
846            std::slice::from_raw_parts(&body as *const _ as *const u8, mem::size_of::<TnBlockHeaderBody>())
847        };
848        // chain_id is little-endian at offset 6.
849        assert_eq!(bytes[6], 0xEF);
850        assert_eq!(bytes[7], 0xBE);
851        // block_producer starts at offset 8.
852        assert_eq!(bytes[8], 0xAA);
853        assert_eq!(bytes[39], 0xAA);
854        // weight_slot (offset 88, TN_BLOCK_HEADER_BODY_OFF_WEIGHT_SLOT) — the
855        // offset the on-chain validator memcpy's for the weight lookup.
856        assert_eq!(&bytes[88..96], &0x1122_3344_5566_7788u64.to_le_bytes());
857        // block_time_ns (offset 96) pins the tail boundary so a reserved-size
858        // change can't silently shift weight_slot.
859        assert_eq!(&bytes[96..104], &0x99AA_BBCC_DDEE_FF00u64.to_le_bytes());
860    }
861
862    #[test]
863    fn mutating_attestor_payment_changes_hash() {
864        let (header_body, txn_region, footer_body) = fixture();
865        let a = compute_commitment_hash(&header_body, &txn_region, &footer_body);
866        let mut footer2 = footer_body.clone();
867        footer2[0] ^= 0xFF;
868        let b = compute_commitment_hash(&header_body, &txn_region, &footer2);
869        assert_ne!(a, b);
870    }
871}