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    /// Sign the transaction through any [`Signer`](crate::signer::Signer)
456    /// (local key, HSM/MPC, hardware wallet).  Validates the account layout
457    /// first (like [`Transaction::sign`]), then builds the body with
458    /// [`Transaction::to_wire_for_signing`], asks the signer to sign the body
459    /// ([`Signer::sign_transaction_body`](crate::signer::Signer::sign_transaction_body)),
460    /// and strictly verifies the signature before attaching it
461    /// ([`crate::signer::attach_signature`]).  For a local Ed25519 key this
462    /// produces byte-identical output to [`Transaction::sign`].
463    pub fn sign_with_signer<S: crate::signer::Signer + ?Sized>(
464        &mut self,
465        signer: &S,
466    ) -> Result<(), Box<dyn std::error::Error>> {
467        self.sign_with_signer_wire(signer).map(|_| ())
468    }
469
470    /// Like [`Transaction::sign_with_signer`], and return the signed wire
471    /// (`body ‖ sig`) assembled from the frozen body snapshot that was
472    /// actually signed ([`crate::signer::attach_signature`]).  Submit these
473    /// bytes: they are exactly what the signer saw plus its signature.
474    pub fn sign_with_signer_wire<S: crate::signer::Signer + ?Sized>(
475        &mut self,
476        signer: &S,
477    ) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
478        self.validate()?;
479        let body = self.to_wire_for_signing();
480        let signed = crate::signer::sign_transaction_body_with(signer, &body)?;
481        self.attach_signed_wire(&signed)?;
482        Ok(signed)
483    }
484
485    /// Attach the signature from a signed wire `body ‖ sig` (as returned by
486    /// [`crate::signer::attach_signature`]) after checking that it is exactly
487    /// this transaction: `body` equals [`Transaction::to_wire_for_signing`],
488    /// the signature verifies over it under the fee payer, and
489    /// [`Transaction::to_wire`] with the signature attached reproduces
490    /// `signed` byte for byte.  Nothing is attached on any mismatch, so a
491    /// signature is never paired with re-serialized bytes that differ from
492    /// the bytes that were signed.
493    pub fn attach_signed_wire(&mut self, signed: &[u8]) -> Result<(), RpcError> {
494        let body = self.to_wire_for_signing();
495        if signed.len() != body.len() + 64 || signed[..body.len()] != body[..] {
496            return Err(RpcError::InvalidParams(
497                "signed bytes do not match this transaction's signing body",
498            ));
499        }
500        let mut sig = [0u8; 64];
501        sig.copy_from_slice(&signed[body.len()..]);
502        verify_transaction(&body, &sig, &self.fee_payer)
503            .map_err(|_| RpcError::InvalidTransactionSignature)?;
504        let previous = self.signature.replace(sig);
505        if self.serialize_wire() != signed {
506            self.signature = previous;
507            return Err(RpcError::InvalidParams(
508                "the transaction's wire serialization differs from the signed bytes",
509            ));
510        }
511        Ok(())
512    }
513
514    /// Validate account count and duplicate-account rules before signing or serialization.
515    pub fn validate(&self) -> Result<(), RpcError> {
516        let rw_accs = self.rw_accs.as_deref().unwrap_or(&[]);
517        let r_accs = self.r_accs.as_deref().unwrap_or(&[]);
518        validate_account_layout(rw_accs, r_accs, &self.fee_payer, &self.program)
519    }
520
521    /// Verify the transaction signature
522    pub fn verify(&self) -> bool {
523        if let Some(sig_bytes) = &self.signature {
524            let wire_bytes = self.to_wire_for_signing();
525            return verify_transaction(&wire_bytes, sig_bytes, &self.fee_payer).is_ok();
526        }
527        false
528    }
529
530    /// Create wire format for signing (excluding trailing signature)
531    /// The message is: header + accounts + instr_data + state_proof + account_meta
532    pub fn to_wire_for_signing(&self) -> Vec<u8> {
533        // Zero out all bytes first to ensure deterministic padding
534        let mut wire: WireTxnHdrV1 = unsafe { core::mem::zeroed() };
535        wire.transaction_version = 1;
536        wire.flags = self.flags;
537        wire.readwrite_accounts_cnt = self.rw_accs.as_ref().map_or(0, |v| v.len() as u16);
538        wire.readonly_accounts_cnt = self.r_accs.as_ref().map_or(0, |v| v.len() as u16);
539        wire.instr_data_sz = self.instructions.as_ref().map_or(0, |v| v.len() as u16);
540        wire.req_compute_units = self.req_compute_units;
541        wire.req_state_units = self.req_state_units;
542        wire.req_memory_units = self.req_memory_units;
543        wire.expiry_after = self.expiry_after;
544        wire.chain_id = self.chain_id;
545        wire.fee = self.fee;
546        wire.nonce = self.nonce;
547        wire.start_slot = self.start_slot;
548        wire.fee_payer_pubkey = self.fee_payer;
549        wire.program_pubkey = self.program;
550
551        let mut result = bytes_of(&wire).to_vec();
552
553        // Append variable-length data
554        if let Some(ref rw_accs) = self.rw_accs {
555            for acc in rw_accs {
556                result.extend_from_slice(acc);
557            }
558        }
559
560        if let Some(ref r_accs) = self.r_accs {
561            for acc in r_accs {
562                result.extend_from_slice(acc);
563            }
564        }
565
566        if let Some(ref instructions) = self.instructions {
567            result.extend_from_slice(instructions);
568        }
569
570        // Append state proof if present
571        if let Some(ref state_proof) = self.fee_payer_state_proof {
572            result.extend_from_slice(&state_proof.to_wire());
573        }
574
575        // Use raw account meta if available, otherwise use structured account meta
576        if let Some(ref fee_payer_account_meta_raw) = self.fee_payer_account_meta_raw {
577            result.extend_from_slice(fee_payer_account_meta_raw);
578        }
579
580        result
581    }
582
583    /// Serialize to on-wire format (WireTxnHdrV1).
584    /// Wire format: header + accounts + instr_data + state_proof + account_meta + signature
585    ///
586    /// This is INFALLIBLE and does NOT validate account layout: it must remain
587    /// usable for re-serializing transactions that were ingested from the
588    /// network/block store (which may predate, or otherwise violate, the
589    /// duplicate-account rules — e.g. a stored poison transaction served via
590    /// getTransactionRaw). Validation is enforced at the construction boundary
591    /// (`sign`) and is available explicitly via `try_to_wire`.
592    pub fn to_wire(&self) -> Vec<u8> {
593        self.serialize_wire()
594    }
595
596    /// Fallible serialization: validate account layout, then serialize.
597    /// Use this for newly-built transactions that must satisfy the
598    /// duplicate/sort/count rules before going on the wire.
599    pub fn try_to_wire(&self) -> Result<Vec<u8>, RpcError> {
600        self.validate()?;
601        Ok(self.serialize_wire())
602    }
603
604    /// Internal: pure serialization with no validation.
605    fn serialize_wire(&self) -> Vec<u8> {
606        let mut wire = WireTxnHdrV1::default();
607        wire.transaction_version = 1;
608        wire.flags = self.flags;
609        wire.readwrite_accounts_cnt = self.rw_accs.as_ref().map_or(0, |v| v.len() as u16);
610        wire.readonly_accounts_cnt = self.r_accs.as_ref().map_or(0, |v| v.len() as u16);
611        wire.instr_data_sz = self.instructions.as_ref().map_or(0, |v| v.len() as u16);
612        wire.req_compute_units = self.req_compute_units;
613        wire.req_state_units = self.req_state_units;
614        wire.req_memory_units = self.req_memory_units;
615        wire.expiry_after = self.expiry_after;
616        wire.chain_id = self.chain_id;
617        wire.fee = self.fee;
618        wire.nonce = self.nonce;
619        wire.start_slot = self.start_slot;
620        wire.fee_payer_pubkey = self.fee_payer;
621        wire.program_pubkey = self.program;
622
623        let mut result = bytes_of(&wire).to_vec();
624
625        // Append variable-length data
626        if let Some(ref rw_accs) = self.rw_accs {
627            for acc in rw_accs {
628                result.extend_from_slice(acc);
629            }
630        }
631
632        if let Some(ref r_accs) = self.r_accs {
633            for acc in r_accs {
634                result.extend_from_slice(acc);
635            }
636        }
637
638        if let Some(ref instructions) = self.instructions {
639            result.extend_from_slice(instructions);
640        }
641
642        // Append state proof if present (after instruction data)
643        if let Some(ref state_proof) = self.fee_payer_state_proof {
644            result.extend_from_slice(&state_proof.to_wire());
645        }
646
647        // Use raw account meta if available, otherwise use structured account meta
648        if let Some(ref fee_payer_account_meta_raw) = self.fee_payer_account_meta_raw {
649            result.extend_from_slice(fee_payer_account_meta_raw);
650        }
651
652        // Append signature at the END (last 64 bytes)
653        if let Some(sig) = &self.signature {
654            result.extend_from_slice(sig);
655        } else {
656            // Zero signature if not set
657            result.extend_from_slice(&[0u8; TN_TXN_SIGNATURE_SZ]);
658        }
659
660        result
661    }
662
663    /// Deserialize from on-wire format (WireTxnHdrV1)
664    /// Wire format: header + accounts + instr_data + state_proof + account_meta + signature (at end)
665    pub fn from_wire(bytes: &[u8]) -> Option<Self> {
666        // Minimum size: header + signature at end
667        if bytes.len() < core::mem::size_of::<WireTxnHdrV1>() + TN_TXN_SIGNATURE_SZ {
668            return None;
669        }
670
671        let wire: WireTxnHdrV1 =
672            pod_read_unaligned(&bytes[0..core::mem::size_of::<WireTxnHdrV1>()]);
673        let mut offset = core::mem::size_of::<WireTxnHdrV1>();
674
675        let sig_start = bytes.len() - TN_TXN_SIGNATURE_SZ;
676        let mut signature = [0u8; TN_TXN_SIGNATURE_SZ];
677        signature.copy_from_slice(&bytes[sig_start..]);
678
679        // Parse read-write accounts
680        let rw_accs = if wire.readwrite_accounts_cnt > 0 {
681            let mut accounts = Vec::new();
682            for _ in 0..wire.readwrite_accounts_cnt {
683                if offset + 32 > sig_start {
684                    return None;
685                }
686                let mut acc = [0u8; 32];
687                acc.copy_from_slice(&bytes[offset..offset + 32]);
688                accounts.push(acc);
689                offset += 32;
690            }
691            Some(accounts)
692        } else {
693            None
694        };
695
696        // Parse read-only accounts
697        let r_accs = if wire.readonly_accounts_cnt > 0 {
698            let mut accounts = Vec::new();
699            for _ in 0..wire.readonly_accounts_cnt {
700                if offset + 32 > sig_start {
701                    return None;
702                }
703                let mut acc = [0u8; 32];
704                acc.copy_from_slice(&bytes[offset..offset + 32]);
705                accounts.push(acc);
706                offset += 32;
707            }
708            Some(accounts)
709        } else {
710            None
711        };
712
713        // Parse instructions
714        let instructions = if wire.instr_data_sz > 0 {
715            if offset + wire.instr_data_sz as usize > sig_start {
716                return None;
717            }
718            let instr = bytes[offset..offset + wire.instr_data_sz as usize].to_vec();
719            offset += wire.instr_data_sz as usize;
720            Some(instr)
721        } else {
722            None
723        };
724
725        let mut fee_payer_account_meta_raw: Option<Vec<u8>> = None;
726        // Parse state proof if present
727        let fee_payer_state_proof = if has_fee_payer_state_proof(wire.flags) {
728            if offset >= sig_start {
729                return None;
730            }
731            let state_proof_bytes = &bytes[offset..sig_start];
732            if let Some(state_proof) = StateProof::from_wire(state_proof_bytes) {
733                offset += state_proof.footprint();
734                if state_proof.header.proof_type == StateProofType::Existing {
735                    if offset + TN_ACCOUNT_META_FOOTPRINT > sig_start {
736                        return None;
737                    }
738                    let account_meta_bytes = &bytes[offset..offset + TN_ACCOUNT_META_FOOTPRINT];
739                    fee_payer_account_meta_raw = Some(account_meta_bytes.to_vec());
740                    offset += TN_ACCOUNT_META_FOOTPRINT;
741                }
742                Some(state_proof)
743            } else {
744                return None;
745            }
746        } else {
747            None
748        };
749
750        // Verify we've consumed all bytes before signature
751        if offset != sig_start {
752            log::warn!(
753                "Transaction::from_wire: offset != sig_start ({} != {})",
754                offset,
755                sig_start
756            );
757            return None;
758        }
759
760        Some(Transaction {
761            fee_payer: wire.fee_payer_pubkey,
762            program: wire.program_pubkey,
763            rw_accs,
764            r_accs,
765            instructions,
766            flags: wire.flags,
767            chain_id: wire.chain_id,
768            fee: wire.fee,
769            req_compute_units: wire.req_compute_units,
770            req_state_units: wire.req_state_units,
771            req_memory_units: wire.req_memory_units,
772            expiry_after: wire.expiry_after,
773            start_slot: wire.start_slot,
774            nonce: wire.nonce,
775            signature: Some(signature),
776            fee_payer_state_proof,
777            fee_payer_account_meta_raw,
778        })
779    }
780
781    /// Accessor: read a field from serialized bytes by name
782    pub fn get_field_from_wire(bytes: &[u8], field: &str) -> Option<Vec<u8>> {
783        if bytes.len() < core::mem::size_of::<WireTxnHdrV1>() + TN_TXN_SIGNATURE_SZ {
784            return None;
785        }
786        let wire: WireTxnHdrV1 =
787            pod_read_unaligned(&bytes[0..core::mem::size_of::<WireTxnHdrV1>()]);
788        match field {
789            "fee_payer_signature" => {
790                let sig_start = bytes.len() - TN_TXN_SIGNATURE_SZ;
791                Some(bytes[sig_start..].to_vec())
792            }
793            "transaction_version" => Some(vec![wire.transaction_version]),
794            "flags" => Some(vec![wire.flags]),
795            "readwrite_accounts_cnt" => Some(wire.readwrite_accounts_cnt.to_le_bytes().to_vec()),
796            "readonly_accounts_cnt" => Some(wire.readonly_accounts_cnt.to_le_bytes().to_vec()),
797            "instr_data_sz" => Some(wire.instr_data_sz.to_le_bytes().to_vec()),
798            "req_compute_units" => Some(wire.req_compute_units.to_le_bytes().to_vec()),
799            "req_state_units" => Some(wire.req_state_units.to_le_bytes().to_vec()),
800            "req_memory_units" => Some(wire.req_memory_units.to_le_bytes().to_vec()),
801            "expiry_after" => Some(wire.expiry_after.to_le_bytes().to_vec()),
802            "chain_id" => Some(wire.chain_id.to_le_bytes().to_vec()),
803            "fee" => Some(wire.fee.to_le_bytes().to_vec()),
804            "nonce" => Some(wire.nonce.to_le_bytes().to_vec()),
805            "start_slot" => Some(wire.start_slot.to_le_bytes().to_vec()),
806            "fee_payer_pubkey" => Some(wire.fee_payer_pubkey.to_vec()),
807            "program_pubkey" => Some(wire.program_pubkey.to_vec()),
808            _ => None,
809        }
810    }
811}
812
813/// Helper function to check if transaction has fee payer state proof
814fn has_fee_payer_state_proof(flags: u8) -> bool {
815    (flags & (1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT)) != 0
816}
817
818/// Helper function to extract state proof type from header
819fn extract_state_proof_type(type_slot: u64) -> u64 {
820    (type_slot >> 62) & 0x3 // Extract top 2 bits
821}
822
823/// Helper function to calculate state proof footprint from header
824fn calculate_state_proof_footprint(state_proof_data: &[u8]) -> Result<usize, RpcError> {
825    if state_proof_data.len() < TN_STATE_PROOF_HDR_SIZE {
826        return Err(RpcError::invalid_format());
827    }
828
829    // Extract type_slot (first 8 bytes)
830    let type_slot = u64::from_le_bytes([
831        state_proof_data[0],
832        state_proof_data[1],
833        state_proof_data[2],
834        state_proof_data[3],
835        state_proof_data[4],
836        state_proof_data[5],
837        state_proof_data[6],
838        state_proof_data[7],
839    ]);
840
841    // Extract path_bitset (next 32 bytes) and count set bits
842    let mut sibling_hash_cnt = 0u32;
843    for i in 0..4 {
844        let start = 8 + i * 8;
845        let word = u64::from_le_bytes([
846            state_proof_data[start],
847            state_proof_data[start + 1],
848            state_proof_data[start + 2],
849            state_proof_data[start + 3],
850            state_proof_data[start + 4],
851            state_proof_data[start + 5],
852            state_proof_data[start + 6],
853            state_proof_data[start + 7],
854        ]);
855        sibling_hash_cnt += word.count_ones();
856    }
857
858    let proof_type = extract_state_proof_type(type_slot);
859    let body_sz = (proof_type + sibling_hash_cnt as u64) * 32; // Each hash is 32 bytes
860
861    Ok(TN_STATE_PROOF_HDR_SIZE + body_sz as usize)
862}
863
864pub fn tn_txn_size(bytes: &[u8]) -> Result<usize, RpcError> {
865    // Basic size checks
866    if bytes.len() < core::mem::size_of::<WireTxnHdrV1>() + TN_TXN_SIGNATURE_SZ {
867        return Err(RpcError::invalid_format());
868    }
869
870    // Parse the header
871    // Use read_unaligned to safely read from potentially unaligned memory
872    let hdr: WireTxnHdrV1 =
873        unsafe { std::ptr::read_unaligned(bytes.as_ptr() as *const WireTxnHdrV1) };
874    let hdr = &hdr;
875    let mut offset = core::mem::size_of::<WireTxnHdrV1>();
876
877    // Calculate accounts size
878    let accs_sz = (hdr.readwrite_accounts_cnt as usize + hdr.readonly_accounts_cnt as usize) * 32;
879    if offset + accs_sz > bytes.len() {
880        return Err(RpcError::invalid_format());
881    }
882    offset += accs_sz;
883
884    // Calculate instruction data size
885    let instr_sz = hdr.instr_data_sz as usize;
886    if offset + instr_sz > bytes.len() {
887        return Err(RpcError::invalid_format());
888    }
889    offset += instr_sz;
890
891    // Handle fee payer state proof if present
892    if has_fee_payer_state_proof(hdr.flags) {
893        // Check state proof header size
894        if offset + TN_STATE_PROOF_HDR_SIZE > bytes.len() {
895            return Err(RpcError::invalid_format());
896        }
897
898        // Calculate state proof footprint
899        let state_proof_data = &bytes[offset..];
900        let state_proof_sz = calculate_state_proof_footprint(state_proof_data)?;
901
902        if offset + state_proof_sz > bytes.len() {
903            return Err(RpcError::invalid_format());
904        }
905        offset += state_proof_sz;
906
907        // Extract proof type for additional validation
908        let type_slot = u64::from_le_bytes([
909            state_proof_data[0],
910            state_proof_data[1],
911            state_proof_data[2],
912            state_proof_data[3],
913            state_proof_data[4],
914            state_proof_data[5],
915            state_proof_data[6],
916            state_proof_data[7],
917        ]);
918        let proof_type = extract_state_proof_type(type_slot);
919
920        // If proof type is EXISTING, account for account meta
921        if proof_type == TN_STATE_PROOF_TYPE_EXISTING {
922            if offset + TN_ACCOUNT_META_FOOTPRINT > bytes.len() {
923                return Err(RpcError::invalid_format());
924            }
925            offset += TN_ACCOUNT_META_FOOTPRINT;
926        }
927    }
928
929    // Add trailing signature size
930    offset += TN_TXN_SIGNATURE_SZ;
931
932    // Verify we don't exceed the provided bytes
933    if offset > bytes.len() {
934        return Err(RpcError::invalid_format());
935    }
936
937    Ok(offset)
938}
939
940/// Validate a transaction's account layout (count, duplicates, sort order).
941///
942/// Mirrors the C source of truth tn_validate_txn_accounts
943/// (src/thru/runtime/tn_txn_account_validate.c): a combined merge-walk detects
944/// sort-order violations, within-array duplicates, and cross-array (rw∩ro)
945/// duplicates in a single pass, with the same error precedence (unsorted before
946/// a fee_payer/program duplicate). The fee_payer/program-in-array check runs only
947/// after sort order is confirmed.
948pub fn validate_account_layout(
949    rw_accs: &[TnPubkey],
950    r_accs: &[TnPubkey],
951    fee_payer: &TnPubkey,
952    program: &TnPubkey,
953) -> Result<(), RpcError> {
954    let total_accounts = 2usize
955        .checked_add(rw_accs.len())
956        .and_then(|v| v.checked_add(r_accs.len()))
957        .ok_or_else(|| RpcError::too_many_accounts(usize::MAX, TN_TXN_MAX_ACCOUNTS))?;
958    if total_accounts > TN_TXN_MAX_ACCOUNTS {
959        return Err(RpcError::too_many_accounts(
960            total_accounts,
961            TN_TXN_MAX_ACCOUNTS,
962        ));
963    }
964    if fee_payer == program {
965        return Err(RpcError::duplicate_account());
966    }
967
968    let (mut i, mut j) = (0usize, 0usize);
969    let mut prev_rw: Option<&[u8; 32]> = None;
970    let mut prev_ro: Option<&[u8; 32]> = None;
971    while i < rw_accs.len() || j < r_accs.len() {
972        let use_rw = j >= r_accs.len() || (i < rw_accs.len() && rw_accs[i] <= r_accs[j]);
973        if use_rw {
974            let key = &rw_accs[i];
975            if j < r_accs.len() && *key == r_accs[j] {
976                return Err(RpcError::duplicate_account());
977            }
978            if let Some(prev) = prev_rw {
979                if prev == key {
980                    return Err(RpcError::duplicate_account());
981                }
982                if prev > key {
983                    return Err(RpcError::unsorted_readwrite_accounts());
984                }
985            }
986            prev_rw = Some(key);
987            i += 1;
988        } else {
989            let key = &r_accs[j];
990            if let Some(prev) = prev_ro {
991                if prev == key {
992                    return Err(RpcError::duplicate_account());
993                }
994                if prev > key {
995                    return Err(RpcError::unsorted_readonly_accounts());
996                }
997            }
998            prev_ro = Some(key);
999            j += 1;
1000        }
1001    }
1002
1003    for account in rw_accs.iter().chain(r_accs.iter()) {
1004        if account == fee_payer || account == program {
1005            return Err(RpcError::duplicate_account());
1006        }
1007    }
1008
1009    Ok(())
1010}
1011
1012/// Validate a wire-format transaction for protocol correctness (matching C tn_txn_parse_core).
1013pub fn validate_wire_transaction(bytes: &[u8]) -> Result<(), RpcError> {
1014    const TN_TXN_MTU: usize = 32_768;
1015    // Version and flags are now at offset 0 and 1
1016    const TN_TXN_VERSION_OFFSET: usize = 0;
1017    const TN_TXN_FLAGS_OFFSET: usize = 1;
1018
1019    use bytemuck::pod_read_unaligned;
1020
1021    // 1. Check payload size
1022    if bytes.len() > TN_TXN_MTU {
1023        return Err(RpcError::invalid_transaction_size(bytes.len(), TN_TXN_MTU));
1024    }
1025
1026    // 2. Check minimum size
1027    if bytes.len() < core::mem::size_of::<WireTxnHdrV1>() + TN_TXN_SIGNATURE_SZ {
1028        return Err(RpcError::invalid_format());
1029    }
1030
1031    // 3. Check transaction version
1032    let transaction_version = bytes[TN_TXN_VERSION_OFFSET];
1033    if transaction_version != 0x01 {
1034        return Err(RpcError::invalid_version());
1035    }
1036
1037    // 4. Check flags
1038    let flags = bytes[TN_TXN_FLAGS_OFFSET];
1039    // Clear the fee payer proof bit and check that all other bits are 0
1040    let flags_without_proof_bit = flags & !(1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT);
1041    let flags_cleared = flags_without_proof_bit & !(1 << TN_TXN_FLAG_MAY_COMPRESS_ACCOUNT_BIT);
1042    if flags_cleared != 0 {
1043        return Err(RpcError::invalid_flags());
1044    }
1045
1046    // 5. Parse header
1047    let hdr: WireTxnHdrV1 = pod_read_unaligned(&bytes[0..core::mem::size_of::<WireTxnHdrV1>()]);
1048    let mut offset = core::mem::size_of::<WireTxnHdrV1>();
1049
1050    let sig_start = bytes.len() - TN_TXN_SIGNATURE_SZ;
1051
1052    // 6. Validate chain_id is non-zero (matches C tn_txn_parse.c:37)
1053    if hdr.chain_id == 0 {
1054        return Err(RpcError::invalid_chain_id());
1055    }
1056
1057    // 6. Parse accounts
1058    let accs_sz = (hdr.readwrite_accounts_cnt as usize + hdr.readonly_accounts_cnt as usize) * 32;
1059    if offset + accs_sz > sig_start {
1060        return Err(RpcError::invalid_format());
1061    }
1062    offset += accs_sz;
1063
1064    // 7. Parse instruction data
1065    let instr_sz = hdr.instr_data_sz as usize;
1066    if offset + instr_sz > sig_start {
1067        return Err(RpcError::invalid_format());
1068    }
1069    offset += instr_sz;
1070
1071    // 8. Handle fee payer state proof if present
1072    if has_fee_payer_state_proof(flags) {
1073        // Check state proof header size
1074        if offset + TN_STATE_PROOF_HDR_SIZE > sig_start {
1075            return Err(RpcError::invalid_format());
1076        }
1077
1078        let state_proof_data = &bytes[offset..sig_start];
1079
1080        // Extract and validate the proof type before using the footprint. Only
1081        // EXISTING and CREATION are valid; UPDATING and out-of-range types (e.g.
1082        // type 3) are rejected — matching C tn_txn_parse.c, where an invalid type
1083        // yields a zero footprint and is rejected before further parsing.
1084        let type_slot = u64::from_le_bytes([
1085            state_proof_data[0],
1086            state_proof_data[1],
1087            state_proof_data[2],
1088            state_proof_data[3],
1089            state_proof_data[4],
1090            state_proof_data[5],
1091            state_proof_data[6],
1092            state_proof_data[7],
1093        ]);
1094        let proof_type = extract_state_proof_type(type_slot);
1095        if proof_type != TN_STATE_PROOF_TYPE_EXISTING && proof_type != TN_STATE_PROOF_TYPE_CREATION
1096        {
1097            return Err(RpcError::invalid_fee_payer_state_proof_type());
1098        }
1099
1100        // Calculate state proof footprint
1101        let state_proof_sz = calculate_state_proof_footprint(state_proof_data)?;
1102
1103        if offset + state_proof_sz > sig_start {
1104            return Err(RpcError::invalid_format());
1105        }
1106
1107        offset += state_proof_sz;
1108
1109        // If proof type is EXISTING, expect account meta
1110        if proof_type == TN_STATE_PROOF_TYPE_EXISTING {
1111            if offset + TN_ACCOUNT_META_FOOTPRINT > sig_start {
1112                return Err(RpcError::invalid_format());
1113            }
1114            offset += TN_ACCOUNT_META_FOOTPRINT;
1115        }
1116    }
1117
1118    // 9. Check for exact size match (offset should be at signature start)
1119    if offset != sig_start {
1120        return Err(RpcError::trailing_bytes(
1121            offset + TN_TXN_SIGNATURE_SZ,
1122            bytes.len(),
1123        ));
1124    }
1125
1126    // 9b. Account-layout validation (count, duplicates, sort order) runs after
1127    // the whole wire structure is confirmed and before signature verification,
1128    // matching the C/Go order. Keep in sync with
1129    // src/thru/runtime/tn_txn_account_validate.c.
1130    {
1131        let accs_start = core::mem::size_of::<WireTxnHdrV1>();
1132        let rw_cnt = hdr.readwrite_accounts_cnt as usize;
1133        let ro_cnt = hdr.readonly_accounts_cnt as usize;
1134        let mut rw_accs: Vec<TnPubkey> = Vec::with_capacity(rw_cnt);
1135        for k in 0..rw_cnt {
1136            let s = accs_start + k * 32;
1137            let mut a = [0u8; 32];
1138            a.copy_from_slice(&bytes[s..s + 32]);
1139            rw_accs.push(a);
1140        }
1141        let ro_start = accs_start + rw_cnt * 32;
1142        let mut ro_accs: Vec<TnPubkey> = Vec::with_capacity(ro_cnt);
1143        for k in 0..ro_cnt {
1144            let s = ro_start + k * 32;
1145            let mut a = [0u8; 32];
1146            a.copy_from_slice(&bytes[s..s + 32]);
1147            ro_accs.push(a);
1148        }
1149        validate_account_layout(
1150            &rw_accs,
1151            &ro_accs,
1152            &hdr.fee_payer_pubkey,
1153            &hdr.program_pubkey,
1154        )?;
1155    }
1156
1157    // 10. Signature check
1158    let wire_for_signing = &bytes[..sig_start];
1159    let signature = &bytes[sig_start..];
1160    if verify_transaction(
1161        wire_for_signing,
1162        signature.try_into().expect("signature should be 64 bytes"),
1163        &hdr.fee_payer_pubkey,
1164    )
1165    .is_err()
1166    {
1167        return Err(RpcError::invalid_transaction_signature());
1168    }
1169
1170    Ok(())
1171}
1172
1173#[cfg(test)]
1174mod tests {
1175    use super::*;
1176    use ed25519_dalek::SigningKey;
1177
1178    #[test]
1179    fn transaction_resource_defaults_are_zero_and_overridable() {
1180        let tx = Transaction::new([1; 32], [2; 32], 1, 0);
1181        assert_eq!(&tx.to_wire()[8..16], &[0; 8]);
1182        let tx = tx
1183            .with_compute_units(123)
1184            .with_state_units(4)
1185            .with_memory_units(5);
1186        assert_eq!(&tx.to_wire()[8..16], &[123, 0, 0, 0, 4, 0, 5, 0]);
1187    }
1188
1189    fn make_valid_txn_bytes_with_flags(flags: u8) -> Vec<u8> {
1190        let signing_key = SigningKey::from(&[1u8; 32]);
1191        let verifying_key = signing_key.verifying_key();
1192        let mut tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42);
1193        tx.rw_accs = Some(vec![[3u8; 32], [4u8; 32]]);
1194        tx.r_accs = Some(vec![[5u8; 32]]);
1195        tx.instructions = Some(vec![1, 2, 3, 4]);
1196        tx.flags = flags;
1197        tx.sign(&signing_key.to_bytes()).unwrap();
1198        tx.to_wire()
1199    }
1200
1201    fn make_valid_txn_bytes() -> Vec<u8> {
1202        make_valid_txn_bytes_with_flags(0)
1203    }
1204
1205    #[test]
1206    fn sign_with_signer_is_byte_identical_to_sign() {
1207        use crate::signer::LocalSigner;
1208        let seed = [1u8; 32];
1209        let fee_payer = SigningKey::from(&seed).verifying_key().to_bytes();
1210        let build = || {
1211            let mut tx = Transaction::new(fee_payer, [2u8; 32], 100, 42)
1212                .with_chain_id(7)
1213                .with_start_slot(9)
1214                .with_expiry_after(100)
1215                .with_compute_units(1234);
1216            tx.rw_accs = Some(vec![[3u8; 32], [4u8; 32]]);
1217            tx.r_accs = Some(vec![[5u8; 32]]);
1218            tx.instructions = Some(vec![1, 2, 3, 4]);
1219            tx
1220        };
1221        let mut old = build();
1222        old.sign(&seed).unwrap();
1223        let mut new = build();
1224        new.sign_with_signer(&LocalSigner::from_seed(seed)).unwrap();
1225        assert_eq!(old.to_wire(), new.to_wire());
1226        assert!(new.verify());
1227    }
1228
1229    #[test]
1230    fn sign_with_signer_validates_layout_and_key() {
1231        use crate::signer::LocalSigner;
1232        let seed = [1u8; 32];
1233        let fee_payer = SigningKey::from(&seed).verifying_key().to_bytes();
1234        // Duplicate account: rejected before signing, like `sign`.
1235        let mut tx = Transaction::new(fee_payer, [2u8; 32], 100, 42);
1236        tx.rw_accs = Some(vec![[3u8; 32], [3u8; 32]]);
1237        assert!(tx.sign_with_signer(&LocalSigner::from_seed(seed)).is_err());
1238        assert!(tx.signature.is_none());
1239        // Wrong key for the fee payer: rejected, nothing attached.
1240        let mut tx = Transaction::new(fee_payer, [2u8; 32], 100, 42);
1241        let wrong_key = LocalSigner::from_seed([9u8; 32]);
1242        assert!(tx.sign_with_signer(&wrong_key).is_err());
1243        assert!(tx.signature.is_none());
1244    }
1245
1246    /// Audit A-042: the signature is attached to the exact bytes that were
1247    /// signed.  `sign_with_signer_wire` returns the frozen `body ‖ sig`, which
1248    /// equals `to_wire()`, and `attach_signed_wire` refuses signed bytes that
1249    /// do not match this transaction (attaching nothing).
1250    #[test]
1251    fn signed_wire_is_the_exact_signed_body() {
1252        use crate::signer::{LocalSigner, sign_transaction_body_with};
1253        let seed = [1u8; 32];
1254        let signer = LocalSigner::from_seed(seed);
1255        let fee_payer = SigningKey::from(&seed).verifying_key().to_bytes();
1256        let build = || {
1257            let mut tx = Transaction::new(fee_payer, [2u8; 32], 100, 42).with_chain_id(7);
1258            tx.rw_accs = Some(vec![[3u8; 32], [4u8; 32]]);
1259            tx.instructions = Some(vec![1, 2, 3, 4]);
1260            tx
1261        };
1262        let mut tx = build();
1263        let signed = tx.sign_with_signer_wire(&signer).unwrap();
1264        assert_eq!(signed, tx.to_wire());
1265        assert_eq!(&signed[..signed.len() - 64], &tx.to_wire_for_signing()[..]);
1266        assert!(tx.verify());
1267
1268        // Signed bytes for a different body (another nonce): refused, and the
1269        // unsigned transaction stays unsigned.
1270        let mut other = build();
1271        other.nonce = 43;
1272        let other_signed =
1273            sign_transaction_body_with(&signer, &other.to_wire_for_signing()).unwrap();
1274        let mut target = build();
1275        assert!(target.attach_signed_wire(&other_signed).is_err());
1276        assert!(target.signature.is_none());
1277        // Right body, corrupted signature: refused.
1278        let mut bad = signed.clone();
1279        *bad.last_mut().unwrap() ^= 1;
1280        assert!(target.attach_signed_wire(&bad).is_err());
1281        assert!(target.signature.is_none());
1282        // Truncated: refused.
1283        let truncated = &signed[..signed.len() - 1];
1284        assert!(target.attach_signed_wire(truncated).is_err());
1285        // The genuine bytes attach.
1286        target.attach_signed_wire(&signed).unwrap();
1287        assert_eq!(target.to_wire(), signed);
1288    }
1289
1290    #[test]
1291    fn test_tn_txn_size_basic_transaction() {
1292        let bytes = make_valid_txn_bytes();
1293        let calculated_size = tn_txn_size(&bytes).unwrap();
1294
1295        // The calculated size should match the actual bytes length
1296        assert_eq!(calculated_size, bytes.len());
1297    }
1298
1299    #[test]
1300    fn test_state_units_default_and_fee_payer_proof_minimum() {
1301        use crate::tn_state_proof::StateProof;
1302
1303        let state_proof = StateProof::creation(100, [0u8; 32], [7u8; 32], [8u8; 32], vec![]);
1304
1305        // Only transactions that create or grow state need state units.
1306        let tx = Transaction::new([1u8; 32], [2u8; 32], 100, 42);
1307        assert_eq!(tx.req_state_units, 0);
1308
1309        // A fee payer proof activates the fee payer, which needs one unit.
1310        let tx = Transaction::new([1u8; 32], [2u8; 32], 100, 42)
1311            .with_fee_payer_state_proof(&state_proof);
1312        assert_eq!(tx.req_state_units, 1);
1313
1314        // A larger request is kept.
1315        let tx = Transaction::new([1u8; 32], [2u8; 32], 100, 42)
1316            .with_state_units(3)
1317            .with_fee_payer_state_proof(&state_proof);
1318        assert_eq!(tx.req_state_units, 3);
1319
1320        // An explicit request after the proof still wins.
1321        let tx = Transaction::new([1u8; 32], [2u8; 32], 100, 42)
1322            .with_fee_payer_state_proof(&state_proof)
1323            .with_state_units(0);
1324        assert_eq!(tx.req_state_units, 0);
1325    }
1326
1327    #[test]
1328    fn test_tn_txn_size_with_state_proof() {
1329        use crate::tn_state_proof::StateProof;
1330
1331        let signing_key = SigningKey::from(&[1u8; 32]);
1332        let verifying_key = signing_key.verifying_key();
1333
1334        // Create a CREATION state proof
1335        let path_bitset = [0u8; 32]; // No set bits = no sibling hashes
1336        let existing_leaf_pubkey = [7u8; 32];
1337        let existing_leaf_hash = [8u8; 32];
1338        let state_proof = StateProof::creation(
1339            100,
1340            path_bitset,
1341            existing_leaf_pubkey,
1342            existing_leaf_hash,
1343            vec![],
1344        );
1345
1346        // Create transaction with state proof
1347        let mut tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42)
1348            .with_rw_accounts(vec![[3u8; 32]])
1349            .with_instructions(vec![1, 2, 3])
1350            .with_fee_payer_state_proof(&state_proof);
1351
1352        tx.sign(&signing_key.to_bytes()).unwrap();
1353        let bytes = tx.to_wire();
1354
1355        let calculated_size = tn_txn_size(&bytes).unwrap();
1356
1357        // The calculated size should match the actual bytes length
1358        assert_eq!(calculated_size, bytes.len());
1359    }
1360
1361    #[test]
1362    fn test_tn_txn_size_minimal_transaction() {
1363        let signing_key = SigningKey::from(&[1u8; 32]);
1364        let verifying_key = signing_key.verifying_key();
1365
1366        // Create minimal transaction (no accounts, no instructions)
1367        let mut tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42);
1368        tx.sign(&signing_key.to_bytes()).unwrap();
1369        let bytes = tx.to_wire();
1370
1371        let calculated_size = tn_txn_size(&bytes).unwrap();
1372
1373        // The calculated size should match the actual bytes length
1374        assert_eq!(calculated_size, bytes.len());
1375
1376        // Should be header size + trailing signature for minimal transaction
1377        let expected_min_size = core::mem::size_of::<WireTxnHdrV1>() + TN_TXN_SIGNATURE_SZ;
1378        assert_eq!(calculated_size, expected_min_size);
1379    }
1380
1381    #[test]
1382    fn test_tn_txn_size_invalid_format() {
1383        // Test with bytes too short for header
1384        let short_bytes = vec![0u8; 50];
1385        let result = tn_txn_size(&short_bytes);
1386        assert!(matches!(result, Err(RpcError::InvalidFormat)));
1387
1388        // Test with header but missing account data
1389        let mut bytes = make_valid_txn_bytes();
1390        bytes.truncate(core::mem::size_of::<WireTxnHdrV1>() + 10); // Truncate to cause missing data
1391        let result = tn_txn_size(&bytes);
1392        assert!(matches!(result, Err(RpcError::InvalidFormat)));
1393    }
1394
1395    #[test]
1396    fn test_tn_txn_size_consistency_with_validation() {
1397        let bytes = make_valid_txn_bytes();
1398
1399        // Both functions should succeed for valid transactions
1400        assert!(validate_wire_transaction(&bytes).is_ok());
1401        assert!(tn_txn_size(&bytes).is_ok());
1402
1403        // Size should match actual length
1404        let calculated_size = tn_txn_size(&bytes).unwrap();
1405        assert_eq!(calculated_size, bytes.len());
1406    }
1407
1408    #[test]
1409    fn test_valid_transaction() {
1410        let bytes = make_valid_txn_bytes();
1411        assert!(validate_wire_transaction(&bytes).is_ok());
1412    }
1413
1414    #[test]
1415    fn test_transaction_duplicate_accounts_rejected() {
1416        let signing_key = SigningKey::from(&[1u8; 32]);
1417        let fee = signing_key.verifying_key().to_bytes();
1418        let program = [2u8; 32];
1419        let a = [3u8; 32];
1420        let b = [4u8; 32];
1421
1422        let cases = [
1423            Transaction::new(fee, fee, 100, 42),
1424            Transaction::new(fee, program, 100, 42).with_rw_accounts(vec![fee]),
1425            Transaction::new(fee, program, 100, 42).with_r_accounts(vec![fee]),
1426            Transaction::new(fee, program, 100, 42).with_rw_accounts(vec![program]),
1427            Transaction::new(fee, program, 100, 42).with_r_accounts(vec![program]),
1428            Transaction::new(fee, program, 100, 42).with_rw_accounts(vec![a, a]),
1429            Transaction::new(fee, program, 100, 42).with_r_accounts(vec![a, a]),
1430            Transaction::new(fee, program, 100, 42)
1431                .with_rw_accounts(vec![a])
1432                .with_r_accounts(vec![a, b]),
1433        ];
1434
1435        for mut tx in cases {
1436            assert!(matches!(tx.validate(), Err(RpcError::DuplicateAccount)));
1437            assert!(matches!(tx.try_to_wire(), Err(RpcError::DuplicateAccount)));
1438            assert!(tx.sign(&signing_key.to_bytes()).is_err());
1439        }
1440    }
1441
1442    #[test]
1443    fn test_oversize_transaction() {
1444        let mut bytes = make_valid_txn_bytes();
1445        bytes.resize(32_769, 0);
1446        let err = validate_wire_transaction(&bytes).unwrap_err();
1447        assert!(matches!(
1448            err,
1449            RpcError::InvalidTransactionSize {
1450                size: 32_769,
1451                max_size: 32_768
1452            }
1453        ));
1454    }
1455
1456    #[test]
1457    fn test_trailing_bytes() {
1458        let mut bytes = make_valid_txn_bytes();
1459        let orig_len = bytes.len();
1460        // Insert a byte before the signature (trailing bytes between body and signature)
1461        bytes.insert(orig_len - TN_TXN_SIGNATURE_SZ, 0);
1462        let err = validate_wire_transaction(&bytes).unwrap_err();
1463        // Expected size changes due to new wire format (112-byte header instead of 176)
1464        assert!(matches!(err, RpcError::TrailingBytes { .. }));
1465    }
1466
1467    #[test]
1468    fn test_invalid_transaction_version() {
1469        let mut bytes = make_valid_txn_bytes();
1470        // Corrupt the transaction version
1471        bytes[0] = 0x00; // Invalid version
1472        let err = validate_wire_transaction(&bytes).unwrap_err();
1473        assert!(matches!(err, RpcError::InvalidVersion));
1474    }
1475
1476    #[test]
1477    fn test_invalid_flags() {
1478        // Set invalid flag bits (keeping fee payer proof bit, but adding others)
1479        let bytes = make_valid_txn_bytes_with_flags(0x07);
1480        let err = validate_wire_transaction(&bytes).unwrap_err();
1481        assert!(matches!(err, RpcError::InvalidFlags));
1482    }
1483
1484    #[test]
1485    fn test_invalid_chain_id_zero() {
1486        let mut bytes = make_valid_txn_bytes();
1487
1488        /* Modify chain_id field to 0 (chain_id is at offset 108-109 in WireTxnHdrV1) */
1489        let hdr: &mut WireTxnHdrV1 =
1490            bytemuck::from_bytes_mut(&mut bytes[0..core::mem::size_of::<WireTxnHdrV1>()]);
1491        hdr.chain_id = 0;
1492
1493        let err = validate_wire_transaction(&bytes).unwrap_err();
1494        assert!(matches!(err, RpcError::InvalidChainId));
1495    }
1496
1497    #[test]
1498    fn test_transaction_too_short() {
1499        let bytes = vec![0u8; 50]; // Too short for header
1500        let err = validate_wire_transaction(&bytes).unwrap_err();
1501        assert!(matches!(err, RpcError::InvalidFormat));
1502    }
1503
1504    #[test]
1505    fn test_transaction_with_state_proof() {
1506        use crate::tn_state_proof::{StateProof, StateProofType};
1507
1508        let signing_key = SigningKey::from(&[1u8; 32]);
1509        let verifying_key = signing_key.verifying_key();
1510
1511        // Create a CREATION state proof (doesn't require account meta)
1512        let path_bitset = [0u8; 32]; // No set bits = no sibling hashes
1513        let existing_leaf_pubkey = [7u8; 32];
1514        let existing_leaf_hash = [8u8; 32];
1515        let state_proof = StateProof::creation(
1516            100,
1517            path_bitset,
1518            existing_leaf_pubkey,
1519            existing_leaf_hash,
1520            vec![],
1521        );
1522
1523        // Create transaction with state proof
1524        let mut tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42)
1525            .with_fee_payer_state_proof(&state_proof);
1526
1527        // Verify flag is set
1528        assert!(tx.has_fee_payer_state_proof());
1529        assert_eq!(tx.flags & (1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT), 1);
1530
1531        tx.sign(&signing_key.to_bytes()).unwrap();
1532        let bytes = tx.to_wire();
1533
1534        // Verify state proof is included in wire format
1535        assert!(bytes.len() > core::mem::size_of::<WireTxnHdrV1>() + TN_TXN_SIGNATURE_SZ);
1536        assert!(validate_wire_transaction(&bytes).is_ok());
1537
1538        // Test deserialization
1539        let decoded_tx = Transaction::from_wire(&bytes).unwrap();
1540        assert!(decoded_tx.has_fee_payer_state_proof());
1541        assert!(decoded_tx.fee_payer_state_proof.is_some());
1542
1543        let decoded_proof = decoded_tx.fee_payer_state_proof.unwrap();
1544        assert_eq!(decoded_proof.proof_type(), StateProofType::Creation);
1545        assert_eq!(decoded_proof.slot(), 100);
1546    }
1547
1548    #[test]
1549    fn test_transaction_with_state_proof_serialization_round_trip() {
1550        use crate::tn_state_proof::StateProof;
1551
1552        let signing_key = SigningKey::from(&[1u8; 32]);
1553        let verifying_key = signing_key.verifying_key();
1554
1555        // Create a creation state proof with some sibling hashes
1556        let mut path_bitset = [0u8; 32];
1557        path_bitset[0] = 0b11; // Set first 2 bits for 2 sibling hashes
1558        let existing_leaf_pubkey = [7u8; 32];
1559        let existing_leaf_hash = [8u8; 32];
1560        let sibling_hashes = vec![[9u8; 32], [10u8; 32]];
1561
1562        let state_proof = StateProof::creation(
1563            200,
1564            path_bitset,
1565            existing_leaf_pubkey,
1566            existing_leaf_hash,
1567            sibling_hashes.clone(),
1568        );
1569
1570        // Create transaction with complex state proof
1571        let mut tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42)
1572            .with_rw_accounts(vec![[3u8; 32], [4u8; 32]])
1573            .with_r_accounts(vec![[5u8; 32]])
1574            .with_instructions(vec![1, 2, 3, 4])
1575            .with_fee_payer_state_proof(&state_proof);
1576
1577        tx.sign(&signing_key.to_bytes()).unwrap();
1578        let bytes = tx.to_wire();
1579
1580        // Test validation
1581        assert!(validate_wire_transaction(&bytes).is_ok());
1582
1583        // Test round-trip serialization
1584        let decoded_tx = Transaction::from_wire(&bytes).unwrap();
1585        assert_eq!(decoded_tx.fee_payer, tx.fee_payer);
1586        assert_eq!(decoded_tx.program, tx.program);
1587        assert_eq!(decoded_tx.rw_accs, tx.rw_accs);
1588        assert_eq!(decoded_tx.r_accs, tx.r_accs);
1589        assert_eq!(decoded_tx.instructions, tx.instructions);
1590        assert_eq!(decoded_tx.flags, tx.flags);
1591        assert!(decoded_tx.has_fee_payer_state_proof());
1592
1593        let decoded_proof = decoded_tx.fee_payer_state_proof.unwrap();
1594        assert_eq!(decoded_proof.slot(), 200);
1595        assert_eq!(decoded_proof.path_bitset(), &path_bitset);
1596    }
1597
1598    #[test]
1599    fn test_transaction_without_state_proof() {
1600        let signing_key = SigningKey::from(&[1u8; 32]);
1601        let verifying_key = signing_key.verifying_key();
1602
1603        let mut tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42);
1604
1605        // Verify flag is not set
1606        assert!(!tx.has_fee_payer_state_proof());
1607        assert_eq!(tx.flags & (1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT), 0);
1608        assert!(tx.fee_payer_state_proof.is_none());
1609
1610        tx.sign(&signing_key.to_bytes()).unwrap();
1611        let bytes = tx.to_wire();
1612
1613        assert!(validate_wire_transaction(&bytes).is_ok());
1614
1615        // Test deserialization
1616        let decoded_tx = Transaction::from_wire(&bytes).unwrap();
1617        assert!(!decoded_tx.has_fee_payer_state_proof());
1618        assert!(decoded_tx.fee_payer_state_proof.is_none());
1619    }
1620
1621    #[test]
1622    fn test_transaction_remove_state_proof() {
1623        use crate::tn_state_proof::StateProof;
1624
1625        let signing_key = SigningKey::from(&[1u8; 32]);
1626        let verifying_key = signing_key.verifying_key();
1627
1628        // Create a CREATION state proof
1629        let path_bitset = [0u8; 32];
1630        let existing_leaf_pubkey = [7u8; 32];
1631        let existing_leaf_hash = [8u8; 32];
1632        let state_proof = StateProof::creation(
1633            100,
1634            path_bitset,
1635            existing_leaf_pubkey,
1636            existing_leaf_hash,
1637            vec![],
1638        );
1639
1640        // Create transaction with state proof, then remove it
1641        let tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42)
1642            .with_fee_payer_state_proof(&state_proof)
1643            .without_fee_payer_state_proof();
1644
1645        // Verify flag is cleared and state proof is removed
1646        assert!(!tx.has_fee_payer_state_proof());
1647        assert_eq!(tx.flags & (1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT), 0);
1648        assert!(tx.fee_payer_state_proof.is_none());
1649    }
1650}