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: 0,
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    ///
324    /// A fee payer proof activates the fee payer, and the runtime rejects
325    /// such a transaction before execution when it requests no state units
326    /// (TN_RUNTIME_TXN_ERR_FEE_PAYER_ACTIVATION_REQUIRES_STATE_UNIT), so the
327    /// request is raised to at least one. A later `with_state_units` call
328    /// still sets the request explicitly. This minimum does not include any
329    /// additional accounts created or grown by the program; callers must
330    /// budget for the transaction's total net growth.
331    pub fn with_fee_payer_state_proof(mut self, state_proof: &StateProof) -> Self {
332        self.fee_payer_state_proof = Some(state_proof.clone());
333        // Set the flag bit to indicate presence of state proof
334        self.flags |= 1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT;
335        self.req_state_units = self.req_state_units.max(1);
336        self
337    }
338
339    /// Builder method: set fee payer account meta as raw bytes
340    pub fn with_fee_payer_account_meta_raw(mut self, account_meta_raw: Vec<u8>) -> Self {
341        self.fee_payer_account_meta_raw = Some(account_meta_raw);
342        self
343    }
344
345    /// Builder method: remove fee payer state proof
346    pub fn without_fee_payer_state_proof(mut self) -> Self {
347        self.fee_payer_state_proof = None;
348        // Clear the flag bit to indicate absence of state proof
349        self.flags &= !(1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT);
350        self
351    }
352
353    /// Builder method: add read-write accounts
354    pub fn with_rw_accounts(mut self, accounts: Vec<TnPubkey>) -> Self {
355        self.rw_accs = Some(accounts);
356        self
357    }
358
359    /// Builder method: add read-only accounts
360    pub fn with_r_accounts(mut self, accounts: Vec<TnPubkey>) -> Self {
361        self.r_accs = Some(accounts);
362        self
363    }
364
365    /// Builder method: add a single read-write account
366    pub fn add_rw_account(mut self, account: TnPubkey) -> Self {
367        match self.rw_accs {
368            Some(ref mut accounts) => accounts.push(account),
369            None => self.rw_accs = Some(vec![account]),
370        }
371        self
372    }
373
374    /// Builder method: add a single read-only account
375    pub fn add_r_account(mut self, account: TnPubkey) -> Self {
376        match self.r_accs {
377            Some(ref mut accounts) => accounts.push(account),
378            None => self.r_accs = Some(vec![account]),
379        }
380        self
381    }
382
383    /// Builder method: add instruction data
384    pub fn with_instructions(mut self, instructions: Vec<u8>) -> Self {
385        self.instructions = Some(instructions);
386        self
387    }
388
389    /// Builder method: set compute units
390    pub fn with_compute_units(mut self, units: u32) -> Self {
391        self.req_compute_units = units;
392        self
393    }
394
395    /// Builder method: set state units
396    pub fn with_state_units(mut self, units: u16) -> Self {
397        self.req_state_units = units;
398        self
399    }
400
401    /// Builder method: set memory units
402    pub fn with_memory_units(mut self, units: u16) -> Self {
403        self.req_memory_units = units;
404        self
405    }
406
407    /// Builder method: set expiry
408    pub fn with_expiry_after(mut self, expiry: u32) -> Self {
409        self.expiry_after = expiry;
410        self
411    }
412
413    /// Builder method: set nonce
414    pub fn with_nonce(mut self, nonce: u64) -> Self {
415        self.nonce = nonce;
416        self
417    }
418
419    /// Builder method: set start slot
420    pub fn with_start_slot(mut self, slot: u64) -> Self {
421        self.start_slot = slot;
422        self
423    }
424
425    /// Builder method: set chain ID
426    pub fn with_chain_id(mut self, chain_id: u16) -> Self {
427        self.chain_id = chain_id;
428        self
429    }
430
431    /// Sign the transaction with a 32-byte Ed25519 private key.
432    /// Validates the account layout first, so a transaction with duplicate,
433    /// unsorted, or too-many accounts is rejected before signing.
434    pub fn sign(&mut self, private_key: &[u8; 32]) -> Result<(), Box<dyn std::error::Error>> {
435        self.validate()
436            .map_err(|e| Box::<dyn std::error::Error>::from(e))?;
437        self.sign_unchecked(private_key)
438    }
439
440    /// Sign WITHOUT validating the account layout. Intended for constructing
441    /// intentionally-invalid transactions (e.g. negative tests that submit a
442    /// malformed txn and expect the server to reject it). Production callers
443    /// should use `sign`, which validates first.
444    pub fn sign_unchecked(
445        &mut self,
446        private_key: &[u8; 32],
447    ) -> Result<(), Box<dyn std::error::Error>> {
448        let wire_bytes = self.to_wire_for_signing();
449        let sig = sign_transaction(&wire_bytes, &self.fee_payer, private_key)
450            .map_err(|e| Box::<dyn std::error::Error>::from(e))?;
451        self.signature = Some(sig);
452        Ok(())
453    }
454
455    /// Validate account count and duplicate-account rules before signing or serialization.
456    pub fn validate(&self) -> Result<(), RpcError> {
457        let rw_accs = self.rw_accs.as_deref().unwrap_or(&[]);
458        let r_accs = self.r_accs.as_deref().unwrap_or(&[]);
459        validate_account_layout(rw_accs, r_accs, &self.fee_payer, &self.program)
460    }
461
462    /// Verify the transaction signature
463    pub fn verify(&self) -> bool {
464        if let Some(sig_bytes) = &self.signature {
465            let wire_bytes = self.to_wire_for_signing();
466            return verify_transaction(&wire_bytes, sig_bytes, &self.fee_payer).is_ok();
467        }
468        false
469    }
470
471    /// Create wire format for signing (excluding trailing signature)
472    /// The message is: header + accounts + instr_data + state_proof + account_meta
473    fn to_wire_for_signing(&self) -> Vec<u8> {
474        // Zero out all bytes first to ensure deterministic padding
475        let mut wire: WireTxnHdrV1 = unsafe { core::mem::zeroed() };
476        wire.transaction_version = 1;
477        wire.flags = self.flags;
478        wire.readwrite_accounts_cnt = self.rw_accs.as_ref().map_or(0, |v| v.len() as u16);
479        wire.readonly_accounts_cnt = self.r_accs.as_ref().map_or(0, |v| v.len() as u16);
480        wire.instr_data_sz = self.instructions.as_ref().map_or(0, |v| v.len() as u16);
481        wire.req_compute_units = self.req_compute_units;
482        wire.req_state_units = self.req_state_units;
483        wire.req_memory_units = self.req_memory_units;
484        wire.expiry_after = self.expiry_after;
485        wire.chain_id = self.chain_id;
486        wire.fee = self.fee;
487        wire.nonce = self.nonce;
488        wire.start_slot = self.start_slot;
489        wire.fee_payer_pubkey = self.fee_payer;
490        wire.program_pubkey = self.program;
491
492        let mut result = bytes_of(&wire).to_vec();
493
494        // Append variable-length data
495        if let Some(ref rw_accs) = self.rw_accs {
496            for acc in rw_accs {
497                result.extend_from_slice(acc);
498            }
499        }
500
501        if let Some(ref r_accs) = self.r_accs {
502            for acc in r_accs {
503                result.extend_from_slice(acc);
504            }
505        }
506
507        if let Some(ref instructions) = self.instructions {
508            result.extend_from_slice(instructions);
509        }
510
511        // Append state proof if present
512        if let Some(ref state_proof) = self.fee_payer_state_proof {
513            result.extend_from_slice(&state_proof.to_wire());
514        }
515
516        // Use raw account meta if available, otherwise use structured account meta
517        if let Some(ref fee_payer_account_meta_raw) = self.fee_payer_account_meta_raw {
518            result.extend_from_slice(fee_payer_account_meta_raw);
519        }
520
521        result
522    }
523
524    /// Serialize to on-wire format (WireTxnHdrV1).
525    /// Wire format: header + accounts + instr_data + state_proof + account_meta + signature
526    ///
527    /// This is INFALLIBLE and does NOT validate account layout: it must remain
528    /// usable for re-serializing transactions that were ingested from the
529    /// network/block store (which may predate, or otherwise violate, the
530    /// duplicate-account rules — e.g. a stored poison transaction served via
531    /// getTransactionRaw). Validation is enforced at the construction boundary
532    /// (`sign`) and is available explicitly via `try_to_wire`.
533    pub fn to_wire(&self) -> Vec<u8> {
534        self.serialize_wire()
535    }
536
537    /// Fallible serialization: validate account layout, then serialize.
538    /// Use this for newly-built transactions that must satisfy the
539    /// duplicate/sort/count rules before going on the wire.
540    pub fn try_to_wire(&self) -> Result<Vec<u8>, RpcError> {
541        self.validate()?;
542        Ok(self.serialize_wire())
543    }
544
545    /// Internal: pure serialization with no validation.
546    fn serialize_wire(&self) -> Vec<u8> {
547        let mut wire = WireTxnHdrV1::default();
548        wire.transaction_version = 1;
549        wire.flags = self.flags;
550        wire.readwrite_accounts_cnt = self.rw_accs.as_ref().map_or(0, |v| v.len() as u16);
551        wire.readonly_accounts_cnt = self.r_accs.as_ref().map_or(0, |v| v.len() as u16);
552        wire.instr_data_sz = self.instructions.as_ref().map_or(0, |v| v.len() as u16);
553        wire.req_compute_units = self.req_compute_units;
554        wire.req_state_units = self.req_state_units;
555        wire.req_memory_units = self.req_memory_units;
556        wire.expiry_after = self.expiry_after;
557        wire.chain_id = self.chain_id;
558        wire.fee = self.fee;
559        wire.nonce = self.nonce;
560        wire.start_slot = self.start_slot;
561        wire.fee_payer_pubkey = self.fee_payer;
562        wire.program_pubkey = self.program;
563
564        let mut result = bytes_of(&wire).to_vec();
565
566        // Append variable-length data
567        if let Some(ref rw_accs) = self.rw_accs {
568            for acc in rw_accs {
569                result.extend_from_slice(acc);
570            }
571        }
572
573        if let Some(ref r_accs) = self.r_accs {
574            for acc in r_accs {
575                result.extend_from_slice(acc);
576            }
577        }
578
579        if let Some(ref instructions) = self.instructions {
580            result.extend_from_slice(instructions);
581        }
582
583        // Append state proof if present (after instruction data)
584        if let Some(ref state_proof) = self.fee_payer_state_proof {
585            result.extend_from_slice(&state_proof.to_wire());
586        }
587
588        // Use raw account meta if available, otherwise use structured account meta
589        if let Some(ref fee_payer_account_meta_raw) = self.fee_payer_account_meta_raw {
590            result.extend_from_slice(fee_payer_account_meta_raw);
591        }
592
593        // Append signature at the END (last 64 bytes)
594        if let Some(sig) = &self.signature {
595            result.extend_from_slice(sig);
596        } else {
597            // Zero signature if not set
598            result.extend_from_slice(&[0u8; TN_TXN_SIGNATURE_SZ]);
599        }
600
601        result
602    }
603
604    /// Deserialize from on-wire format (WireTxnHdrV1)
605    /// Wire format: header + accounts + instr_data + state_proof + account_meta + signature (at end)
606    pub fn from_wire(bytes: &[u8]) -> Option<Self> {
607        // Minimum size: header + signature at end
608        if bytes.len() < core::mem::size_of::<WireTxnHdrV1>() + TN_TXN_SIGNATURE_SZ {
609            return None;
610        }
611
612        let wire: WireTxnHdrV1 =
613            pod_read_unaligned(&bytes[0..core::mem::size_of::<WireTxnHdrV1>()]);
614        let mut offset = core::mem::size_of::<WireTxnHdrV1>();
615
616        let sig_start = bytes.len() - TN_TXN_SIGNATURE_SZ;
617        let mut signature = [0u8; TN_TXN_SIGNATURE_SZ];
618        signature.copy_from_slice(&bytes[sig_start..]);
619
620        // Parse read-write accounts
621        let rw_accs = if wire.readwrite_accounts_cnt > 0 {
622            let mut accounts = Vec::new();
623            for _ in 0..wire.readwrite_accounts_cnt {
624                if offset + 32 > sig_start {
625                    return None;
626                }
627                let mut acc = [0u8; 32];
628                acc.copy_from_slice(&bytes[offset..offset + 32]);
629                accounts.push(acc);
630                offset += 32;
631            }
632            Some(accounts)
633        } else {
634            None
635        };
636
637        // Parse read-only accounts
638        let r_accs = if wire.readonly_accounts_cnt > 0 {
639            let mut accounts = Vec::new();
640            for _ in 0..wire.readonly_accounts_cnt {
641                if offset + 32 > sig_start {
642                    return None;
643                }
644                let mut acc = [0u8; 32];
645                acc.copy_from_slice(&bytes[offset..offset + 32]);
646                accounts.push(acc);
647                offset += 32;
648            }
649            Some(accounts)
650        } else {
651            None
652        };
653
654        // Parse instructions
655        let instructions = if wire.instr_data_sz > 0 {
656            if offset + wire.instr_data_sz as usize > sig_start {
657                return None;
658            }
659            let instr = bytes[offset..offset + wire.instr_data_sz as usize].to_vec();
660            offset += wire.instr_data_sz as usize;
661            Some(instr)
662        } else {
663            None
664        };
665
666        let mut fee_payer_account_meta_raw: Option<Vec<u8>> = None;
667        // Parse state proof if present
668        let fee_payer_state_proof = if has_fee_payer_state_proof(wire.flags) {
669            if offset >= sig_start {
670                return None;
671            }
672            let state_proof_bytes = &bytes[offset..sig_start];
673            if let Some(state_proof) = StateProof::from_wire(state_proof_bytes) {
674                offset += state_proof.footprint();
675                if state_proof.header.proof_type == StateProofType::Existing {
676                    if offset + TN_ACCOUNT_META_FOOTPRINT > sig_start {
677                        return None;
678                    }
679                    let account_meta_bytes = &bytes[offset..offset + TN_ACCOUNT_META_FOOTPRINT];
680                    fee_payer_account_meta_raw = Some(account_meta_bytes.to_vec());
681                    offset += TN_ACCOUNT_META_FOOTPRINT;
682                }
683                Some(state_proof)
684            } else {
685                return None;
686            }
687        } else {
688            None
689        };
690
691        // Verify we've consumed all bytes before signature
692        if offset != sig_start {
693            log::warn!(
694                "Transaction::from_wire: offset != sig_start ({} != {})",
695                offset,
696                sig_start
697            );
698            return None;
699        }
700
701        Some(Transaction {
702            fee_payer: wire.fee_payer_pubkey,
703            program: wire.program_pubkey,
704            rw_accs,
705            r_accs,
706            instructions,
707            flags: wire.flags,
708            chain_id: wire.chain_id,
709            fee: wire.fee,
710            req_compute_units: wire.req_compute_units,
711            req_state_units: wire.req_state_units,
712            req_memory_units: wire.req_memory_units,
713            expiry_after: wire.expiry_after,
714            start_slot: wire.start_slot,
715            nonce: wire.nonce,
716            signature: Some(signature),
717            fee_payer_state_proof,
718            fee_payer_account_meta_raw,
719        })
720    }
721
722    /// Accessor: read a field from serialized bytes by name
723    pub fn get_field_from_wire(bytes: &[u8], field: &str) -> Option<Vec<u8>> {
724        if bytes.len() < core::mem::size_of::<WireTxnHdrV1>() + TN_TXN_SIGNATURE_SZ {
725            return None;
726        }
727        let wire: WireTxnHdrV1 =
728            pod_read_unaligned(&bytes[0..core::mem::size_of::<WireTxnHdrV1>()]);
729        match field {
730            "fee_payer_signature" => {
731                let sig_start = bytes.len() - TN_TXN_SIGNATURE_SZ;
732                Some(bytes[sig_start..].to_vec())
733            }
734            "transaction_version" => Some(vec![wire.transaction_version]),
735            "flags" => Some(vec![wire.flags]),
736            "readwrite_accounts_cnt" => Some(wire.readwrite_accounts_cnt.to_le_bytes().to_vec()),
737            "readonly_accounts_cnt" => Some(wire.readonly_accounts_cnt.to_le_bytes().to_vec()),
738            "instr_data_sz" => Some(wire.instr_data_sz.to_le_bytes().to_vec()),
739            "req_compute_units" => Some(wire.req_compute_units.to_le_bytes().to_vec()),
740            "req_state_units" => Some(wire.req_state_units.to_le_bytes().to_vec()),
741            "req_memory_units" => Some(wire.req_memory_units.to_le_bytes().to_vec()),
742            "expiry_after" => Some(wire.expiry_after.to_le_bytes().to_vec()),
743            "chain_id" => Some(wire.chain_id.to_le_bytes().to_vec()),
744            "fee" => Some(wire.fee.to_le_bytes().to_vec()),
745            "nonce" => Some(wire.nonce.to_le_bytes().to_vec()),
746            "start_slot" => Some(wire.start_slot.to_le_bytes().to_vec()),
747            "fee_payer_pubkey" => Some(wire.fee_payer_pubkey.to_vec()),
748            "program_pubkey" => Some(wire.program_pubkey.to_vec()),
749            _ => None,
750        }
751    }
752}
753
754/// Helper function to check if transaction has fee payer state proof
755fn has_fee_payer_state_proof(flags: u8) -> bool {
756    (flags & (1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT)) != 0
757}
758
759/// Helper function to extract state proof type from header
760fn extract_state_proof_type(type_slot: u64) -> u64 {
761    (type_slot >> 62) & 0x3 // Extract top 2 bits
762}
763
764/// Helper function to calculate state proof footprint from header
765fn calculate_state_proof_footprint(state_proof_data: &[u8]) -> Result<usize, RpcError> {
766    if state_proof_data.len() < TN_STATE_PROOF_HDR_SIZE {
767        return Err(RpcError::invalid_format());
768    }
769
770    // Extract type_slot (first 8 bytes)
771    let type_slot = u64::from_le_bytes([
772        state_proof_data[0],
773        state_proof_data[1],
774        state_proof_data[2],
775        state_proof_data[3],
776        state_proof_data[4],
777        state_proof_data[5],
778        state_proof_data[6],
779        state_proof_data[7],
780    ]);
781
782    // Extract path_bitset (next 32 bytes) and count set bits
783    let mut sibling_hash_cnt = 0u32;
784    for i in 0..4 {
785        let start = 8 + i * 8;
786        let word = u64::from_le_bytes([
787            state_proof_data[start],
788            state_proof_data[start + 1],
789            state_proof_data[start + 2],
790            state_proof_data[start + 3],
791            state_proof_data[start + 4],
792            state_proof_data[start + 5],
793            state_proof_data[start + 6],
794            state_proof_data[start + 7],
795        ]);
796        sibling_hash_cnt += word.count_ones();
797    }
798
799    let proof_type = extract_state_proof_type(type_slot);
800    let body_sz = (proof_type + sibling_hash_cnt as u64) * 32; // Each hash is 32 bytes
801
802    Ok(TN_STATE_PROOF_HDR_SIZE + body_sz as usize)
803}
804
805pub fn tn_txn_size(bytes: &[u8]) -> Result<usize, RpcError> {
806    // Basic size checks
807    if bytes.len() < core::mem::size_of::<WireTxnHdrV1>() + TN_TXN_SIGNATURE_SZ {
808        return Err(RpcError::invalid_format());
809    }
810
811    // Parse the header
812    // Use read_unaligned to safely read from potentially unaligned memory
813    let hdr: WireTxnHdrV1 =
814        unsafe { std::ptr::read_unaligned(bytes.as_ptr() as *const WireTxnHdrV1) };
815    let hdr = &hdr;
816    let mut offset = core::mem::size_of::<WireTxnHdrV1>();
817
818    // Calculate accounts size
819    let accs_sz = (hdr.readwrite_accounts_cnt as usize + hdr.readonly_accounts_cnt as usize) * 32;
820    if offset + accs_sz > bytes.len() {
821        return Err(RpcError::invalid_format());
822    }
823    offset += accs_sz;
824
825    // Calculate instruction data size
826    let instr_sz = hdr.instr_data_sz as usize;
827    if offset + instr_sz > bytes.len() {
828        return Err(RpcError::invalid_format());
829    }
830    offset += instr_sz;
831
832    // Handle fee payer state proof if present
833    if has_fee_payer_state_proof(hdr.flags) {
834        // Check state proof header size
835        if offset + TN_STATE_PROOF_HDR_SIZE > bytes.len() {
836            return Err(RpcError::invalid_format());
837        }
838
839        // Calculate state proof footprint
840        let state_proof_data = &bytes[offset..];
841        let state_proof_sz = calculate_state_proof_footprint(state_proof_data)?;
842
843        if offset + state_proof_sz > bytes.len() {
844            return Err(RpcError::invalid_format());
845        }
846        offset += state_proof_sz;
847
848        // Extract proof type for additional validation
849        let type_slot = u64::from_le_bytes([
850            state_proof_data[0],
851            state_proof_data[1],
852            state_proof_data[2],
853            state_proof_data[3],
854            state_proof_data[4],
855            state_proof_data[5],
856            state_proof_data[6],
857            state_proof_data[7],
858        ]);
859        let proof_type = extract_state_proof_type(type_slot);
860
861        // If proof type is EXISTING, account for account meta
862        if proof_type == TN_STATE_PROOF_TYPE_EXISTING {
863            if offset + TN_ACCOUNT_META_FOOTPRINT > bytes.len() {
864                return Err(RpcError::invalid_format());
865            }
866            offset += TN_ACCOUNT_META_FOOTPRINT;
867        }
868    }
869
870    // Add trailing signature size
871    offset += TN_TXN_SIGNATURE_SZ;
872
873    // Verify we don't exceed the provided bytes
874    if offset > bytes.len() {
875        return Err(RpcError::invalid_format());
876    }
877
878    Ok(offset)
879}
880
881/// Validate a transaction's account layout (count, duplicates, sort order).
882///
883/// Mirrors the C source of truth tn_validate_txn_accounts
884/// (src/thru/runtime/tn_txn_account_validate.c): a combined merge-walk detects
885/// sort-order violations, within-array duplicates, and cross-array (rw∩ro)
886/// duplicates in a single pass, with the same error precedence (unsorted before
887/// a fee_payer/program duplicate). The fee_payer/program-in-array check runs only
888/// after sort order is confirmed.
889pub fn validate_account_layout(
890    rw_accs: &[TnPubkey],
891    r_accs: &[TnPubkey],
892    fee_payer: &TnPubkey,
893    program: &TnPubkey,
894) -> Result<(), RpcError> {
895    let total_accounts = 2usize
896        .checked_add(rw_accs.len())
897        .and_then(|v| v.checked_add(r_accs.len()))
898        .ok_or_else(|| RpcError::too_many_accounts(usize::MAX, TN_TXN_MAX_ACCOUNTS))?;
899    if total_accounts > TN_TXN_MAX_ACCOUNTS {
900        return Err(RpcError::too_many_accounts(
901            total_accounts,
902            TN_TXN_MAX_ACCOUNTS,
903        ));
904    }
905    if fee_payer == program {
906        return Err(RpcError::duplicate_account());
907    }
908
909    let (mut i, mut j) = (0usize, 0usize);
910    let mut prev_rw: Option<&[u8; 32]> = None;
911    let mut prev_ro: Option<&[u8; 32]> = None;
912    while i < rw_accs.len() || j < r_accs.len() {
913        let use_rw = j >= r_accs.len() || (i < rw_accs.len() && rw_accs[i] <= r_accs[j]);
914        if use_rw {
915            let key = &rw_accs[i];
916            if j < r_accs.len() && *key == r_accs[j] {
917                return Err(RpcError::duplicate_account());
918            }
919            if let Some(prev) = prev_rw {
920                if prev == key {
921                    return Err(RpcError::duplicate_account());
922                }
923                if prev > key {
924                    return Err(RpcError::unsorted_readwrite_accounts());
925                }
926            }
927            prev_rw = Some(key);
928            i += 1;
929        } else {
930            let key = &r_accs[j];
931            if let Some(prev) = prev_ro {
932                if prev == key {
933                    return Err(RpcError::duplicate_account());
934                }
935                if prev > key {
936                    return Err(RpcError::unsorted_readonly_accounts());
937                }
938            }
939            prev_ro = Some(key);
940            j += 1;
941        }
942    }
943
944    for account in rw_accs.iter().chain(r_accs.iter()) {
945        if account == fee_payer || account == program {
946            return Err(RpcError::duplicate_account());
947        }
948    }
949
950    Ok(())
951}
952
953/// Validate a wire-format transaction for protocol correctness (matching C tn_txn_parse_core).
954pub fn validate_wire_transaction(bytes: &[u8]) -> Result<(), RpcError> {
955    const TN_TXN_MTU: usize = 32_768;
956    // Version and flags are now at offset 0 and 1
957    const TN_TXN_VERSION_OFFSET: usize = 0;
958    const TN_TXN_FLAGS_OFFSET: usize = 1;
959
960    use bytemuck::pod_read_unaligned;
961
962    // 1. Check payload size
963    if bytes.len() > TN_TXN_MTU {
964        return Err(RpcError::invalid_transaction_size(bytes.len(), TN_TXN_MTU));
965    }
966
967    // 2. Check minimum size
968    if bytes.len() < core::mem::size_of::<WireTxnHdrV1>() + TN_TXN_SIGNATURE_SZ {
969        return Err(RpcError::invalid_format());
970    }
971
972    // 3. Check transaction version
973    let transaction_version = bytes[TN_TXN_VERSION_OFFSET];
974    if transaction_version != 0x01 {
975        return Err(RpcError::invalid_version());
976    }
977
978    // 4. Check flags
979    let flags = bytes[TN_TXN_FLAGS_OFFSET];
980    // Clear the fee payer proof bit and check that all other bits are 0
981    let flags_without_proof_bit = flags & !(1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT);
982    let flags_cleared = flags_without_proof_bit & !(1 << TN_TXN_FLAG_MAY_COMPRESS_ACCOUNT_BIT);
983    if flags_cleared != 0 {
984        return Err(RpcError::invalid_flags());
985    }
986
987    // 5. Parse header
988    let hdr: WireTxnHdrV1 = pod_read_unaligned(&bytes[0..core::mem::size_of::<WireTxnHdrV1>()]);
989    let mut offset = core::mem::size_of::<WireTxnHdrV1>();
990
991    let sig_start = bytes.len() - TN_TXN_SIGNATURE_SZ;
992
993    // 6. Validate chain_id is non-zero (matches C tn_txn_parse.c:37)
994    if hdr.chain_id == 0 {
995        return Err(RpcError::invalid_chain_id());
996    }
997
998    // 6. Parse accounts
999    let accs_sz = (hdr.readwrite_accounts_cnt as usize + hdr.readonly_accounts_cnt as usize) * 32;
1000    if offset + accs_sz > sig_start {
1001        return Err(RpcError::invalid_format());
1002    }
1003    offset += accs_sz;
1004
1005    // 7. Parse instruction data
1006    let instr_sz = hdr.instr_data_sz as usize;
1007    if offset + instr_sz > sig_start {
1008        return Err(RpcError::invalid_format());
1009    }
1010    offset += instr_sz;
1011
1012    // 8. Handle fee payer state proof if present
1013    if has_fee_payer_state_proof(flags) {
1014        // Check state proof header size
1015        if offset + TN_STATE_PROOF_HDR_SIZE > sig_start {
1016            return Err(RpcError::invalid_format());
1017        }
1018
1019        let state_proof_data = &bytes[offset..sig_start];
1020
1021        // Extract and validate the proof type before using the footprint. Only
1022        // EXISTING and CREATION are valid; UPDATING and out-of-range types (e.g.
1023        // type 3) are rejected — matching C tn_txn_parse.c, where an invalid type
1024        // yields a zero footprint and is rejected before further parsing.
1025        let type_slot = u64::from_le_bytes([
1026            state_proof_data[0],
1027            state_proof_data[1],
1028            state_proof_data[2],
1029            state_proof_data[3],
1030            state_proof_data[4],
1031            state_proof_data[5],
1032            state_proof_data[6],
1033            state_proof_data[7],
1034        ]);
1035        let proof_type = extract_state_proof_type(type_slot);
1036        if proof_type != TN_STATE_PROOF_TYPE_EXISTING && proof_type != TN_STATE_PROOF_TYPE_CREATION
1037        {
1038            return Err(RpcError::invalid_fee_payer_state_proof_type());
1039        }
1040
1041        // Calculate state proof footprint
1042        let state_proof_sz = calculate_state_proof_footprint(state_proof_data)?;
1043
1044        if offset + state_proof_sz > sig_start {
1045            return Err(RpcError::invalid_format());
1046        }
1047
1048        offset += state_proof_sz;
1049
1050        // If proof type is EXISTING, expect account meta
1051        if proof_type == TN_STATE_PROOF_TYPE_EXISTING {
1052            if offset + TN_ACCOUNT_META_FOOTPRINT > sig_start {
1053                return Err(RpcError::invalid_format());
1054            }
1055            offset += TN_ACCOUNT_META_FOOTPRINT;
1056        }
1057    }
1058
1059    // 9. Check for exact size match (offset should be at signature start)
1060    if offset != sig_start {
1061        return Err(RpcError::trailing_bytes(
1062            offset + TN_TXN_SIGNATURE_SZ,
1063            bytes.len(),
1064        ));
1065    }
1066
1067    // 9b. Account-layout validation (count, duplicates, sort order) runs after
1068    // the whole wire structure is confirmed and before signature verification,
1069    // matching the C/Go order. Keep in sync with
1070    // src/thru/runtime/tn_txn_account_validate.c.
1071    {
1072        let accs_start = core::mem::size_of::<WireTxnHdrV1>();
1073        let rw_cnt = hdr.readwrite_accounts_cnt as usize;
1074        let ro_cnt = hdr.readonly_accounts_cnt as usize;
1075        let mut rw_accs: Vec<TnPubkey> = Vec::with_capacity(rw_cnt);
1076        for k in 0..rw_cnt {
1077            let s = accs_start + k * 32;
1078            let mut a = [0u8; 32];
1079            a.copy_from_slice(&bytes[s..s + 32]);
1080            rw_accs.push(a);
1081        }
1082        let ro_start = accs_start + rw_cnt * 32;
1083        let mut ro_accs: Vec<TnPubkey> = Vec::with_capacity(ro_cnt);
1084        for k in 0..ro_cnt {
1085            let s = ro_start + k * 32;
1086            let mut a = [0u8; 32];
1087            a.copy_from_slice(&bytes[s..s + 32]);
1088            ro_accs.push(a);
1089        }
1090        validate_account_layout(
1091            &rw_accs,
1092            &ro_accs,
1093            &hdr.fee_payer_pubkey,
1094            &hdr.program_pubkey,
1095        )?;
1096    }
1097
1098    // 10. Signature check
1099    let wire_for_signing = &bytes[..sig_start];
1100    let signature = &bytes[sig_start..];
1101    if verify_transaction(
1102        wire_for_signing,
1103        signature.try_into().expect("signature should be 64 bytes"),
1104        &hdr.fee_payer_pubkey,
1105    )
1106    .is_err()
1107    {
1108        return Err(RpcError::invalid_transaction_signature());
1109    }
1110
1111    Ok(())
1112}
1113
1114#[cfg(test)]
1115mod tests {
1116    use super::*;
1117    use ed25519_dalek::SigningKey;
1118
1119    #[test]
1120    fn transaction_resource_defaults_are_zero_and_overridable() {
1121        let tx = Transaction::new([1; 32], [2; 32], 1, 0);
1122        assert_eq!(&tx.to_wire()[8..16], &[0; 8]);
1123        let tx = tx
1124            .with_compute_units(123)
1125            .with_state_units(4)
1126            .with_memory_units(5);
1127        assert_eq!(&tx.to_wire()[8..16], &[123, 0, 0, 0, 4, 0, 5, 0]);
1128    }
1129
1130    fn make_valid_txn_bytes_with_flags(flags: u8) -> Vec<u8> {
1131        let signing_key = SigningKey::from(&[1u8; 32]);
1132        let verifying_key = signing_key.verifying_key();
1133        let mut tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42);
1134        tx.rw_accs = Some(vec![[3u8; 32], [4u8; 32]]);
1135        tx.r_accs = Some(vec![[5u8; 32]]);
1136        tx.instructions = Some(vec![1, 2, 3, 4]);
1137        tx.flags = flags;
1138        tx.sign(&signing_key.to_bytes()).unwrap();
1139        tx.to_wire()
1140    }
1141
1142    fn make_valid_txn_bytes() -> Vec<u8> {
1143        make_valid_txn_bytes_with_flags(0)
1144    }
1145
1146    #[test]
1147    fn test_tn_txn_size_basic_transaction() {
1148        let bytes = make_valid_txn_bytes();
1149        let calculated_size = tn_txn_size(&bytes).unwrap();
1150
1151        // The calculated size should match the actual bytes length
1152        assert_eq!(calculated_size, bytes.len());
1153    }
1154
1155    #[test]
1156    fn test_state_units_default_and_fee_payer_proof_minimum() {
1157        use crate::tn_state_proof::StateProof;
1158
1159        let state_proof = StateProof::creation(100, [0u8; 32], [7u8; 32], [8u8; 32], vec![]);
1160
1161        // Only transactions that create or grow state need state units.
1162        let tx = Transaction::new([1u8; 32], [2u8; 32], 100, 42);
1163        assert_eq!(tx.req_state_units, 0);
1164
1165        // A fee payer proof activates the fee payer, which needs one unit.
1166        let tx = Transaction::new([1u8; 32], [2u8; 32], 100, 42)
1167            .with_fee_payer_state_proof(&state_proof);
1168        assert_eq!(tx.req_state_units, 1);
1169
1170        // A larger request is kept.
1171        let tx = Transaction::new([1u8; 32], [2u8; 32], 100, 42)
1172            .with_state_units(3)
1173            .with_fee_payer_state_proof(&state_proof);
1174        assert_eq!(tx.req_state_units, 3);
1175
1176        // An explicit request after the proof still wins.
1177        let tx = Transaction::new([1u8; 32], [2u8; 32], 100, 42)
1178            .with_fee_payer_state_proof(&state_proof)
1179            .with_state_units(0);
1180        assert_eq!(tx.req_state_units, 0);
1181    }
1182
1183    #[test]
1184    fn test_tn_txn_size_with_state_proof() {
1185        use crate::tn_state_proof::StateProof;
1186
1187        let signing_key = SigningKey::from(&[1u8; 32]);
1188        let verifying_key = signing_key.verifying_key();
1189
1190        // Create a CREATION state proof
1191        let path_bitset = [0u8; 32]; // No set bits = no sibling hashes
1192        let existing_leaf_pubkey = [7u8; 32];
1193        let existing_leaf_hash = [8u8; 32];
1194        let state_proof = StateProof::creation(
1195            100,
1196            path_bitset,
1197            existing_leaf_pubkey,
1198            existing_leaf_hash,
1199            vec![],
1200        );
1201
1202        // Create transaction with state proof
1203        let mut tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42)
1204            .with_rw_accounts(vec![[3u8; 32]])
1205            .with_instructions(vec![1, 2, 3])
1206            .with_fee_payer_state_proof(&state_proof);
1207
1208        tx.sign(&signing_key.to_bytes()).unwrap();
1209        let bytes = tx.to_wire();
1210
1211        let calculated_size = tn_txn_size(&bytes).unwrap();
1212
1213        // The calculated size should match the actual bytes length
1214        assert_eq!(calculated_size, bytes.len());
1215    }
1216
1217    #[test]
1218    fn test_tn_txn_size_minimal_transaction() {
1219        let signing_key = SigningKey::from(&[1u8; 32]);
1220        let verifying_key = signing_key.verifying_key();
1221
1222        // Create minimal transaction (no accounts, no instructions)
1223        let mut tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42);
1224        tx.sign(&signing_key.to_bytes()).unwrap();
1225        let bytes = tx.to_wire();
1226
1227        let calculated_size = tn_txn_size(&bytes).unwrap();
1228
1229        // The calculated size should match the actual bytes length
1230        assert_eq!(calculated_size, bytes.len());
1231
1232        // Should be header size + trailing signature for minimal transaction
1233        let expected_min_size = core::mem::size_of::<WireTxnHdrV1>() + TN_TXN_SIGNATURE_SZ;
1234        assert_eq!(calculated_size, expected_min_size);
1235    }
1236
1237    #[test]
1238    fn test_tn_txn_size_invalid_format() {
1239        // Test with bytes too short for header
1240        let short_bytes = vec![0u8; 50];
1241        let result = tn_txn_size(&short_bytes);
1242        assert!(matches!(result, Err(RpcError::InvalidFormat)));
1243
1244        // Test with header but missing account data
1245        let mut bytes = make_valid_txn_bytes();
1246        bytes.truncate(core::mem::size_of::<WireTxnHdrV1>() + 10); // Truncate to cause missing data
1247        let result = tn_txn_size(&bytes);
1248        assert!(matches!(result, Err(RpcError::InvalidFormat)));
1249    }
1250
1251    #[test]
1252    fn test_tn_txn_size_consistency_with_validation() {
1253        let bytes = make_valid_txn_bytes();
1254
1255        // Both functions should succeed for valid transactions
1256        assert!(validate_wire_transaction(&bytes).is_ok());
1257        assert!(tn_txn_size(&bytes).is_ok());
1258
1259        // Size should match actual length
1260        let calculated_size = tn_txn_size(&bytes).unwrap();
1261        assert_eq!(calculated_size, bytes.len());
1262    }
1263
1264    #[test]
1265    fn test_valid_transaction() {
1266        let bytes = make_valid_txn_bytes();
1267        assert!(validate_wire_transaction(&bytes).is_ok());
1268    }
1269
1270    #[test]
1271    fn test_transaction_duplicate_accounts_rejected() {
1272        let signing_key = SigningKey::from(&[1u8; 32]);
1273        let fee = signing_key.verifying_key().to_bytes();
1274        let program = [2u8; 32];
1275        let a = [3u8; 32];
1276        let b = [4u8; 32];
1277
1278        let cases = [
1279            Transaction::new(fee, fee, 100, 42),
1280            Transaction::new(fee, program, 100, 42).with_rw_accounts(vec![fee]),
1281            Transaction::new(fee, program, 100, 42).with_r_accounts(vec![fee]),
1282            Transaction::new(fee, program, 100, 42).with_rw_accounts(vec![program]),
1283            Transaction::new(fee, program, 100, 42).with_r_accounts(vec![program]),
1284            Transaction::new(fee, program, 100, 42).with_rw_accounts(vec![a, a]),
1285            Transaction::new(fee, program, 100, 42).with_r_accounts(vec![a, a]),
1286            Transaction::new(fee, program, 100, 42)
1287                .with_rw_accounts(vec![a])
1288                .with_r_accounts(vec![a, b]),
1289        ];
1290
1291        for mut tx in cases {
1292            assert!(matches!(tx.validate(), Err(RpcError::DuplicateAccount)));
1293            assert!(matches!(tx.try_to_wire(), Err(RpcError::DuplicateAccount)));
1294            assert!(tx.sign(&signing_key.to_bytes()).is_err());
1295        }
1296    }
1297
1298    #[test]
1299    fn test_oversize_transaction() {
1300        let mut bytes = make_valid_txn_bytes();
1301        bytes.resize(32_769, 0);
1302        let err = validate_wire_transaction(&bytes).unwrap_err();
1303        assert!(matches!(
1304            err,
1305            RpcError::InvalidTransactionSize {
1306                size: 32_769,
1307                max_size: 32_768
1308            }
1309        ));
1310    }
1311
1312    #[test]
1313    fn test_trailing_bytes() {
1314        let mut bytes = make_valid_txn_bytes();
1315        let orig_len = bytes.len();
1316        // Insert a byte before the signature (trailing bytes between body and signature)
1317        bytes.insert(orig_len - TN_TXN_SIGNATURE_SZ, 0);
1318        let err = validate_wire_transaction(&bytes).unwrap_err();
1319        // Expected size changes due to new wire format (112-byte header instead of 176)
1320        assert!(matches!(err, RpcError::TrailingBytes { .. }));
1321    }
1322
1323    #[test]
1324    fn test_invalid_transaction_version() {
1325        let mut bytes = make_valid_txn_bytes();
1326        // Corrupt the transaction version
1327        bytes[0] = 0x00; // Invalid version
1328        let err = validate_wire_transaction(&bytes).unwrap_err();
1329        assert!(matches!(err, RpcError::InvalidVersion));
1330    }
1331
1332    #[test]
1333    fn test_invalid_flags() {
1334        // Set invalid flag bits (keeping fee payer proof bit, but adding others)
1335        let bytes = make_valid_txn_bytes_with_flags(0x07);
1336        let err = validate_wire_transaction(&bytes).unwrap_err();
1337        assert!(matches!(err, RpcError::InvalidFlags));
1338    }
1339
1340    #[test]
1341    fn test_invalid_chain_id_zero() {
1342        let mut bytes = make_valid_txn_bytes();
1343
1344        /* Modify chain_id field to 0 (chain_id is at offset 108-109 in WireTxnHdrV1) */
1345        let hdr: &mut WireTxnHdrV1 =
1346            bytemuck::from_bytes_mut(&mut bytes[0..core::mem::size_of::<WireTxnHdrV1>()]);
1347        hdr.chain_id = 0;
1348
1349        let err = validate_wire_transaction(&bytes).unwrap_err();
1350        assert!(matches!(err, RpcError::InvalidChainId));
1351    }
1352
1353    #[test]
1354    fn test_transaction_too_short() {
1355        let bytes = vec![0u8; 50]; // Too short for header
1356        let err = validate_wire_transaction(&bytes).unwrap_err();
1357        assert!(matches!(err, RpcError::InvalidFormat));
1358    }
1359
1360    #[test]
1361    fn test_transaction_with_state_proof() {
1362        use crate::tn_state_proof::{StateProof, StateProofType};
1363
1364        let signing_key = SigningKey::from(&[1u8; 32]);
1365        let verifying_key = signing_key.verifying_key();
1366
1367        // Create a CREATION state proof (doesn't require account meta)
1368        let path_bitset = [0u8; 32]; // No set bits = no sibling hashes
1369        let existing_leaf_pubkey = [7u8; 32];
1370        let existing_leaf_hash = [8u8; 32];
1371        let state_proof = StateProof::creation(
1372            100,
1373            path_bitset,
1374            existing_leaf_pubkey,
1375            existing_leaf_hash,
1376            vec![],
1377        );
1378
1379        // Create transaction with state proof
1380        let mut tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42)
1381            .with_fee_payer_state_proof(&state_proof);
1382
1383        // Verify flag is set
1384        assert!(tx.has_fee_payer_state_proof());
1385        assert_eq!(tx.flags & (1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT), 1);
1386
1387        tx.sign(&signing_key.to_bytes()).unwrap();
1388        let bytes = tx.to_wire();
1389
1390        // Verify state proof is included in wire format
1391        assert!(bytes.len() > core::mem::size_of::<WireTxnHdrV1>() + TN_TXN_SIGNATURE_SZ);
1392        assert!(validate_wire_transaction(&bytes).is_ok());
1393
1394        // Test deserialization
1395        let decoded_tx = Transaction::from_wire(&bytes).unwrap();
1396        assert!(decoded_tx.has_fee_payer_state_proof());
1397        assert!(decoded_tx.fee_payer_state_proof.is_some());
1398
1399        let decoded_proof = decoded_tx.fee_payer_state_proof.unwrap();
1400        assert_eq!(decoded_proof.proof_type(), StateProofType::Creation);
1401        assert_eq!(decoded_proof.slot(), 100);
1402    }
1403
1404    #[test]
1405    fn test_transaction_with_state_proof_serialization_round_trip() {
1406        use crate::tn_state_proof::StateProof;
1407
1408        let signing_key = SigningKey::from(&[1u8; 32]);
1409        let verifying_key = signing_key.verifying_key();
1410
1411        // Create a creation state proof with some sibling hashes
1412        let mut path_bitset = [0u8; 32];
1413        path_bitset[0] = 0b11; // Set first 2 bits for 2 sibling hashes
1414        let existing_leaf_pubkey = [7u8; 32];
1415        let existing_leaf_hash = [8u8; 32];
1416        let sibling_hashes = vec![[9u8; 32], [10u8; 32]];
1417
1418        let state_proof = StateProof::creation(
1419            200,
1420            path_bitset,
1421            existing_leaf_pubkey,
1422            existing_leaf_hash,
1423            sibling_hashes.clone(),
1424        );
1425
1426        // Create transaction with complex state proof
1427        let mut tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42)
1428            .with_rw_accounts(vec![[3u8; 32], [4u8; 32]])
1429            .with_r_accounts(vec![[5u8; 32]])
1430            .with_instructions(vec![1, 2, 3, 4])
1431            .with_fee_payer_state_proof(&state_proof);
1432
1433        tx.sign(&signing_key.to_bytes()).unwrap();
1434        let bytes = tx.to_wire();
1435
1436        // Test validation
1437        assert!(validate_wire_transaction(&bytes).is_ok());
1438
1439        // Test round-trip serialization
1440        let decoded_tx = Transaction::from_wire(&bytes).unwrap();
1441        assert_eq!(decoded_tx.fee_payer, tx.fee_payer);
1442        assert_eq!(decoded_tx.program, tx.program);
1443        assert_eq!(decoded_tx.rw_accs, tx.rw_accs);
1444        assert_eq!(decoded_tx.r_accs, tx.r_accs);
1445        assert_eq!(decoded_tx.instructions, tx.instructions);
1446        assert_eq!(decoded_tx.flags, tx.flags);
1447        assert!(decoded_tx.has_fee_payer_state_proof());
1448
1449        let decoded_proof = decoded_tx.fee_payer_state_proof.unwrap();
1450        assert_eq!(decoded_proof.slot(), 200);
1451        assert_eq!(decoded_proof.path_bitset(), &path_bitset);
1452    }
1453
1454    #[test]
1455    fn test_transaction_without_state_proof() {
1456        let signing_key = SigningKey::from(&[1u8; 32]);
1457        let verifying_key = signing_key.verifying_key();
1458
1459        let mut tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42);
1460
1461        // Verify flag is not set
1462        assert!(!tx.has_fee_payer_state_proof());
1463        assert_eq!(tx.flags & (1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT), 0);
1464        assert!(tx.fee_payer_state_proof.is_none());
1465
1466        tx.sign(&signing_key.to_bytes()).unwrap();
1467        let bytes = tx.to_wire();
1468
1469        assert!(validate_wire_transaction(&bytes).is_ok());
1470
1471        // Test deserialization
1472        let decoded_tx = Transaction::from_wire(&bytes).unwrap();
1473        assert!(!decoded_tx.has_fee_payer_state_proof());
1474        assert!(decoded_tx.fee_payer_state_proof.is_none());
1475    }
1476
1477    #[test]
1478    fn test_transaction_remove_state_proof() {
1479        use crate::tn_state_proof::StateProof;
1480
1481        let signing_key = SigningKey::from(&[1u8; 32]);
1482        let verifying_key = signing_key.verifying_key();
1483
1484        // Create a CREATION state proof
1485        let path_bitset = [0u8; 32];
1486        let existing_leaf_pubkey = [7u8; 32];
1487        let existing_leaf_hash = [8u8; 32];
1488        let state_proof = StateProof::creation(
1489            100,
1490            path_bitset,
1491            existing_leaf_pubkey,
1492            existing_leaf_hash,
1493            vec![],
1494        );
1495
1496        // Create transaction with state proof, then remove it
1497        let tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42)
1498            .with_fee_payer_state_proof(&state_proof)
1499            .without_fee_payer_state_proof();
1500
1501        // Verify flag is cleared and state proof is removed
1502        assert!(!tx.has_fee_payer_state_proof());
1503        assert_eq!(tx.flags & (1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT), 0);
1504        assert!(tx.fee_payer_state_proof.is_none());
1505    }
1506}