Skip to main content

thru_base/
txn_lib.rs

1//! Transaction library: normal Rust struct, signing, serialization, accessors
2//!
3
4pub type TnPubkey = [u8; 32];
5pub type TnHash = [u8; 32];
6pub type TnSignature = [u8; 64];
7
8use crate::{
9    tn_signature::{sign_transaction, verify_transaction},
10    tn_state_proof::StateProof,
11    StateProofType,
12};
13use bytemuck::{bytes_of, pod_read_unaligned, Pod, Zeroable};
14
15pub const TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT: u8 = 0; // Bit position (matching C #define TN_TXN_FLAG_HAS_FEE_PAYER_PROOF (0U))
16pub const TN_TXN_FLAG_MAY_COMPRESS_ACCOUNT_BIT: u8 = 1; // Bit position (matching C #define TN_TXN_FLAG_MAY_COMPRESS_ACCOUNT (1U))
17
18// State proof type constants (matching C implementation)
19pub const TN_STATE_PROOF_TYPE_EXISTING: u64 = 0x0;
20pub const TN_STATE_PROOF_TYPE_UPDATING: u64 = 0x1;
21pub const TN_STATE_PROOF_TYPE_CREATION: u64 = 0x2;
22
23// State proof header size constants
24pub const TN_STATE_PROOF_HDR_SIZE: usize = 40; // 8 bytes type_slot + 32 bytes path_bitset
25pub const TN_ACCOUNT_META_FOOTPRINT: usize = 64; // Size of tn_account_meta_t (matching C sizeof)
26
27// TEMPORARY: Minimal local RpcError for test pass (remove when shared error type is available)
28#[derive(Debug, PartialEq)]
29pub enum RpcError {
30    InvalidTransactionSize { size: usize, max_size: usize },
31    TrailingBytes { expected: usize, found: usize },
32    TooManyAccounts { count: usize, max_count: usize },
33    InvalidTransactionSignature,
34    InvalidParams(&'static str),
35    InvalidFormat,
36    InvalidVersion,
37    InvalidFlags,
38    InvalidFeePayerStateProofType,
39    InvalidChainId,
40    DuplicateAccount,
41    UnsortedReadwriteAccounts,
42    UnsortedReadonlyAccounts,
43}
44
45impl std::fmt::Display for RpcError {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        match self {
48            RpcError::InvalidTransactionSize { size, max_size } => {
49                write!(
50                    f,
51                    "Transaction size {} exceeds maximum allowed size {}",
52                    size, max_size
53                )
54            }
55            RpcError::TrailingBytes { expected, found } => {
56                write!(
57                    f,
58                    "Transaction has trailing bytes: expected {} bytes, found {} bytes",
59                    expected, found
60                )
61            }
62            RpcError::TooManyAccounts { count, max_count } => {
63                write!(
64                    f,
65                    "Too many accounts: {} exceeds maximum {}",
66                    count, max_count
67                )
68            }
69            RpcError::InvalidTransactionSignature => {
70                write!(f, "Invalid transaction signature")
71            }
72            RpcError::InvalidParams(msg) => {
73                write!(f, "Invalid parameters: {}", msg)
74            }
75            RpcError::InvalidFormat => {
76                write!(f, "Invalid transaction format")
77            }
78            RpcError::InvalidVersion => {
79                write!(f, "Invalid transaction version")
80            }
81            RpcError::InvalidFlags => {
82                write!(f, "Invalid transaction flags")
83            }
84            RpcError::InvalidFeePayerStateProofType => {
85                write!(f, "Invalid fee payer state proof type")
86            }
87            RpcError::InvalidChainId => {
88                write!(f, "Invalid chain ID: chain_id cannot be zero")
89            }
90            RpcError::DuplicateAccount => {
91                write!(f, "Duplicate account in transaction")
92            }
93            RpcError::UnsortedReadwriteAccounts => {
94                write!(f, "Read-write accounts are not strictly ascending")
95            }
96            RpcError::UnsortedReadonlyAccounts => {
97                write!(f, "Read-only accounts are not strictly ascending")
98            }
99        }
100    }
101}
102
103impl std::error::Error for RpcError {}
104
105impl RpcError {
106    pub fn invalid_transaction_size(size: usize, max_size: usize) -> Self {
107        Self::InvalidTransactionSize { size, max_size }
108    }
109    pub fn trailing_bytes(expected: usize, found: usize) -> Self {
110        Self::TrailingBytes { expected, found }
111    }
112    pub fn too_many_accounts(count: usize, max_count: usize) -> Self {
113        Self::TooManyAccounts { count, max_count }
114    }
115    pub fn invalid_transaction_signature() -> Self {
116        Self::InvalidTransactionSignature
117    }
118    pub fn invalid_params(msg: &'static str) -> Self {
119        Self::InvalidParams(msg)
120    }
121    pub fn invalid_format() -> Self {
122        Self::InvalidFormat
123    }
124    pub fn invalid_version() -> Self {
125        Self::InvalidVersion
126    }
127    pub fn invalid_flags() -> Self {
128        Self::InvalidFlags
129    }
130    pub fn invalid_fee_payer_state_proof_type() -> Self {
131        Self::InvalidFeePayerStateProofType
132    }
133    pub fn invalid_chain_id() -> Self {
134        Self::InvalidChainId
135    }
136    pub fn duplicate_account() -> Self {
137        Self::DuplicateAccount
138    }
139    pub fn unsorted_readwrite_accounts() -> Self {
140        Self::UnsortedReadwriteAccounts
141    }
142    pub fn unsorted_readonly_accounts() -> Self {
143        Self::UnsortedReadonlyAccounts
144    }
145}
146
147/// On-wire transaction header (matches TnTxnHdrV1 layout)
148///
149/// Transaction wire format:
150///   [header (112 bytes)]
151///   [input_pubkeys (variable)]
152///   [instr_data (variable)]
153///   [state_proof (optional)]
154///   [account_meta (optional)]
155///   [fee_payer_signature (64 bytes)]
156#[repr(C)]
157#[derive(Clone, Copy, Debug)]
158pub struct WireTxnHdrV1 {
159    pub transaction_version: u8,
160    pub flags: u8,
161    pub readwrite_accounts_cnt: u16,
162    pub readonly_accounts_cnt: u16,
163    pub instr_data_sz: u16,
164    pub req_compute_units: u32,
165    pub req_state_units: u16,
166    pub req_memory_units: u16,
167    pub fee: u64,
168    pub nonce: u64,
169    pub start_slot: u64,
170    pub expiry_after: u32,
171    pub chain_id: u16,
172    pub padding_0: [u8; 2],
173    pub fee_payer_pubkey: [u8; 32],
174    pub program_pubkey: [u8; 32],
175}
176
177/// Size of the signature in bytes (always at end of transaction)
178pub const TN_TXN_SIGNATURE_SZ: usize = 64;
179pub const TN_TXN_MAX_ACCOUNTS: usize = 1024;
180
181impl Default for WireTxnHdrV1 {
182    fn default() -> Self {
183        Self {
184            transaction_version: 0,
185            flags: 0,
186            readwrite_accounts_cnt: 0,
187            readonly_accounts_cnt: 0,
188            instr_data_sz: 0,
189            req_compute_units: 0,
190            req_state_units: 0,
191            req_memory_units: 0,
192            fee: 0,
193            nonce: 0,
194            start_slot: 0,
195            expiry_after: 0,
196            chain_id: 0,
197            padding_0: [0u8; 2],
198            fee_payer_pubkey: [0u8; 32],
199            program_pubkey: [0u8; 32],
200        }
201    }
202}
203
204// Manual Pod implementation to avoid derive issues
205unsafe impl Pod for WireTxnHdrV1 {}
206unsafe impl Zeroable for WireTxnHdrV1 {}
207
208/// Normal Rust struct for transaction construction
209#[derive(Clone, Debug)]
210pub struct Transaction {
211    // Core transaction fields
212    pub fee_payer: TnPubkey, // [u8; 32] - who pays the fee
213    pub program: TnPubkey,   // [u8; 32] - target program
214
215    // Account lists (optional)
216    pub rw_accs: Option<Vec<TnPubkey>>, // read-write accounts
217    pub r_accs: Option<Vec<TnPubkey>>,  // read-only accounts
218
219    // Instruction data (optional)
220    pub instructions: Option<Vec<u8>>, // instruction bytes
221
222    // Transaction parameters
223    pub fee: u64,               // transaction fee
224    pub req_compute_units: u32, // requested compute units
225    pub req_state_units: u16,   // requested state units
226    pub req_memory_units: u16,  // requested memory units
227    pub expiry_after: u32,      // expiry time offset
228    pub start_slot: u64,        // starting slot
229    pub nonce: u64,             // transaction nonce
230    pub flags: u8,              // transaction flags
231    pub chain_id: u16,          // chain identifier (must be non-zero)
232
233    // Signature (optional until signed)
234    pub signature: Option<TnSignature>, // [u8; 64] - Ed25519 signature
235
236    // Fee payer state proof (optional)
237    pub fee_payer_state_proof: Option<StateProof>, // State proof for fee payer account
238
239    pub fee_payer_account_meta_raw: Option<Vec<u8>>,
240}
241
242impl Default for Transaction {
243    fn default() -> Self {
244        Self {
245            chain_id: 0,
246            ..Self::new([0; 32], [0; 32], 0, 0)
247        }
248    }
249}
250
251impl Transaction {
252    /// Create a new unsigned transaction
253    pub fn new(fee_payer: TnPubkey, program: TnPubkey, fee: u64, nonce: u64) -> Self {
254        Self {
255            fee_payer,
256            program,
257            rw_accs: None,
258            r_accs: None,
259            instructions: None,
260            fee,
261            req_compute_units: 0,
262            req_state_units: 1,
263            req_memory_units: 0,
264            expiry_after: 0,
265            start_slot: 0,
266            nonce,
267            flags: 0,
268            chain_id: 1,
269            signature: None,
270            fee_payer_state_proof: None,
271            fee_payer_account_meta_raw: None,
272        }
273    }
274
275    /// Create a minimal transaction with just a program ID and instruction data.
276    /// Used for fake event transactions that don't need accounts or fees.
277    pub fn new_raw_instruction(
278        fee_payer: &TnPubkey,
279        program: &TnPubkey,
280        instruction_data: &[u8],
281    ) -> Result<Self, Box<dyn std::error::Error>> {
282        Ok(Self {
283            fee_payer: *fee_payer,
284            program: *program,
285            rw_accs: None,
286            r_accs: None,
287            instructions: Some(instruction_data.to_vec()),
288            fee: 0,
289            req_compute_units: 0,
290            req_state_units: 0,
291            req_memory_units: 0,
292            expiry_after: 0,
293            start_slot: 0,
294            nonce: 0,
295            flags: 0,
296            chain_id: 1,
297            signature: None,
298            fee_payer_state_proof: None,
299            fee_payer_account_meta_raw: None,
300        })
301    }
302
303    pub fn has_fee_payer_state_proof(&self) -> bool {
304        (self.flags & (1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT)) != 0
305    }
306    pub fn may_compress_account(&self) -> bool {
307        (self.flags & (1 << TN_TXN_FLAG_MAY_COMPRESS_ACCOUNT_BIT)) != 0
308    }
309
310    pub fn get_signature(&self) -> Option<crate::Signature> {
311        if let Some(sig) = &self.signature {
312            return Some(crate::Signature::from_bytes(&sig));
313        }
314        None
315    }
316
317    pub fn with_may_compress_account(mut self) -> Self {
318        self.flags |= 1 << TN_TXN_FLAG_MAY_COMPRESS_ACCOUNT_BIT;
319        self
320    }
321
322    /// Builder method: set fee payer state proof
323    pub fn with_fee_payer_state_proof(mut self, state_proof: &StateProof) -> Self {
324        self.fee_payer_state_proof = Some(state_proof.clone());
325        // Set the flag bit to indicate presence of state proof
326        self.flags |= 1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT;
327        self
328    }
329
330    /// Builder method: set fee payer account meta as raw bytes
331    pub fn with_fee_payer_account_meta_raw(mut self, account_meta_raw: Vec<u8>) -> Self {
332        self.fee_payer_account_meta_raw = Some(account_meta_raw);
333        self
334    }
335
336    /// Builder method: remove fee payer state proof
337    pub fn without_fee_payer_state_proof(mut self) -> Self {
338        self.fee_payer_state_proof = None;
339        // Clear the flag bit to indicate absence of state proof
340        self.flags &= !(1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT);
341        self
342    }
343
344    /// Builder method: add read-write accounts
345    pub fn with_rw_accounts(mut self, accounts: Vec<TnPubkey>) -> Self {
346        self.rw_accs = Some(accounts);
347        self
348    }
349
350    /// Builder method: add read-only accounts
351    pub fn with_r_accounts(mut self, accounts: Vec<TnPubkey>) -> Self {
352        self.r_accs = Some(accounts);
353        self
354    }
355
356    /// Builder method: add a single read-write account
357    pub fn add_rw_account(mut self, account: TnPubkey) -> Self {
358        match self.rw_accs {
359            Some(ref mut accounts) => accounts.push(account),
360            None => self.rw_accs = Some(vec![account]),
361        }
362        self
363    }
364
365    /// Builder method: add a single read-only account
366    pub fn add_r_account(mut self, account: TnPubkey) -> Self {
367        match self.r_accs {
368            Some(ref mut accounts) => accounts.push(account),
369            None => self.r_accs = Some(vec![account]),
370        }
371        self
372    }
373
374    /// Builder method: add instruction data
375    pub fn with_instructions(mut self, instructions: Vec<u8>) -> Self {
376        self.instructions = Some(instructions);
377        self
378    }
379
380    /// Builder method: set compute units
381    pub fn with_compute_units(mut self, units: u32) -> Self {
382        self.req_compute_units = units;
383        self
384    }
385
386    /// Builder method: set state units
387    pub fn with_state_units(mut self, units: u16) -> Self {
388        self.req_state_units = units;
389        self
390    }
391
392    /// Builder method: set memory units
393    pub fn with_memory_units(mut self, units: u16) -> Self {
394        self.req_memory_units = units;
395        self
396    }
397
398    /// Builder method: set expiry
399    pub fn with_expiry_after(mut self, expiry: u32) -> Self {
400        self.expiry_after = expiry;
401        self
402    }
403
404    /// Builder method: set nonce
405    pub fn with_nonce(mut self, nonce: u64) -> Self {
406        self.nonce = nonce;
407        self
408    }
409
410    /// Builder method: set start slot
411    pub fn with_start_slot(mut self, slot: u64) -> Self {
412        self.start_slot = slot;
413        self
414    }
415
416    /// Builder method: set chain ID
417    pub fn with_chain_id(mut self, chain_id: u16) -> Self {
418        self.chain_id = chain_id;
419        self
420    }
421
422    /// Sign the transaction with a 32-byte Ed25519 private key.
423    /// Validates the account layout first, so a transaction with duplicate,
424    /// unsorted, or too-many accounts is rejected before signing.
425    pub fn sign(&mut self, private_key: &[u8; 32]) -> Result<(), Box<dyn std::error::Error>> {
426        self.validate()
427            .map_err(|e| Box::<dyn std::error::Error>::from(e))?;
428        self.sign_unchecked(private_key)
429    }
430
431    /// Sign WITHOUT validating the account layout. Intended for constructing
432    /// intentionally-invalid transactions (e.g. negative tests that submit a
433    /// malformed txn and expect the server to reject it). Production callers
434    /// should use `sign`, which validates first.
435    pub fn sign_unchecked(
436        &mut self,
437        private_key: &[u8; 32],
438    ) -> Result<(), Box<dyn std::error::Error>> {
439        let wire_bytes = self.to_wire_for_signing();
440        let sig = sign_transaction(&wire_bytes, &self.fee_payer, private_key)
441            .map_err(|e| Box::<dyn std::error::Error>::from(e))?;
442        self.signature = Some(sig);
443        Ok(())
444    }
445
446    /// Validate account count and duplicate-account rules before signing or serialization.
447    pub fn validate(&self) -> Result<(), RpcError> {
448        let rw_accs = self.rw_accs.as_deref().unwrap_or(&[]);
449        let r_accs = self.r_accs.as_deref().unwrap_or(&[]);
450        validate_account_layout(rw_accs, r_accs, &self.fee_payer, &self.program)
451    }
452
453    /// Verify the transaction signature
454    pub fn verify(&self) -> bool {
455        if let Some(sig_bytes) = &self.signature {
456            let wire_bytes = self.to_wire_for_signing();
457            return verify_transaction(&wire_bytes, sig_bytes, &self.fee_payer).is_ok();
458        }
459        false
460    }
461
462    /// Create wire format for signing (excluding trailing signature)
463    /// The message is: header + accounts + instr_data + state_proof + account_meta
464    fn to_wire_for_signing(&self) -> Vec<u8> {
465        // Zero out all bytes first to ensure deterministic padding
466        let mut wire: WireTxnHdrV1 = unsafe { core::mem::zeroed() };
467        wire.transaction_version = 1;
468        wire.flags = self.flags;
469        wire.readwrite_accounts_cnt = self.rw_accs.as_ref().map_or(0, |v| v.len() as u16);
470        wire.readonly_accounts_cnt = self.r_accs.as_ref().map_or(0, |v| v.len() as u16);
471        wire.instr_data_sz = self.instructions.as_ref().map_or(0, |v| v.len() as u16);
472        wire.req_compute_units = self.req_compute_units;
473        wire.req_state_units = self.req_state_units;
474        wire.req_memory_units = self.req_memory_units;
475        wire.expiry_after = self.expiry_after;
476        wire.chain_id = self.chain_id;
477        wire.fee = self.fee;
478        wire.nonce = self.nonce;
479        wire.start_slot = self.start_slot;
480        wire.fee_payer_pubkey = self.fee_payer;
481        wire.program_pubkey = self.program;
482
483        let mut result = bytes_of(&wire).to_vec();
484
485        // Append variable-length data
486        if let Some(ref rw_accs) = self.rw_accs {
487            for acc in rw_accs {
488                result.extend_from_slice(acc);
489            }
490        }
491
492        if let Some(ref r_accs) = self.r_accs {
493            for acc in r_accs {
494                result.extend_from_slice(acc);
495            }
496        }
497
498        if let Some(ref instructions) = self.instructions {
499            result.extend_from_slice(instructions);
500        }
501
502        // Append state proof if present
503        if let Some(ref state_proof) = self.fee_payer_state_proof {
504            result.extend_from_slice(&state_proof.to_wire());
505        }
506
507        // Use raw account meta if available, otherwise use structured account meta
508        if let Some(ref fee_payer_account_meta_raw) = self.fee_payer_account_meta_raw {
509            result.extend_from_slice(fee_payer_account_meta_raw);
510        }
511
512        result
513    }
514
515    /// Serialize to on-wire format (WireTxnHdrV1).
516    /// Wire format: header + accounts + instr_data + state_proof + account_meta + signature
517    ///
518    /// This is INFALLIBLE and does NOT validate account layout: it must remain
519    /// usable for re-serializing transactions that were ingested from the
520    /// network/block store (which may predate, or otherwise violate, the
521    /// duplicate-account rules — e.g. a stored poison transaction served via
522    /// getTransactionRaw). Validation is enforced at the construction boundary
523    /// (`sign`) and is available explicitly via `try_to_wire`.
524    pub fn to_wire(&self) -> Vec<u8> {
525        self.serialize_wire()
526    }
527
528    /// Fallible serialization: validate account layout, then serialize.
529    /// Use this for newly-built transactions that must satisfy the
530    /// duplicate/sort/count rules before going on the wire.
531    pub fn try_to_wire(&self) -> Result<Vec<u8>, RpcError> {
532        self.validate()?;
533        Ok(self.serialize_wire())
534    }
535
536    /// Internal: pure serialization with no validation.
537    fn serialize_wire(&self) -> Vec<u8> {
538        let mut wire = WireTxnHdrV1::default();
539        wire.transaction_version = 1;
540        wire.flags = self.flags;
541        wire.readwrite_accounts_cnt = self.rw_accs.as_ref().map_or(0, |v| v.len() as u16);
542        wire.readonly_accounts_cnt = self.r_accs.as_ref().map_or(0, |v| v.len() as u16);
543        wire.instr_data_sz = self.instructions.as_ref().map_or(0, |v| v.len() as u16);
544        wire.req_compute_units = self.req_compute_units;
545        wire.req_state_units = self.req_state_units;
546        wire.req_memory_units = self.req_memory_units;
547        wire.expiry_after = self.expiry_after;
548        wire.chain_id = self.chain_id;
549        wire.fee = self.fee;
550        wire.nonce = self.nonce;
551        wire.start_slot = self.start_slot;
552        wire.fee_payer_pubkey = self.fee_payer;
553        wire.program_pubkey = self.program;
554
555        let mut result = bytes_of(&wire).to_vec();
556
557        // Append variable-length data
558        if let Some(ref rw_accs) = self.rw_accs {
559            for acc in rw_accs {
560                result.extend_from_slice(acc);
561            }
562        }
563
564        if let Some(ref r_accs) = self.r_accs {
565            for acc in r_accs {
566                result.extend_from_slice(acc);
567            }
568        }
569
570        if let Some(ref instructions) = self.instructions {
571            result.extend_from_slice(instructions);
572        }
573
574        // Append state proof if present (after instruction data)
575        if let Some(ref state_proof) = self.fee_payer_state_proof {
576            result.extend_from_slice(&state_proof.to_wire());
577        }
578
579        // Use raw account meta if available, otherwise use structured account meta
580        if let Some(ref fee_payer_account_meta_raw) = self.fee_payer_account_meta_raw {
581            result.extend_from_slice(fee_payer_account_meta_raw);
582        }
583
584        // Append signature at the END (last 64 bytes)
585        if let Some(sig) = &self.signature {
586            result.extend_from_slice(sig);
587        } else {
588            // Zero signature if not set
589            result.extend_from_slice(&[0u8; TN_TXN_SIGNATURE_SZ]);
590        }
591
592        result
593    }
594
595    /// Deserialize from on-wire format (WireTxnHdrV1)
596    /// Wire format: header + accounts + instr_data + state_proof + account_meta + signature (at end)
597    pub fn from_wire(bytes: &[u8]) -> Option<Self> {
598        // Minimum size: header + signature at end
599        if bytes.len() < core::mem::size_of::<WireTxnHdrV1>() + TN_TXN_SIGNATURE_SZ {
600            return None;
601        }
602
603        let wire: WireTxnHdrV1 =
604            pod_read_unaligned(&bytes[0..core::mem::size_of::<WireTxnHdrV1>()]);
605        let mut offset = core::mem::size_of::<WireTxnHdrV1>();
606
607        let sig_start = bytes.len() - TN_TXN_SIGNATURE_SZ;
608        let mut signature = [0u8; TN_TXN_SIGNATURE_SZ];
609        signature.copy_from_slice(&bytes[sig_start..]);
610
611        // Parse read-write accounts
612        let rw_accs = if wire.readwrite_accounts_cnt > 0 {
613            let mut accounts = Vec::new();
614            for _ in 0..wire.readwrite_accounts_cnt {
615                if offset + 32 > sig_start {
616                    return None;
617                }
618                let mut acc = [0u8; 32];
619                acc.copy_from_slice(&bytes[offset..offset + 32]);
620                accounts.push(acc);
621                offset += 32;
622            }
623            Some(accounts)
624        } else {
625            None
626        };
627
628        // Parse read-only accounts
629        let r_accs = if wire.readonly_accounts_cnt > 0 {
630            let mut accounts = Vec::new();
631            for _ in 0..wire.readonly_accounts_cnt {
632                if offset + 32 > sig_start {
633                    return None;
634                }
635                let mut acc = [0u8; 32];
636                acc.copy_from_slice(&bytes[offset..offset + 32]);
637                accounts.push(acc);
638                offset += 32;
639            }
640            Some(accounts)
641        } else {
642            None
643        };
644
645        // Parse instructions
646        let instructions = if wire.instr_data_sz > 0 {
647            if offset + wire.instr_data_sz as usize > sig_start {
648                return None;
649            }
650            let instr = bytes[offset..offset + wire.instr_data_sz as usize].to_vec();
651            offset += wire.instr_data_sz as usize;
652            Some(instr)
653        } else {
654            None
655        };
656
657        let mut fee_payer_account_meta_raw: Option<Vec<u8>> = None;
658        // Parse state proof if present
659        let fee_payer_state_proof = if has_fee_payer_state_proof(wire.flags) {
660            if offset >= sig_start {
661                return None;
662            }
663            let state_proof_bytes = &bytes[offset..sig_start];
664            if let Some(state_proof) = StateProof::from_wire(state_proof_bytes) {
665                offset += state_proof.footprint();
666                if state_proof.header.proof_type == StateProofType::Existing {
667                    if offset + TN_ACCOUNT_META_FOOTPRINT > sig_start {
668                        return None;
669                    }
670                    let account_meta_bytes = &bytes[offset..offset + TN_ACCOUNT_META_FOOTPRINT];
671                    fee_payer_account_meta_raw = Some(account_meta_bytes.to_vec());
672                    offset += TN_ACCOUNT_META_FOOTPRINT;
673                }
674                Some(state_proof)
675            } else {
676                return None;
677            }
678        } else {
679            None
680        };
681
682        // Verify we've consumed all bytes before signature
683        if offset != sig_start {
684            log::warn!(
685                "Transaction::from_wire: offset != sig_start ({} != {})",
686                offset,
687                sig_start
688            );
689            return None;
690        }
691
692        Some(Transaction {
693            fee_payer: wire.fee_payer_pubkey,
694            program: wire.program_pubkey,
695            rw_accs,
696            r_accs,
697            instructions,
698            flags: wire.flags,
699            chain_id: wire.chain_id,
700            fee: wire.fee,
701            req_compute_units: wire.req_compute_units,
702            req_state_units: wire.req_state_units,
703            req_memory_units: wire.req_memory_units,
704            expiry_after: wire.expiry_after,
705            start_slot: wire.start_slot,
706            nonce: wire.nonce,
707            signature: Some(signature),
708            fee_payer_state_proof,
709            fee_payer_account_meta_raw,
710        })
711    }
712
713    /// Accessor: read a field from serialized bytes by name
714    pub fn get_field_from_wire(bytes: &[u8], field: &str) -> Option<Vec<u8>> {
715        if bytes.len() < core::mem::size_of::<WireTxnHdrV1>() + TN_TXN_SIGNATURE_SZ {
716            return None;
717        }
718        let wire: WireTxnHdrV1 =
719            pod_read_unaligned(&bytes[0..core::mem::size_of::<WireTxnHdrV1>()]);
720        match field {
721            "fee_payer_signature" => {
722                let sig_start = bytes.len() - TN_TXN_SIGNATURE_SZ;
723                Some(bytes[sig_start..].to_vec())
724            }
725            "transaction_version" => Some(vec![wire.transaction_version]),
726            "flags" => Some(vec![wire.flags]),
727            "readwrite_accounts_cnt" => Some(wire.readwrite_accounts_cnt.to_le_bytes().to_vec()),
728            "readonly_accounts_cnt" => Some(wire.readonly_accounts_cnt.to_le_bytes().to_vec()),
729            "instr_data_sz" => Some(wire.instr_data_sz.to_le_bytes().to_vec()),
730            "req_compute_units" => Some(wire.req_compute_units.to_le_bytes().to_vec()),
731            "req_state_units" => Some(wire.req_state_units.to_le_bytes().to_vec()),
732            "req_memory_units" => Some(wire.req_memory_units.to_le_bytes().to_vec()),
733            "expiry_after" => Some(wire.expiry_after.to_le_bytes().to_vec()),
734            "chain_id" => Some(wire.chain_id.to_le_bytes().to_vec()),
735            "fee" => Some(wire.fee.to_le_bytes().to_vec()),
736            "nonce" => Some(wire.nonce.to_le_bytes().to_vec()),
737            "start_slot" => Some(wire.start_slot.to_le_bytes().to_vec()),
738            "fee_payer_pubkey" => Some(wire.fee_payer_pubkey.to_vec()),
739            "program_pubkey" => Some(wire.program_pubkey.to_vec()),
740            _ => None,
741        }
742    }
743}
744
745/// Helper function to check if transaction has fee payer state proof
746fn has_fee_payer_state_proof(flags: u8) -> bool {
747    (flags & (1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT)) != 0
748}
749
750/// Helper function to extract state proof type from header
751fn extract_state_proof_type(type_slot: u64) -> u64 {
752    (type_slot >> 62) & 0x3 // Extract top 2 bits
753}
754
755/// Helper function to calculate state proof footprint from header
756fn calculate_state_proof_footprint(state_proof_data: &[u8]) -> Result<usize, RpcError> {
757    if state_proof_data.len() < TN_STATE_PROOF_HDR_SIZE {
758        return Err(RpcError::invalid_format());
759    }
760
761    // Extract type_slot (first 8 bytes)
762    let type_slot = u64::from_le_bytes([
763        state_proof_data[0],
764        state_proof_data[1],
765        state_proof_data[2],
766        state_proof_data[3],
767        state_proof_data[4],
768        state_proof_data[5],
769        state_proof_data[6],
770        state_proof_data[7],
771    ]);
772
773    // Extract path_bitset (next 32 bytes) and count set bits
774    let mut sibling_hash_cnt = 0u32;
775    for i in 0..4 {
776        let start = 8 + i * 8;
777        let word = u64::from_le_bytes([
778            state_proof_data[start],
779            state_proof_data[start + 1],
780            state_proof_data[start + 2],
781            state_proof_data[start + 3],
782            state_proof_data[start + 4],
783            state_proof_data[start + 5],
784            state_proof_data[start + 6],
785            state_proof_data[start + 7],
786        ]);
787        sibling_hash_cnt += word.count_ones();
788    }
789
790    let proof_type = extract_state_proof_type(type_slot);
791    let body_sz = (proof_type + sibling_hash_cnt as u64) * 32; // Each hash is 32 bytes
792
793    Ok(TN_STATE_PROOF_HDR_SIZE + body_sz as usize)
794}
795
796pub fn tn_txn_size(bytes: &[u8]) -> Result<usize, RpcError> {
797    // Basic size checks
798    if bytes.len() < core::mem::size_of::<WireTxnHdrV1>() + TN_TXN_SIGNATURE_SZ {
799        return Err(RpcError::invalid_format());
800    }
801
802    // Parse the header
803    // Use read_unaligned to safely read from potentially unaligned memory
804    let hdr: WireTxnHdrV1 =
805        unsafe { std::ptr::read_unaligned(bytes.as_ptr() as *const WireTxnHdrV1) };
806    let hdr = &hdr;
807    let mut offset = core::mem::size_of::<WireTxnHdrV1>();
808
809    // Calculate accounts size
810    let accs_sz = (hdr.readwrite_accounts_cnt as usize + hdr.readonly_accounts_cnt as usize) * 32;
811    if offset + accs_sz > bytes.len() {
812        return Err(RpcError::invalid_format());
813    }
814    offset += accs_sz;
815
816    // Calculate instruction data size
817    let instr_sz = hdr.instr_data_sz as usize;
818    if offset + instr_sz > bytes.len() {
819        return Err(RpcError::invalid_format());
820    }
821    offset += instr_sz;
822
823    // Handle fee payer state proof if present
824    if has_fee_payer_state_proof(hdr.flags) {
825        // Check state proof header size
826        if offset + TN_STATE_PROOF_HDR_SIZE > bytes.len() {
827            return Err(RpcError::invalid_format());
828        }
829
830        // Calculate state proof footprint
831        let state_proof_data = &bytes[offset..];
832        let state_proof_sz = calculate_state_proof_footprint(state_proof_data)?;
833
834        if offset + state_proof_sz > bytes.len() {
835            return Err(RpcError::invalid_format());
836        }
837        offset += state_proof_sz;
838
839        // Extract proof type for additional validation
840        let type_slot = u64::from_le_bytes([
841            state_proof_data[0],
842            state_proof_data[1],
843            state_proof_data[2],
844            state_proof_data[3],
845            state_proof_data[4],
846            state_proof_data[5],
847            state_proof_data[6],
848            state_proof_data[7],
849        ]);
850        let proof_type = extract_state_proof_type(type_slot);
851
852        // If proof type is EXISTING, account for account meta
853        if proof_type == TN_STATE_PROOF_TYPE_EXISTING {
854            if offset + TN_ACCOUNT_META_FOOTPRINT > bytes.len() {
855                return Err(RpcError::invalid_format());
856            }
857            offset += TN_ACCOUNT_META_FOOTPRINT;
858        }
859    }
860
861    // Add trailing signature size
862    offset += TN_TXN_SIGNATURE_SZ;
863
864    // Verify we don't exceed the provided bytes
865    if offset > bytes.len() {
866        return Err(RpcError::invalid_format());
867    }
868
869    Ok(offset)
870}
871
872/// Validate a transaction's account layout (count, duplicates, sort order).
873///
874/// Mirrors the C source of truth tn_validate_txn_accounts
875/// (src/thru/runtime/tn_txn_account_validate.c): a combined merge-walk detects
876/// sort-order violations, within-array duplicates, and cross-array (rw∩ro)
877/// duplicates in a single pass, with the same error precedence (unsorted before
878/// a fee_payer/program duplicate). The fee_payer/program-in-array check runs only
879/// after sort order is confirmed.
880pub fn validate_account_layout(
881    rw_accs: &[TnPubkey],
882    r_accs: &[TnPubkey],
883    fee_payer: &TnPubkey,
884    program: &TnPubkey,
885) -> Result<(), RpcError> {
886    let total_accounts = 2usize
887        .checked_add(rw_accs.len())
888        .and_then(|v| v.checked_add(r_accs.len()))
889        .ok_or_else(|| RpcError::too_many_accounts(usize::MAX, TN_TXN_MAX_ACCOUNTS))?;
890    if total_accounts > TN_TXN_MAX_ACCOUNTS {
891        return Err(RpcError::too_many_accounts(
892            total_accounts,
893            TN_TXN_MAX_ACCOUNTS,
894        ));
895    }
896    if fee_payer == program {
897        return Err(RpcError::duplicate_account());
898    }
899
900    let (mut i, mut j) = (0usize, 0usize);
901    let mut prev_rw: Option<&[u8; 32]> = None;
902    let mut prev_ro: Option<&[u8; 32]> = None;
903    while i < rw_accs.len() || j < r_accs.len() {
904        let use_rw = j >= r_accs.len() || (i < rw_accs.len() && rw_accs[i] <= r_accs[j]);
905        if use_rw {
906            let key = &rw_accs[i];
907            if j < r_accs.len() && *key == r_accs[j] {
908                return Err(RpcError::duplicate_account());
909            }
910            if let Some(prev) = prev_rw {
911                if prev == key {
912                    return Err(RpcError::duplicate_account());
913                }
914                if prev > key {
915                    return Err(RpcError::unsorted_readwrite_accounts());
916                }
917            }
918            prev_rw = Some(key);
919            i += 1;
920        } else {
921            let key = &r_accs[j];
922            if let Some(prev) = prev_ro {
923                if prev == key {
924                    return Err(RpcError::duplicate_account());
925                }
926                if prev > key {
927                    return Err(RpcError::unsorted_readonly_accounts());
928                }
929            }
930            prev_ro = Some(key);
931            j += 1;
932        }
933    }
934
935    for account in rw_accs.iter().chain(r_accs.iter()) {
936        if account == fee_payer || account == program {
937            return Err(RpcError::duplicate_account());
938        }
939    }
940
941    Ok(())
942}
943
944/// Validate a wire-format transaction for protocol correctness (matching C tn_txn_parse_core).
945pub fn validate_wire_transaction(bytes: &[u8]) -> Result<(), RpcError> {
946    const TN_TXN_MTU: usize = 32_768;
947    // Version and flags are now at offset 0 and 1
948    const TN_TXN_VERSION_OFFSET: usize = 0;
949    const TN_TXN_FLAGS_OFFSET: usize = 1;
950
951    use bytemuck::pod_read_unaligned;
952
953    // 1. Check payload size
954    if bytes.len() > TN_TXN_MTU {
955        return Err(RpcError::invalid_transaction_size(bytes.len(), TN_TXN_MTU));
956    }
957
958    // 2. Check minimum size
959    if bytes.len() < core::mem::size_of::<WireTxnHdrV1>() + TN_TXN_SIGNATURE_SZ {
960        return Err(RpcError::invalid_format());
961    }
962
963    // 3. Check transaction version
964    let transaction_version = bytes[TN_TXN_VERSION_OFFSET];
965    if transaction_version != 0x01 {
966        return Err(RpcError::invalid_version());
967    }
968
969    // 4. Check flags
970    let flags = bytes[TN_TXN_FLAGS_OFFSET];
971    // Clear the fee payer proof bit and check that all other bits are 0
972    let flags_without_proof_bit = flags & !(1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT);
973    let flags_cleared = flags_without_proof_bit & !(1 << TN_TXN_FLAG_MAY_COMPRESS_ACCOUNT_BIT);
974    if flags_cleared != 0 {
975        return Err(RpcError::invalid_flags());
976    }
977
978    // 5. Parse header
979    let hdr: WireTxnHdrV1 = pod_read_unaligned(&bytes[0..core::mem::size_of::<WireTxnHdrV1>()]);
980    let mut offset = core::mem::size_of::<WireTxnHdrV1>();
981
982    let sig_start = bytes.len() - TN_TXN_SIGNATURE_SZ;
983
984    // 6. Validate chain_id is non-zero (matches C tn_txn_parse.c:37)
985    if hdr.chain_id == 0 {
986        return Err(RpcError::invalid_chain_id());
987    }
988
989    // 6. Parse accounts
990    let accs_sz = (hdr.readwrite_accounts_cnt as usize + hdr.readonly_accounts_cnt as usize) * 32;
991    if offset + accs_sz > sig_start {
992        return Err(RpcError::invalid_format());
993    }
994    offset += accs_sz;
995
996    // 7. Parse instruction data
997    let instr_sz = hdr.instr_data_sz as usize;
998    if offset + instr_sz > sig_start {
999        return Err(RpcError::invalid_format());
1000    }
1001    offset += instr_sz;
1002
1003    // 8. Handle fee payer state proof if present
1004    if has_fee_payer_state_proof(flags) {
1005        // Check state proof header size
1006        if offset + TN_STATE_PROOF_HDR_SIZE > sig_start {
1007            return Err(RpcError::invalid_format());
1008        }
1009
1010        let state_proof_data = &bytes[offset..sig_start];
1011
1012        // Extract and validate the proof type before using the footprint. Only
1013        // EXISTING and CREATION are valid; UPDATING and out-of-range types (e.g.
1014        // type 3) are rejected — matching C tn_txn_parse.c, where an invalid type
1015        // yields a zero footprint and is rejected before further parsing.
1016        let type_slot = u64::from_le_bytes([
1017            state_proof_data[0],
1018            state_proof_data[1],
1019            state_proof_data[2],
1020            state_proof_data[3],
1021            state_proof_data[4],
1022            state_proof_data[5],
1023            state_proof_data[6],
1024            state_proof_data[7],
1025        ]);
1026        let proof_type = extract_state_proof_type(type_slot);
1027        if proof_type != TN_STATE_PROOF_TYPE_EXISTING && proof_type != TN_STATE_PROOF_TYPE_CREATION
1028        {
1029            return Err(RpcError::invalid_fee_payer_state_proof_type());
1030        }
1031
1032        // Calculate state proof footprint
1033        let state_proof_sz = calculate_state_proof_footprint(state_proof_data)?;
1034
1035        if offset + state_proof_sz > sig_start {
1036            return Err(RpcError::invalid_format());
1037        }
1038
1039        offset += state_proof_sz;
1040
1041        // If proof type is EXISTING, expect account meta
1042        if proof_type == TN_STATE_PROOF_TYPE_EXISTING {
1043            if offset + TN_ACCOUNT_META_FOOTPRINT > sig_start {
1044                return Err(RpcError::invalid_format());
1045            }
1046            offset += TN_ACCOUNT_META_FOOTPRINT;
1047        }
1048    }
1049
1050    // 9. Check for exact size match (offset should be at signature start)
1051    if offset != sig_start {
1052        return Err(RpcError::trailing_bytes(
1053            offset + TN_TXN_SIGNATURE_SZ,
1054            bytes.len(),
1055        ));
1056    }
1057
1058    // 9b. Account-layout validation (count, duplicates, sort order) runs after
1059    // the whole wire structure is confirmed and before signature verification,
1060    // matching the C/Go order. Keep in sync with
1061    // src/thru/runtime/tn_txn_account_validate.c.
1062    {
1063        let accs_start = core::mem::size_of::<WireTxnHdrV1>();
1064        let rw_cnt = hdr.readwrite_accounts_cnt as usize;
1065        let ro_cnt = hdr.readonly_accounts_cnt as usize;
1066        let mut rw_accs: Vec<TnPubkey> = Vec::with_capacity(rw_cnt);
1067        for k in 0..rw_cnt {
1068            let s = accs_start + k * 32;
1069            let mut a = [0u8; 32];
1070            a.copy_from_slice(&bytes[s..s + 32]);
1071            rw_accs.push(a);
1072        }
1073        let ro_start = accs_start + rw_cnt * 32;
1074        let mut ro_accs: Vec<TnPubkey> = Vec::with_capacity(ro_cnt);
1075        for k in 0..ro_cnt {
1076            let s = ro_start + k * 32;
1077            let mut a = [0u8; 32];
1078            a.copy_from_slice(&bytes[s..s + 32]);
1079            ro_accs.push(a);
1080        }
1081        validate_account_layout(
1082            &rw_accs,
1083            &ro_accs,
1084            &hdr.fee_payer_pubkey,
1085            &hdr.program_pubkey,
1086        )?;
1087    }
1088
1089    // 10. Signature check
1090    let wire_for_signing = &bytes[..sig_start];
1091    let signature = &bytes[sig_start..];
1092    if verify_transaction(
1093        wire_for_signing,
1094        signature.try_into().expect("signature should be 64 bytes"),
1095        &hdr.fee_payer_pubkey,
1096    )
1097    .is_err()
1098    {
1099        return Err(RpcError::invalid_transaction_signature());
1100    }
1101
1102    Ok(())
1103}
1104
1105#[cfg(test)]
1106mod tests {
1107    use super::*;
1108    use ed25519_dalek::SigningKey;
1109
1110    fn make_valid_txn_bytes_with_flags(flags: u8) -> Vec<u8> {
1111        let signing_key = SigningKey::from(&[1u8; 32]);
1112        let verifying_key = signing_key.verifying_key();
1113        let mut tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42);
1114        tx.rw_accs = Some(vec![[3u8; 32], [4u8; 32]]);
1115        tx.r_accs = Some(vec![[5u8; 32]]);
1116        tx.instructions = Some(vec![1, 2, 3, 4]);
1117        tx.flags = flags;
1118        tx.sign(&signing_key.to_bytes()).unwrap();
1119        tx.to_wire()
1120    }
1121
1122    fn make_valid_txn_bytes() -> Vec<u8> {
1123        make_valid_txn_bytes_with_flags(0)
1124    }
1125
1126    #[test]
1127    fn test_tn_txn_size_basic_transaction() {
1128        let bytes = make_valid_txn_bytes();
1129        let calculated_size = tn_txn_size(&bytes).unwrap();
1130
1131        // The calculated size should match the actual bytes length
1132        assert_eq!(calculated_size, bytes.len());
1133    }
1134
1135    #[test]
1136    fn test_tn_txn_size_with_state_proof() {
1137        use crate::tn_state_proof::StateProof;
1138
1139        let signing_key = SigningKey::from(&[1u8; 32]);
1140        let verifying_key = signing_key.verifying_key();
1141
1142        // Create a CREATION state proof
1143        let path_bitset = [0u8; 32]; // No set bits = no sibling hashes
1144        let existing_leaf_pubkey = [7u8; 32];
1145        let existing_leaf_hash = [8u8; 32];
1146        let state_proof = StateProof::creation(
1147            100,
1148            path_bitset,
1149            existing_leaf_pubkey,
1150            existing_leaf_hash,
1151            vec![],
1152        );
1153
1154        // Create transaction with state proof
1155        let mut tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42)
1156            .with_rw_accounts(vec![[3u8; 32]])
1157            .with_instructions(vec![1, 2, 3])
1158            .with_fee_payer_state_proof(&state_proof);
1159
1160        tx.sign(&signing_key.to_bytes()).unwrap();
1161        let bytes = tx.to_wire();
1162
1163        let calculated_size = tn_txn_size(&bytes).unwrap();
1164
1165        // The calculated size should match the actual bytes length
1166        assert_eq!(calculated_size, bytes.len());
1167    }
1168
1169    #[test]
1170    fn test_tn_txn_size_minimal_transaction() {
1171        let signing_key = SigningKey::from(&[1u8; 32]);
1172        let verifying_key = signing_key.verifying_key();
1173
1174        // Create minimal transaction (no accounts, no instructions)
1175        let mut tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42);
1176        tx.sign(&signing_key.to_bytes()).unwrap();
1177        let bytes = tx.to_wire();
1178
1179        let calculated_size = tn_txn_size(&bytes).unwrap();
1180
1181        // The calculated size should match the actual bytes length
1182        assert_eq!(calculated_size, bytes.len());
1183
1184        // Should be header size + trailing signature for minimal transaction
1185        let expected_min_size = core::mem::size_of::<WireTxnHdrV1>() + TN_TXN_SIGNATURE_SZ;
1186        assert_eq!(calculated_size, expected_min_size);
1187    }
1188
1189    #[test]
1190    fn test_tn_txn_size_invalid_format() {
1191        // Test with bytes too short for header
1192        let short_bytes = vec![0u8; 50];
1193        let result = tn_txn_size(&short_bytes);
1194        assert!(matches!(result, Err(RpcError::InvalidFormat)));
1195
1196        // Test with header but missing account data
1197        let mut bytes = make_valid_txn_bytes();
1198        bytes.truncate(core::mem::size_of::<WireTxnHdrV1>() + 10); // Truncate to cause missing data
1199        let result = tn_txn_size(&bytes);
1200        assert!(matches!(result, Err(RpcError::InvalidFormat)));
1201    }
1202
1203    #[test]
1204    fn test_tn_txn_size_consistency_with_validation() {
1205        let bytes = make_valid_txn_bytes();
1206
1207        // Both functions should succeed for valid transactions
1208        assert!(validate_wire_transaction(&bytes).is_ok());
1209        assert!(tn_txn_size(&bytes).is_ok());
1210
1211        // Size should match actual length
1212        let calculated_size = tn_txn_size(&bytes).unwrap();
1213        assert_eq!(calculated_size, bytes.len());
1214    }
1215
1216    #[test]
1217    fn test_valid_transaction() {
1218        let bytes = make_valid_txn_bytes();
1219        assert!(validate_wire_transaction(&bytes).is_ok());
1220    }
1221
1222    #[test]
1223    fn test_transaction_duplicate_accounts_rejected() {
1224        let signing_key = SigningKey::from(&[1u8; 32]);
1225        let fee = signing_key.verifying_key().to_bytes();
1226        let program = [2u8; 32];
1227        let a = [3u8; 32];
1228        let b = [4u8; 32];
1229
1230        let cases = [
1231            Transaction::new(fee, fee, 100, 42),
1232            Transaction::new(fee, program, 100, 42).with_rw_accounts(vec![fee]),
1233            Transaction::new(fee, program, 100, 42).with_r_accounts(vec![fee]),
1234            Transaction::new(fee, program, 100, 42).with_rw_accounts(vec![program]),
1235            Transaction::new(fee, program, 100, 42).with_r_accounts(vec![program]),
1236            Transaction::new(fee, program, 100, 42).with_rw_accounts(vec![a, a]),
1237            Transaction::new(fee, program, 100, 42).with_r_accounts(vec![a, a]),
1238            Transaction::new(fee, program, 100, 42)
1239                .with_rw_accounts(vec![a])
1240                .with_r_accounts(vec![a, b]),
1241        ];
1242
1243        for mut tx in cases {
1244            assert!(matches!(tx.validate(), Err(RpcError::DuplicateAccount)));
1245            assert!(matches!(tx.try_to_wire(), Err(RpcError::DuplicateAccount)));
1246            assert!(tx.sign(&signing_key.to_bytes()).is_err());
1247        }
1248    }
1249
1250    #[test]
1251    fn test_oversize_transaction() {
1252        let mut bytes = make_valid_txn_bytes();
1253        bytes.resize(32_769, 0);
1254        let err = validate_wire_transaction(&bytes).unwrap_err();
1255        assert!(matches!(
1256            err,
1257            RpcError::InvalidTransactionSize {
1258                size: 32_769,
1259                max_size: 32_768
1260            }
1261        ));
1262    }
1263
1264    #[test]
1265    fn test_trailing_bytes() {
1266        let mut bytes = make_valid_txn_bytes();
1267        let orig_len = bytes.len();
1268        // Insert a byte before the signature (trailing bytes between body and signature)
1269        bytes.insert(orig_len - TN_TXN_SIGNATURE_SZ, 0);
1270        let err = validate_wire_transaction(&bytes).unwrap_err();
1271        // Expected size changes due to new wire format (112-byte header instead of 176)
1272        assert!(matches!(err, RpcError::TrailingBytes { .. }));
1273    }
1274
1275    #[test]
1276    fn test_invalid_transaction_version() {
1277        let mut bytes = make_valid_txn_bytes();
1278        // Corrupt the transaction version
1279        bytes[0] = 0x00; // Invalid version
1280        let err = validate_wire_transaction(&bytes).unwrap_err();
1281        assert!(matches!(err, RpcError::InvalidVersion));
1282    }
1283
1284    #[test]
1285    fn test_invalid_flags() {
1286        // Set invalid flag bits (keeping fee payer proof bit, but adding others)
1287        let bytes = make_valid_txn_bytes_with_flags(0x07);
1288        let err = validate_wire_transaction(&bytes).unwrap_err();
1289        assert!(matches!(err, RpcError::InvalidFlags));
1290    }
1291
1292    #[test]
1293    fn test_invalid_chain_id_zero() {
1294        let mut bytes = make_valid_txn_bytes();
1295
1296        /* Modify chain_id field to 0 (chain_id is at offset 108-109 in WireTxnHdrV1) */
1297        let hdr: &mut WireTxnHdrV1 =
1298            bytemuck::from_bytes_mut(&mut bytes[0..core::mem::size_of::<WireTxnHdrV1>()]);
1299        hdr.chain_id = 0;
1300
1301        let err = validate_wire_transaction(&bytes).unwrap_err();
1302        assert!(matches!(err, RpcError::InvalidChainId));
1303    }
1304
1305    #[test]
1306    fn test_transaction_too_short() {
1307        let bytes = vec![0u8; 50]; // Too short for header
1308        let err = validate_wire_transaction(&bytes).unwrap_err();
1309        assert!(matches!(err, RpcError::InvalidFormat));
1310    }
1311
1312    #[test]
1313    fn test_transaction_with_state_proof() {
1314        use crate::tn_state_proof::{StateProof, StateProofType};
1315
1316        let signing_key = SigningKey::from(&[1u8; 32]);
1317        let verifying_key = signing_key.verifying_key();
1318
1319        // Create a CREATION state proof (doesn't require account meta)
1320        let path_bitset = [0u8; 32]; // No set bits = no sibling hashes
1321        let existing_leaf_pubkey = [7u8; 32];
1322        let existing_leaf_hash = [8u8; 32];
1323        let state_proof = StateProof::creation(
1324            100,
1325            path_bitset,
1326            existing_leaf_pubkey,
1327            existing_leaf_hash,
1328            vec![],
1329        );
1330
1331        // Create transaction with state proof
1332        let mut tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42)
1333            .with_fee_payer_state_proof(&state_proof);
1334
1335        // Verify flag is set
1336        assert!(tx.has_fee_payer_state_proof());
1337        assert_eq!(tx.flags & (1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT), 1);
1338
1339        tx.sign(&signing_key.to_bytes()).unwrap();
1340        let bytes = tx.to_wire();
1341
1342        // Verify state proof is included in wire format
1343        assert!(bytes.len() > core::mem::size_of::<WireTxnHdrV1>() + TN_TXN_SIGNATURE_SZ);
1344        assert!(validate_wire_transaction(&bytes).is_ok());
1345
1346        // Test deserialization
1347        let decoded_tx = Transaction::from_wire(&bytes).unwrap();
1348        assert!(decoded_tx.has_fee_payer_state_proof());
1349        assert!(decoded_tx.fee_payer_state_proof.is_some());
1350
1351        let decoded_proof = decoded_tx.fee_payer_state_proof.unwrap();
1352        assert_eq!(decoded_proof.proof_type(), StateProofType::Creation);
1353        assert_eq!(decoded_proof.slot(), 100);
1354    }
1355
1356    #[test]
1357    fn test_transaction_with_state_proof_serialization_round_trip() {
1358        use crate::tn_state_proof::StateProof;
1359
1360        let signing_key = SigningKey::from(&[1u8; 32]);
1361        let verifying_key = signing_key.verifying_key();
1362
1363        // Create a creation state proof with some sibling hashes
1364        let mut path_bitset = [0u8; 32];
1365        path_bitset[0] = 0b11; // Set first 2 bits for 2 sibling hashes
1366        let existing_leaf_pubkey = [7u8; 32];
1367        let existing_leaf_hash = [8u8; 32];
1368        let sibling_hashes = vec![[9u8; 32], [10u8; 32]];
1369
1370        let state_proof = StateProof::creation(
1371            200,
1372            path_bitset,
1373            existing_leaf_pubkey,
1374            existing_leaf_hash,
1375            sibling_hashes.clone(),
1376        );
1377
1378        // Create transaction with complex state proof
1379        let mut tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42)
1380            .with_rw_accounts(vec![[3u8; 32], [4u8; 32]])
1381            .with_r_accounts(vec![[5u8; 32]])
1382            .with_instructions(vec![1, 2, 3, 4])
1383            .with_fee_payer_state_proof(&state_proof);
1384
1385        tx.sign(&signing_key.to_bytes()).unwrap();
1386        let bytes = tx.to_wire();
1387
1388        // Test validation
1389        assert!(validate_wire_transaction(&bytes).is_ok());
1390
1391        // Test round-trip serialization
1392        let decoded_tx = Transaction::from_wire(&bytes).unwrap();
1393        assert_eq!(decoded_tx.fee_payer, tx.fee_payer);
1394        assert_eq!(decoded_tx.program, tx.program);
1395        assert_eq!(decoded_tx.rw_accs, tx.rw_accs);
1396        assert_eq!(decoded_tx.r_accs, tx.r_accs);
1397        assert_eq!(decoded_tx.instructions, tx.instructions);
1398        assert_eq!(decoded_tx.flags, tx.flags);
1399        assert!(decoded_tx.has_fee_payer_state_proof());
1400
1401        let decoded_proof = decoded_tx.fee_payer_state_proof.unwrap();
1402        assert_eq!(decoded_proof.slot(), 200);
1403        assert_eq!(decoded_proof.path_bitset(), &path_bitset);
1404    }
1405
1406    #[test]
1407    fn test_transaction_without_state_proof() {
1408        let signing_key = SigningKey::from(&[1u8; 32]);
1409        let verifying_key = signing_key.verifying_key();
1410
1411        let mut tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42);
1412
1413        // Verify flag is not set
1414        assert!(!tx.has_fee_payer_state_proof());
1415        assert_eq!(tx.flags & (1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT), 0);
1416        assert!(tx.fee_payer_state_proof.is_none());
1417
1418        tx.sign(&signing_key.to_bytes()).unwrap();
1419        let bytes = tx.to_wire();
1420
1421        assert!(validate_wire_transaction(&bytes).is_ok());
1422
1423        // Test deserialization
1424        let decoded_tx = Transaction::from_wire(&bytes).unwrap();
1425        assert!(!decoded_tx.has_fee_payer_state_proof());
1426        assert!(decoded_tx.fee_payer_state_proof.is_none());
1427    }
1428
1429    #[test]
1430    fn test_transaction_remove_state_proof() {
1431        use crate::tn_state_proof::StateProof;
1432
1433        let signing_key = SigningKey::from(&[1u8; 32]);
1434        let verifying_key = signing_key.verifying_key();
1435
1436        // Create a CREATION state proof
1437        let path_bitset = [0u8; 32];
1438        let existing_leaf_pubkey = [7u8; 32];
1439        let existing_leaf_hash = [8u8; 32];
1440        let state_proof = StateProof::creation(
1441            100,
1442            path_bitset,
1443            existing_leaf_pubkey,
1444            existing_leaf_hash,
1445            vec![],
1446        );
1447
1448        // Create transaction with state proof, then remove it
1449        let tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42)
1450            .with_fee_payer_state_proof(&state_proof)
1451            .without_fee_payer_state_proof();
1452
1453        // Verify flag is cleared and state proof is removed
1454        assert!(!tx.has_fee_payer_state_proof());
1455        assert_eq!(tx.flags & (1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT), 0);
1456        assert!(tx.fee_payer_state_proof.is_none());
1457    }
1458}