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};
7pub type FdPubkey = [u8; 32];
12pub type FdSignature = [u8; 64];
13pub type FdBlake3Hash = [u8; 32];
14
15#[derive(Debug, Clone)]
17pub struct BlockParseResult {
18 pub block_hash: [u8; 32], pub block_producer: [u8; 32], pub transactions: Vec<Vec<u8>>, }
22
23#[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
66pub const BLOCK_COMMITMENT_DOMAIN: &[u8] = b"tn-block-commitment";
70
71pub 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
112pub struct BlockParser;
114
115impl BlockParser {
116 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 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 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 Self::verify_header_signature(&header)?;
154 debug!("Block header signature verified successfully");
155
156 let block_hash = Self::compute_block_hash(data)?;
158 debug!("Block hash computed successfully");
159
160 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 Self::verify_block_signature(&block_hash, &footer, &header.body.block_producer)?;
170 debug!("Block signature verified successfully");
171
172 let transactions_data = &data[header_size..footer_start];
174 debug!(
175 "Transaction data section: {} bytes",
176 transactions_data.len()
177 );
178
179 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 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 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 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 fn verify_header_signature(header: &TnBlockHeader) -> Result<(), BlockParseError> {
235 debug!("Starting header signature verification");
236
237 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 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 let body_size = mem::size_of::<TnBlockHeaderBody>();
263
264 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 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 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 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 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 fn parse_header_verified(data: &[u8]) -> Result<TnBlockHeader, BlockParseError> {
327 Self::parse_header(data).map_err(|e| BlockParseError::InvalidBlockStructure(e))
328 }
329
330 fn parse_footer_verified(data: &[u8]) -> Result<TnBlockFooter, BlockParseError> {
332 Self::parse_footer(data).map_err(|e| BlockParseError::InvalidBlockStructure(e))
333 }
334
335 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 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 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 fn parse_transactions(data: &[u8]) -> Result<Vec<Vec<u8>>, String> {
369 let mut transactions = Vec::new();
370 let mut offset = 0;
371
372 while offset < data.len() {
374 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 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 fn try_parse_transaction_at_offset(data: &[u8]) -> Result<(usize, Vec<u8>), String> {
413 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 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 let transaction_data = data[..total_size].to_vec();
432
433 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 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 let sig_start = tx_data.len() - txn_lib::TN_TXN_SIGNATURE_SZ;
449 let signature_bytes = &tx_data[sig_start..];
450
451 let mut sig_array = [0u8; 64];
453 sig_array.copy_from_slice(signature_bytes);
454
455 let signature = tn_signature_to_string(&sig_array);
457
458 debug!("Extracted signature: {}", signature);
459 Ok(signature)
460 }
461
462 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 }
489 }
490 }
491
492 debug!(
493 "Extracted {} unique account addresses from block: {:?}",
494 accounts.len(),
495 accounts
496 );
497 Ok(accounts)
498 }
499
500 fn extract_transaction_accounts(tx_data: &[u8]) -> Result<Vec<String>, BlockParseError> {
503 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 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 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 let header_size = 112;
566 if tx_data.len() > header_size {
567 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 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 let mut transaction_data = vec![0u8; 100];
636 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 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]; 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]; 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 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 block_data[0] = 1; let result = BlockParser::parse_block(&block_data);
701
702 match result {
705 Ok(block_result) => {
706 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 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 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 tx_data[0] = 1; tx_data[2] = 0;
746 tx_data[3] = 0;
747 tx_data[4] = 0;
749 tx_data[5] = 0;
750 tx_data[6] = 0;
752 tx_data[7] = 0;
753
754 let result = BlockParser::try_parse_transaction_at_offset(&tx_data);
756 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 }
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]; let result = BlockParser::parse_transactions(&short_data);
782 assert!(result.is_ok());
783 assert_eq!(result.unwrap().len(), 0); }
785}
786
787#[cfg(test)]
788mod commitment_tests {
789 use super::*;
790 use std::mem;
791
792 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 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 assert_eq!(bytes[6], 0xEF);
850 assert_eq!(bytes[7], 0xBE);
851 assert_eq!(bytes[8], 0xAA);
853 assert_eq!(bytes[39], 0xAA);
854 assert_eq!(&bytes[88..96], &0x1122_3344_5566_7788u64.to_le_bytes());
857 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}