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