Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
//! Transaction library: normal Rust struct, signing, serialization, accessors
//!

pub type TnPubkey = [u8; 32];
pub type TnHash = [u8; 32];
pub type TnSignature = [u8; 64];

use crate::{
    StateProofType,
    tn_signature::{sign_transaction, verify_transaction},
    tn_state_proof::StateProof,
};
use bytemuck::{Pod, Zeroable, bytes_of, pod_read_unaligned};

pub const TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT: u8 = 0; // Bit position (matching C #define TN_TXN_FLAG_HAS_FEE_PAYER_PROOF (0U))
pub const TN_TXN_FLAG_MAY_COMPRESS_ACCOUNT_BIT: u8 = 1; // Bit position (matching C #define TN_TXN_FLAG_MAY_COMPRESS_ACCOUNT (1U))

// State proof type constants (matching C implementation)
pub const TN_STATE_PROOF_TYPE_EXISTING: u64 = 0x0;
pub const TN_STATE_PROOF_TYPE_UPDATING: u64 = 0x1;
pub const TN_STATE_PROOF_TYPE_CREATION: u64 = 0x2;

// State proof header size constants
pub const TN_STATE_PROOF_HDR_SIZE: usize = 40; // 8 bytes type_slot + 32 bytes path_bitset
pub const TN_ACCOUNT_META_FOOTPRINT: usize = 64; // Size of tn_account_meta_t (matching C sizeof)

// TEMPORARY: Minimal local RpcError for test pass (remove when shared error type is available)
#[derive(Debug, PartialEq)]
pub enum RpcError {
    InvalidTransactionSize { size: usize, max_size: usize },
    TrailingBytes { expected: usize, found: usize },
    TooManyAccounts { count: usize, max_count: usize },
    InvalidTransactionSignature,
    InvalidParams(&'static str),
    InvalidFormat,
    InvalidVersion,
    InvalidFlags,
    InvalidFeePayerStateProofType,
    InvalidChainId,
    DuplicateAccount,
    UnsortedReadwriteAccounts,
    UnsortedReadonlyAccounts,
}

impl std::fmt::Display for RpcError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RpcError::InvalidTransactionSize { size, max_size } => {
                write!(
                    f,
                    "Transaction size {} exceeds maximum allowed size {}",
                    size, max_size
                )
            }
            RpcError::TrailingBytes { expected, found } => {
                write!(
                    f,
                    "Transaction has trailing bytes: expected {} bytes, found {} bytes",
                    expected, found
                )
            }
            RpcError::TooManyAccounts { count, max_count } => {
                write!(
                    f,
                    "Too many accounts: {} exceeds maximum {}",
                    count, max_count
                )
            }
            RpcError::InvalidTransactionSignature => {
                write!(f, "Invalid transaction signature")
            }
            RpcError::InvalidParams(msg) => {
                write!(f, "Invalid parameters: {}", msg)
            }
            RpcError::InvalidFormat => {
                write!(f, "Invalid transaction format")
            }
            RpcError::InvalidVersion => {
                write!(f, "Invalid transaction version")
            }
            RpcError::InvalidFlags => {
                write!(f, "Invalid transaction flags")
            }
            RpcError::InvalidFeePayerStateProofType => {
                write!(f, "Invalid fee payer state proof type")
            }
            RpcError::InvalidChainId => {
                write!(f, "Invalid chain ID: chain_id cannot be zero")
            }
            RpcError::DuplicateAccount => {
                write!(f, "Duplicate account in transaction")
            }
            RpcError::UnsortedReadwriteAccounts => {
                write!(f, "Read-write accounts are not strictly ascending")
            }
            RpcError::UnsortedReadonlyAccounts => {
                write!(f, "Read-only accounts are not strictly ascending")
            }
        }
    }
}

impl std::error::Error for RpcError {}

impl RpcError {
    pub fn invalid_transaction_size(size: usize, max_size: usize) -> Self {
        Self::InvalidTransactionSize { size, max_size }
    }
    pub fn trailing_bytes(expected: usize, found: usize) -> Self {
        Self::TrailingBytes { expected, found }
    }
    pub fn too_many_accounts(count: usize, max_count: usize) -> Self {
        Self::TooManyAccounts { count, max_count }
    }
    pub fn invalid_transaction_signature() -> Self {
        Self::InvalidTransactionSignature
    }
    pub fn invalid_params(msg: &'static str) -> Self {
        Self::InvalidParams(msg)
    }
    pub fn invalid_format() -> Self {
        Self::InvalidFormat
    }
    pub fn invalid_version() -> Self {
        Self::InvalidVersion
    }
    pub fn invalid_flags() -> Self {
        Self::InvalidFlags
    }
    pub fn invalid_fee_payer_state_proof_type() -> Self {
        Self::InvalidFeePayerStateProofType
    }
    pub fn invalid_chain_id() -> Self {
        Self::InvalidChainId
    }
    pub fn duplicate_account() -> Self {
        Self::DuplicateAccount
    }
    pub fn unsorted_readwrite_accounts() -> Self {
        Self::UnsortedReadwriteAccounts
    }
    pub fn unsorted_readonly_accounts() -> Self {
        Self::UnsortedReadonlyAccounts
    }
}

/// On-wire transaction header (matches TnTxnHdrV1 layout)
///
/// Transaction wire format:
///   [header (112 bytes)]
///   [input_pubkeys (variable)]
///   [instr_data (variable)]
///   [state_proof (optional)]
///   [account_meta (optional)]
///   [fee_payer_signature (64 bytes)]
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct WireTxnHdrV1 {
    pub transaction_version: u8,
    pub flags: u8,
    pub readwrite_accounts_cnt: u16,
    pub readonly_accounts_cnt: u16,
    pub instr_data_sz: u16,
    pub req_compute_units: u32,
    pub req_state_units: u16,
    pub req_memory_units: u16,
    pub fee: u64,
    pub nonce: u64,
    pub start_slot: u64,
    pub expiry_after: u32,
    pub chain_id: u16,
    pub padding_0: [u8; 2],
    pub fee_payer_pubkey: [u8; 32],
    pub program_pubkey: [u8; 32],
}

/// Size of the signature in bytes (always at end of transaction)
pub const TN_TXN_SIGNATURE_SZ: usize = 64;
pub const TN_TXN_MAX_ACCOUNTS: usize = 1024;

impl Default for WireTxnHdrV1 {
    fn default() -> Self {
        Self {
            transaction_version: 0,
            flags: 0,
            readwrite_accounts_cnt: 0,
            readonly_accounts_cnt: 0,
            instr_data_sz: 0,
            req_compute_units: 0,
            req_state_units: 0,
            req_memory_units: 0,
            fee: 0,
            nonce: 0,
            start_slot: 0,
            expiry_after: 0,
            chain_id: 0,
            padding_0: [0u8; 2],
            fee_payer_pubkey: [0u8; 32],
            program_pubkey: [0u8; 32],
        }
    }
}

// Manual Pod implementation to avoid derive issues
unsafe impl Pod for WireTxnHdrV1 {}
unsafe impl Zeroable for WireTxnHdrV1 {}

/// Normal Rust struct for transaction construction
#[derive(Clone, Debug, Default)]
pub struct Transaction {
    // Core transaction fields
    pub fee_payer: TnPubkey, // [u8; 32] - who pays the fee
    pub program: TnPubkey,   // [u8; 32] - target program

    // Account lists (optional)
    pub rw_accs: Option<Vec<TnPubkey>>, // read-write accounts
    pub r_accs: Option<Vec<TnPubkey>>,  // read-only accounts

    // Instruction data (optional)
    pub instructions: Option<Vec<u8>>, // instruction bytes

    // Transaction parameters
    pub fee: u64,               // transaction fee
    pub req_compute_units: u32, // requested compute units
    pub req_state_units: u16,   // requested state units
    pub req_memory_units: u16,  // requested memory units
    pub expiry_after: u32,      // expiry time offset
    pub start_slot: u64,        // starting slot
    pub nonce: u64,             // transaction nonce
    pub flags: u8,              // transaction flags
    pub chain_id: u16,          // chain identifier (must be non-zero)

    // Signature (optional until signed)
    pub signature: Option<TnSignature>, // [u8; 64] - Ed25519 signature

    // Fee payer state proof (optional)
    pub fee_payer_state_proof: Option<StateProof>, // State proof for fee payer account

    pub fee_payer_account_meta_raw: Option<Vec<u8>>,
}

impl Transaction {
    /// Create a new unsigned transaction
    pub fn new(fee_payer: TnPubkey, program: TnPubkey, fee: u64, nonce: u64) -> Self {
        Self {
            fee_payer,
            program,
            rw_accs: None,
            r_accs: None,
            instructions: None,
            fee,
            req_compute_units: 0,
            req_state_units: 0,
            req_memory_units: 0,
            expiry_after: 0,
            start_slot: 0,
            nonce,
            flags: 0,
            chain_id: 1,
            signature: None,
            fee_payer_state_proof: None,
            fee_payer_account_meta_raw: None,
        }
    }

    /// Create a minimal transaction with just a program ID and instruction data.
    /// Used for fake event transactions that don't need accounts or fees.
    pub fn new_raw_instruction(
        fee_payer: &TnPubkey,
        program: &TnPubkey,
        instruction_data: &[u8],
    ) -> Result<Self, Box<dyn std::error::Error>> {
        Ok(Self {
            fee_payer: *fee_payer,
            program: *program,
            rw_accs: None,
            r_accs: None,
            instructions: Some(instruction_data.to_vec()),
            fee: 0,
            req_compute_units: 0,
            req_state_units: 0,
            req_memory_units: 0,
            expiry_after: 0,
            start_slot: 0,
            nonce: 0,
            flags: 0,
            chain_id: 1,
            signature: None,
            fee_payer_state_proof: None,
            fee_payer_account_meta_raw: None,
        })
    }

    pub fn has_fee_payer_state_proof(&self) -> bool {
        (self.flags & (1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT)) != 0
    }
    pub fn may_compress_account(&self) -> bool {
        (self.flags & (1 << TN_TXN_FLAG_MAY_COMPRESS_ACCOUNT_BIT)) != 0
    }

    pub fn get_signature(&self) -> Option<crate::Signature> {
        if let Some(sig) = &self.signature {
            return Some(crate::Signature::from_bytes(&sig));
        }
        None
    }

    pub fn with_may_compress_account(mut self) -> Self {
        self.flags |= 1 << TN_TXN_FLAG_MAY_COMPRESS_ACCOUNT_BIT;
        self
    }

    /// Builder method: set fee payer state proof
    pub fn with_fee_payer_state_proof(mut self, state_proof: &StateProof) -> Self {
        self.fee_payer_state_proof = Some(state_proof.clone());
        // Set the flag bit to indicate presence of state proof
        self.flags |= 1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT;
        self
    }

    /// Builder method: set fee payer account meta as raw bytes
    pub fn with_fee_payer_account_meta_raw(mut self, account_meta_raw: Vec<u8>) -> Self {
        self.fee_payer_account_meta_raw = Some(account_meta_raw);
        self
    }

    /// Builder method: remove fee payer state proof
    pub fn without_fee_payer_state_proof(mut self) -> Self {
        self.fee_payer_state_proof = None;
        // Clear the flag bit to indicate absence of state proof
        self.flags &= !(1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT);
        self
    }

    /// Builder method: add read-write accounts
    pub fn with_rw_accounts(mut self, accounts: Vec<TnPubkey>) -> Self {
        self.rw_accs = Some(accounts);
        self
    }

    /// Builder method: add read-only accounts
    pub fn with_r_accounts(mut self, accounts: Vec<TnPubkey>) -> Self {
        self.r_accs = Some(accounts);
        self
    }

    /// Builder method: add a single read-write account
    pub fn add_rw_account(mut self, account: TnPubkey) -> Self {
        match self.rw_accs {
            Some(ref mut accounts) => accounts.push(account),
            None => self.rw_accs = Some(vec![account]),
        }
        self
    }

    /// Builder method: add a single read-only account
    pub fn add_r_account(mut self, account: TnPubkey) -> Self {
        match self.r_accs {
            Some(ref mut accounts) => accounts.push(account),
            None => self.r_accs = Some(vec![account]),
        }
        self
    }

    /// Builder method: add instruction data
    pub fn with_instructions(mut self, instructions: Vec<u8>) -> Self {
        self.instructions = Some(instructions);
        self
    }

    /// Builder method: set compute units
    pub fn with_compute_units(mut self, units: u32) -> Self {
        self.req_compute_units = units;
        self
    }

    /// Builder method: set state units
    pub fn with_state_units(mut self, units: u16) -> Self {
        self.req_state_units = units;
        self
    }

    /// Builder method: set memory units
    pub fn with_memory_units(mut self, units: u16) -> Self {
        self.req_memory_units = units;
        self
    }

    /// Builder method: set expiry
    pub fn with_expiry_after(mut self, expiry: u32) -> Self {
        self.expiry_after = expiry;
        self
    }

    /// Builder method: set nonce
    pub fn with_nonce(mut self, nonce: u64) -> Self {
        self.nonce = nonce;
        self
    }

    /// Builder method: set start slot
    pub fn with_start_slot(mut self, slot: u64) -> Self {
        self.start_slot = slot;
        self
    }

    /// Builder method: set chain ID
    pub fn with_chain_id(mut self, chain_id: u16) -> Self {
        self.chain_id = chain_id;
        self
    }

    /// Sign the transaction with a 32-byte Ed25519 private key.
    /// Validates the account layout first, so a transaction with duplicate,
    /// unsorted, or too-many accounts is rejected before signing.
    pub fn sign(&mut self, private_key: &[u8; 32]) -> Result<(), Box<dyn std::error::Error>> {
        self.validate()
            .map_err(|e| Box::<dyn std::error::Error>::from(e))?;
        self.sign_unchecked(private_key)
    }

    /// Sign WITHOUT validating the account layout. Intended for constructing
    /// intentionally-invalid transactions (e.g. negative tests that submit a
    /// malformed txn and expect the server to reject it). Production callers
    /// should use `sign`, which validates first.
    pub fn sign_unchecked(
        &mut self,
        private_key: &[u8; 32],
    ) -> Result<(), Box<dyn std::error::Error>> {
        let wire_bytes = self.to_wire_for_signing();
        let sig = sign_transaction(&wire_bytes, &self.fee_payer, private_key)
            .map_err(|e| Box::<dyn std::error::Error>::from(e))?;
        self.signature = Some(sig);
        Ok(())
    }

    /// Validate account count and duplicate-account rules before signing or serialization.
    pub fn validate(&self) -> Result<(), RpcError> {
        let rw_accs = self.rw_accs.as_deref().unwrap_or(&[]);
        let r_accs = self.r_accs.as_deref().unwrap_or(&[]);
        validate_account_layout(rw_accs, r_accs, &self.fee_payer, &self.program)
    }

    /// Verify the transaction signature
    pub fn verify(&self) -> bool {
        if let Some(sig_bytes) = &self.signature {
            let wire_bytes = self.to_wire_for_signing();
            return verify_transaction(&wire_bytes, sig_bytes, &self.fee_payer).is_ok();
        }
        false
    }

    /// Create wire format for signing (excluding trailing signature)
    /// The message is: header + accounts + instr_data + state_proof + account_meta
    fn to_wire_for_signing(&self) -> Vec<u8> {
        // Zero out all bytes first to ensure deterministic padding
        let mut wire: WireTxnHdrV1 = unsafe { core::mem::zeroed() };
        wire.transaction_version = 1;
        wire.flags = self.flags;
        wire.readwrite_accounts_cnt = self.rw_accs.as_ref().map_or(0, |v| v.len() as u16);
        wire.readonly_accounts_cnt = self.r_accs.as_ref().map_or(0, |v| v.len() as u16);
        wire.instr_data_sz = self.instructions.as_ref().map_or(0, |v| v.len() as u16);
        wire.req_compute_units = self.req_compute_units;
        wire.req_state_units = self.req_state_units;
        wire.req_memory_units = self.req_memory_units;
        wire.expiry_after = self.expiry_after;
        wire.chain_id = self.chain_id;
        wire.fee = self.fee;
        wire.nonce = self.nonce;
        wire.start_slot = self.start_slot;
        wire.fee_payer_pubkey = self.fee_payer;
        wire.program_pubkey = self.program;

        let mut result = bytes_of(&wire).to_vec();

        // Append variable-length data
        if let Some(ref rw_accs) = self.rw_accs {
            for acc in rw_accs {
                result.extend_from_slice(acc);
            }
        }

        if let Some(ref r_accs) = self.r_accs {
            for acc in r_accs {
                result.extend_from_slice(acc);
            }
        }

        if let Some(ref instructions) = self.instructions {
            result.extend_from_slice(instructions);
        }

        // Append state proof if present
        if let Some(ref state_proof) = self.fee_payer_state_proof {
            result.extend_from_slice(&state_proof.to_wire());
        }

        // Use raw account meta if available, otherwise use structured account meta
        if let Some(ref fee_payer_account_meta_raw) = self.fee_payer_account_meta_raw {
            result.extend_from_slice(fee_payer_account_meta_raw);
        }

        result
    }

    /// Serialize to on-wire format (WireTxnHdrV1).
    /// Wire format: header + accounts + instr_data + state_proof + account_meta + signature
    ///
    /// This is INFALLIBLE and does NOT validate account layout: it must remain
    /// usable for re-serializing transactions that were ingested from the
    /// network/block store (which may predate, or otherwise violate, the
    /// duplicate-account rules — e.g. a stored poison transaction served via
    /// getTransactionRaw). Validation is enforced at the construction boundary
    /// (`sign`) and is available explicitly via `try_to_wire`.
    pub fn to_wire(&self) -> Vec<u8> {
        self.serialize_wire()
    }

    /// Fallible serialization: validate account layout, then serialize.
    /// Use this for newly-built transactions that must satisfy the
    /// duplicate/sort/count rules before going on the wire.
    pub fn try_to_wire(&self) -> Result<Vec<u8>, RpcError> {
        self.validate()?;
        Ok(self.serialize_wire())
    }

    /// Internal: pure serialization with no validation.
    fn serialize_wire(&self) -> Vec<u8> {
        let mut wire = WireTxnHdrV1::default();
        wire.transaction_version = 1;
        wire.flags = self.flags;
        wire.readwrite_accounts_cnt = self.rw_accs.as_ref().map_or(0, |v| v.len() as u16);
        wire.readonly_accounts_cnt = self.r_accs.as_ref().map_or(0, |v| v.len() as u16);
        wire.instr_data_sz = self.instructions.as_ref().map_or(0, |v| v.len() as u16);
        wire.req_compute_units = self.req_compute_units;
        wire.req_state_units = self.req_state_units;
        wire.req_memory_units = self.req_memory_units;
        wire.expiry_after = self.expiry_after;
        wire.chain_id = self.chain_id;
        wire.fee = self.fee;
        wire.nonce = self.nonce;
        wire.start_slot = self.start_slot;
        wire.fee_payer_pubkey = self.fee_payer;
        wire.program_pubkey = self.program;

        let mut result = bytes_of(&wire).to_vec();

        // Append variable-length data
        if let Some(ref rw_accs) = self.rw_accs {
            for acc in rw_accs {
                result.extend_from_slice(acc);
            }
        }

        if let Some(ref r_accs) = self.r_accs {
            for acc in r_accs {
                result.extend_from_slice(acc);
            }
        }

        if let Some(ref instructions) = self.instructions {
            result.extend_from_slice(instructions);
        }

        // Append state proof if present (after instruction data)
        if let Some(ref state_proof) = self.fee_payer_state_proof {
            result.extend_from_slice(&state_proof.to_wire());
        }

        // Use raw account meta if available, otherwise use structured account meta
        if let Some(ref fee_payer_account_meta_raw) = self.fee_payer_account_meta_raw {
            result.extend_from_slice(fee_payer_account_meta_raw);
        }

        // Append signature at the END (last 64 bytes)
        if let Some(sig) = &self.signature {
            result.extend_from_slice(sig);
        } else {
            // Zero signature if not set
            result.extend_from_slice(&[0u8; TN_TXN_SIGNATURE_SZ]);
        }

        result
    }

    /// Deserialize from on-wire format (WireTxnHdrV1)
    /// Wire format: header + accounts + instr_data + state_proof + account_meta + signature (at end)
    pub fn from_wire(bytes: &[u8]) -> Option<Self> {
        // Minimum size: header + signature at end
        if bytes.len() < core::mem::size_of::<WireTxnHdrV1>() + TN_TXN_SIGNATURE_SZ {
            return None;
        }

        let wire: WireTxnHdrV1 = pod_read_unaligned(&bytes[0..core::mem::size_of::<WireTxnHdrV1>()]);
        let mut offset = core::mem::size_of::<WireTxnHdrV1>();

        let sig_start = bytes.len() - TN_TXN_SIGNATURE_SZ;
        let mut signature = [0u8; TN_TXN_SIGNATURE_SZ];
        signature.copy_from_slice(&bytes[sig_start..]);

        // Parse read-write accounts
        let rw_accs = if wire.readwrite_accounts_cnt > 0 {
            let mut accounts = Vec::new();
            for _ in 0..wire.readwrite_accounts_cnt {
                if offset + 32 > sig_start {
                    return None;
                }
                let mut acc = [0u8; 32];
                acc.copy_from_slice(&bytes[offset..offset + 32]);
                accounts.push(acc);
                offset += 32;
            }
            Some(accounts)
        } else {
            None
        };

        // Parse read-only accounts
        let r_accs = if wire.readonly_accounts_cnt > 0 {
            let mut accounts = Vec::new();
            for _ in 0..wire.readonly_accounts_cnt {
                if offset + 32 > sig_start {
                    return None;
                }
                let mut acc = [0u8; 32];
                acc.copy_from_slice(&bytes[offset..offset + 32]);
                accounts.push(acc);
                offset += 32;
            }
            Some(accounts)
        } else {
            None
        };

        // Parse instructions
        let instructions = if wire.instr_data_sz > 0 {
            if offset + wire.instr_data_sz as usize > sig_start {
                return None;
            }
            let instr = bytes[offset..offset + wire.instr_data_sz as usize].to_vec();
            offset += wire.instr_data_sz as usize;
            Some(instr)
        } else {
            None
        };

        let mut fee_payer_account_meta_raw: Option<Vec<u8>> = None;
        // Parse state proof if present
        let fee_payer_state_proof = if has_fee_payer_state_proof(wire.flags) {
            if offset >= sig_start {
                return None;
            }
            let state_proof_bytes = &bytes[offset..sig_start];
            if let Some(state_proof) = StateProof::from_wire(state_proof_bytes) {
                offset += state_proof.footprint();
                if state_proof.header.proof_type == StateProofType::Existing {
                    if offset + TN_ACCOUNT_META_FOOTPRINT > sig_start {
                        return None;
                    }
                    let account_meta_bytes = &bytes[offset..offset + TN_ACCOUNT_META_FOOTPRINT];
                    fee_payer_account_meta_raw = Some(account_meta_bytes.to_vec());
                    offset += TN_ACCOUNT_META_FOOTPRINT;
                }
                Some(state_proof)
            } else {
                return None;
            }
        } else {
            None
        };

        // Verify we've consumed all bytes before signature
        if offset != sig_start {
            log::warn!(
                "Transaction::from_wire: offset != sig_start ({} != {})",
                offset,
                sig_start
            );
            return None;
        }

        Some(Transaction {
            fee_payer: wire.fee_payer_pubkey,
            program: wire.program_pubkey,
            rw_accs,
            r_accs,
            instructions,
            flags: wire.flags,
            chain_id: wire.chain_id,
            fee: wire.fee,
            req_compute_units: wire.req_compute_units,
            req_state_units: wire.req_state_units,
            req_memory_units: wire.req_memory_units,
            expiry_after: wire.expiry_after,
            start_slot: wire.start_slot,
            nonce: wire.nonce,
            signature: Some(signature),
            fee_payer_state_proof,
            fee_payer_account_meta_raw,
        })
    }

    /// Accessor: read a field from serialized bytes by name
    pub fn get_field_from_wire(bytes: &[u8], field: &str) -> Option<Vec<u8>> {
        if bytes.len() < core::mem::size_of::<WireTxnHdrV1>() + TN_TXN_SIGNATURE_SZ {
            return None;
        }
        let wire: WireTxnHdrV1 = pod_read_unaligned(&bytes[0..core::mem::size_of::<WireTxnHdrV1>()]);
        match field {
            "fee_payer_signature" => {
                let sig_start = bytes.len() - TN_TXN_SIGNATURE_SZ;
                Some(bytes[sig_start..].to_vec())
            }
            "transaction_version" => Some(vec![wire.transaction_version]),
            "flags" => Some(vec![wire.flags]),
            "readwrite_accounts_cnt" => Some(wire.readwrite_accounts_cnt.to_le_bytes().to_vec()),
            "readonly_accounts_cnt" => Some(wire.readonly_accounts_cnt.to_le_bytes().to_vec()),
            "instr_data_sz" => Some(wire.instr_data_sz.to_le_bytes().to_vec()),
            "req_compute_units" => Some(wire.req_compute_units.to_le_bytes().to_vec()),
            "req_state_units" => Some(wire.req_state_units.to_le_bytes().to_vec()),
            "req_memory_units" => Some(wire.req_memory_units.to_le_bytes().to_vec()),
            "expiry_after" => Some(wire.expiry_after.to_le_bytes().to_vec()),
            "chain_id" => Some(wire.chain_id.to_le_bytes().to_vec()),
            "fee" => Some(wire.fee.to_le_bytes().to_vec()),
            "nonce" => Some(wire.nonce.to_le_bytes().to_vec()),
            "start_slot" => Some(wire.start_slot.to_le_bytes().to_vec()),
            "fee_payer_pubkey" => Some(wire.fee_payer_pubkey.to_vec()),
            "program_pubkey" => Some(wire.program_pubkey.to_vec()),
            _ => None,
        }
    }
}

/// Helper function to check if transaction has fee payer state proof
fn has_fee_payer_state_proof(flags: u8) -> bool {
    (flags & (1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT)) != 0
}

/// Helper function to extract state proof type from header
fn extract_state_proof_type(type_slot: u64) -> u64 {
    (type_slot >> 62) & 0x3 // Extract top 2 bits
}

/// Helper function to calculate state proof footprint from header
fn calculate_state_proof_footprint(state_proof_data: &[u8]) -> Result<usize, RpcError> {
    if state_proof_data.len() < TN_STATE_PROOF_HDR_SIZE {
        return Err(RpcError::invalid_format());
    }

    // Extract type_slot (first 8 bytes)
    let type_slot = u64::from_le_bytes([
        state_proof_data[0],
        state_proof_data[1],
        state_proof_data[2],
        state_proof_data[3],
        state_proof_data[4],
        state_proof_data[5],
        state_proof_data[6],
        state_proof_data[7],
    ]);

    // Extract path_bitset (next 32 bytes) and count set bits
    let mut sibling_hash_cnt = 0u32;
    for i in 0..4 {
        let start = 8 + i * 8;
        let word = u64::from_le_bytes([
            state_proof_data[start],
            state_proof_data[start + 1],
            state_proof_data[start + 2],
            state_proof_data[start + 3],
            state_proof_data[start + 4],
            state_proof_data[start + 5],
            state_proof_data[start + 6],
            state_proof_data[start + 7],
        ]);
        sibling_hash_cnt += word.count_ones();
    }

    let proof_type = extract_state_proof_type(type_slot);
    let body_sz = (proof_type + sibling_hash_cnt as u64) * 32; // Each hash is 32 bytes

    Ok(TN_STATE_PROOF_HDR_SIZE + body_sz as usize)
}

pub fn tn_txn_size(bytes: &[u8]) -> Result<usize, RpcError> {
    // Basic size checks
    if bytes.len() < core::mem::size_of::<WireTxnHdrV1>() + TN_TXN_SIGNATURE_SZ {
        return Err(RpcError::invalid_format());
    }

    // Parse the header
    // Use read_unaligned to safely read from potentially unaligned memory
    let hdr: WireTxnHdrV1 =
        unsafe { std::ptr::read_unaligned(bytes.as_ptr() as *const WireTxnHdrV1) };
    let hdr = &hdr;
    let mut offset = core::mem::size_of::<WireTxnHdrV1>();

    // Calculate accounts size
    let accs_sz = (hdr.readwrite_accounts_cnt as usize + hdr.readonly_accounts_cnt as usize) * 32;
    if offset + accs_sz > bytes.len() {
        return Err(RpcError::invalid_format());
    }
    offset += accs_sz;

    // Calculate instruction data size
    let instr_sz = hdr.instr_data_sz as usize;
    if offset + instr_sz > bytes.len() {
        return Err(RpcError::invalid_format());
    }
    offset += instr_sz;

    // Handle fee payer state proof if present
    if has_fee_payer_state_proof(hdr.flags) {
        // Check state proof header size
        if offset + TN_STATE_PROOF_HDR_SIZE > bytes.len() {
            return Err(RpcError::invalid_format());
        }

        // Calculate state proof footprint
        let state_proof_data = &bytes[offset..];
        let state_proof_sz = calculate_state_proof_footprint(state_proof_data)?;

        if offset + state_proof_sz > bytes.len() {
            return Err(RpcError::invalid_format());
        }
        offset += state_proof_sz;

        // Extract proof type for additional validation
        let type_slot = u64::from_le_bytes([
            state_proof_data[0],
            state_proof_data[1],
            state_proof_data[2],
            state_proof_data[3],
            state_proof_data[4],
            state_proof_data[5],
            state_proof_data[6],
            state_proof_data[7],
        ]);
        let proof_type = extract_state_proof_type(type_slot);

        // If proof type is EXISTING, account for account meta
        if proof_type == TN_STATE_PROOF_TYPE_EXISTING {
            if offset + TN_ACCOUNT_META_FOOTPRINT > bytes.len() {
                return Err(RpcError::invalid_format());
            }
            offset += TN_ACCOUNT_META_FOOTPRINT;
        }
    }

    // Add trailing signature size
    offset += TN_TXN_SIGNATURE_SZ;

    // Verify we don't exceed the provided bytes
    if offset > bytes.len() {
        return Err(RpcError::invalid_format());
    }

    Ok(offset)
}

/// Validate a transaction's account layout (count, duplicates, sort order).
///
/// Mirrors the C source of truth tn_validate_txn_accounts
/// (src/thru/runtime/tn_txn_account_validate.c): a combined merge-walk detects
/// sort-order violations, within-array duplicates, and cross-array (rw∩ro)
/// duplicates in a single pass, with the same error precedence (unsorted before
/// a fee_payer/program duplicate). The fee_payer/program-in-array check runs only
/// after sort order is confirmed.
pub fn validate_account_layout(
    rw_accs: &[TnPubkey],
    r_accs: &[TnPubkey],
    fee_payer: &TnPubkey,
    program: &TnPubkey,
) -> Result<(), RpcError> {
    let total_accounts = 2usize
        .checked_add(rw_accs.len())
        .and_then(|v| v.checked_add(r_accs.len()))
        .ok_or_else(|| RpcError::too_many_accounts(usize::MAX, TN_TXN_MAX_ACCOUNTS))?;
    if total_accounts > TN_TXN_MAX_ACCOUNTS {
        return Err(RpcError::too_many_accounts(total_accounts, TN_TXN_MAX_ACCOUNTS));
    }
    if fee_payer == program {
        return Err(RpcError::duplicate_account());
    }

    let (mut i, mut j) = (0usize, 0usize);
    let mut prev_rw: Option<&[u8; 32]> = None;
    let mut prev_ro: Option<&[u8; 32]> = None;
    while i < rw_accs.len() || j < r_accs.len() {
        let use_rw = j >= r_accs.len() || (i < rw_accs.len() && rw_accs[i] <= r_accs[j]);
        if use_rw {
            let key = &rw_accs[i];
            if j < r_accs.len() && *key == r_accs[j] {
                return Err(RpcError::duplicate_account());
            }
            if let Some(prev) = prev_rw {
                if prev == key {
                    return Err(RpcError::duplicate_account());
                }
                if prev > key {
                    return Err(RpcError::unsorted_readwrite_accounts());
                }
            }
            prev_rw = Some(key);
            i += 1;
        } else {
            let key = &r_accs[j];
            if let Some(prev) = prev_ro {
                if prev == key {
                    return Err(RpcError::duplicate_account());
                }
                if prev > key {
                    return Err(RpcError::unsorted_readonly_accounts());
                }
            }
            prev_ro = Some(key);
            j += 1;
        }
    }

    for account in rw_accs.iter().chain(r_accs.iter()) {
        if account == fee_payer || account == program {
            return Err(RpcError::duplicate_account());
        }
    }

    Ok(())
}

/// Validate a wire-format transaction for protocol correctness (matching C tn_txn_parse_core).
pub fn validate_wire_transaction(bytes: &[u8]) -> Result<(), RpcError> {
    const TN_TXN_MTU: usize = 32_768;
    // Version and flags are now at offset 0 and 1
    const TN_TXN_VERSION_OFFSET: usize = 0;
    const TN_TXN_FLAGS_OFFSET: usize = 1;

    use bytemuck::pod_read_unaligned;

    // 1. Check payload size
    if bytes.len() > TN_TXN_MTU {
        return Err(RpcError::invalid_transaction_size(bytes.len(), TN_TXN_MTU));
    }

    // 2. Check minimum size
    if bytes.len() < core::mem::size_of::<WireTxnHdrV1>() + TN_TXN_SIGNATURE_SZ {
        return Err(RpcError::invalid_format());
    }

    // 3. Check transaction version
    let transaction_version = bytes[TN_TXN_VERSION_OFFSET];
    if transaction_version != 0x01 {
        return Err(RpcError::invalid_version());
    }

    // 4. Check flags
    let flags = bytes[TN_TXN_FLAGS_OFFSET];
    // Clear the fee payer proof bit and check that all other bits are 0
    let flags_without_proof_bit = flags & !(1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT);
    let flags_cleared = flags_without_proof_bit & !(1 << TN_TXN_FLAG_MAY_COMPRESS_ACCOUNT_BIT);
    if flags_cleared != 0 {
        return Err(RpcError::invalid_flags());
    }

    // 5. Parse header
    let hdr: WireTxnHdrV1 = pod_read_unaligned(&bytes[0..core::mem::size_of::<WireTxnHdrV1>()]);
    let mut offset = core::mem::size_of::<WireTxnHdrV1>();

    let sig_start = bytes.len() - TN_TXN_SIGNATURE_SZ;

    // 6. Validate chain_id is non-zero (matches C tn_txn_parse.c:37)
    if hdr.chain_id == 0 {
        return Err(RpcError::invalid_chain_id());
    }

    // 6. Parse accounts
    let accs_sz = (hdr.readwrite_accounts_cnt as usize + hdr.readonly_accounts_cnt as usize) * 32;
    if offset + accs_sz > sig_start {
        return Err(RpcError::invalid_format());
    }
    offset += accs_sz;

    // 7. Parse instruction data
    let instr_sz = hdr.instr_data_sz as usize;
    if offset + instr_sz > sig_start {
        return Err(RpcError::invalid_format());
    }
    offset += instr_sz;

    // 8. Handle fee payer state proof if present
    if has_fee_payer_state_proof(flags) {
        // Check state proof header size
        if offset + TN_STATE_PROOF_HDR_SIZE > sig_start {
            return Err(RpcError::invalid_format());
        }

        let state_proof_data = &bytes[offset..sig_start];

        // Extract and validate the proof type before using the footprint. Only
        // EXISTING and CREATION are valid; UPDATING and out-of-range types (e.g.
        // type 3) are rejected — matching C tn_txn_parse.c, where an invalid type
        // yields a zero footprint and is rejected before further parsing.
        let type_slot = u64::from_le_bytes([
            state_proof_data[0],
            state_proof_data[1],
            state_proof_data[2],
            state_proof_data[3],
            state_proof_data[4],
            state_proof_data[5],
            state_proof_data[6],
            state_proof_data[7],
        ]);
        let proof_type = extract_state_proof_type(type_slot);
        if proof_type != TN_STATE_PROOF_TYPE_EXISTING && proof_type != TN_STATE_PROOF_TYPE_CREATION
        {
            return Err(RpcError::invalid_fee_payer_state_proof_type());
        }

        // Calculate state proof footprint
        let state_proof_sz = calculate_state_proof_footprint(state_proof_data)?;

        if offset + state_proof_sz > sig_start {
            return Err(RpcError::invalid_format());
        }

        offset += state_proof_sz;

        // If proof type is EXISTING, expect account meta
        if proof_type == TN_STATE_PROOF_TYPE_EXISTING {
            if offset + TN_ACCOUNT_META_FOOTPRINT > sig_start {
                return Err(RpcError::invalid_format());
            }
            offset += TN_ACCOUNT_META_FOOTPRINT;
        }
    }

    // 9. Check for exact size match (offset should be at signature start)
    if offset != sig_start {
        return Err(RpcError::trailing_bytes(
            offset + TN_TXN_SIGNATURE_SZ,
            bytes.len(),
        ));
    }

    // 9b. Account-layout validation (count, duplicates, sort order) runs after
    // the whole wire structure is confirmed and before signature verification,
    // matching the C/Go order. Keep in sync with
    // src/thru/runtime/tn_txn_account_validate.c.
    {
        let accs_start = core::mem::size_of::<WireTxnHdrV1>();
        let rw_cnt = hdr.readwrite_accounts_cnt as usize;
        let ro_cnt = hdr.readonly_accounts_cnt as usize;
        let mut rw_accs: Vec<TnPubkey> = Vec::with_capacity(rw_cnt);
        for k in 0..rw_cnt {
            let s = accs_start + k * 32;
            let mut a = [0u8; 32];
            a.copy_from_slice(&bytes[s..s + 32]);
            rw_accs.push(a);
        }
        let ro_start = accs_start + rw_cnt * 32;
        let mut ro_accs: Vec<TnPubkey> = Vec::with_capacity(ro_cnt);
        for k in 0..ro_cnt {
            let s = ro_start + k * 32;
            let mut a = [0u8; 32];
            a.copy_from_slice(&bytes[s..s + 32]);
            ro_accs.push(a);
        }
        validate_account_layout(
            &rw_accs,
            &ro_accs,
            &hdr.fee_payer_pubkey,
            &hdr.program_pubkey,
        )?;
    }

    // 10. Signature check
    let wire_for_signing = &bytes[..sig_start];
    let signature = &bytes[sig_start..];
    if verify_transaction(
        wire_for_signing,
        signature.try_into().expect("signature should be 64 bytes"),
        &hdr.fee_payer_pubkey,
    )
    .is_err()
    {
        return Err(RpcError::invalid_transaction_signature());
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use ed25519_dalek::SigningKey;

    fn make_valid_txn_bytes_with_flags(flags: u8) -> Vec<u8> {
        let signing_key = SigningKey::from(&[1u8; 32]);
        let verifying_key = signing_key.verifying_key();
        let mut tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42);
        tx.rw_accs = Some(vec![[3u8; 32], [4u8; 32]]);
        tx.r_accs = Some(vec![[5u8; 32]]);
        tx.instructions = Some(vec![1, 2, 3, 4]);
        tx.flags = flags;
        tx.sign(&signing_key.to_bytes()).unwrap();
        tx.to_wire()
    }

    fn make_valid_txn_bytes() -> Vec<u8> {
        make_valid_txn_bytes_with_flags(0)
    }

    #[test]
    fn test_tn_txn_size_basic_transaction() {
        let bytes = make_valid_txn_bytes();
        let calculated_size = tn_txn_size(&bytes).unwrap();

        // The calculated size should match the actual bytes length
        assert_eq!(calculated_size, bytes.len());
    }

    #[test]
    fn test_tn_txn_size_with_state_proof() {
        use crate::tn_state_proof::StateProof;

        let signing_key = SigningKey::from(&[1u8; 32]);
        let verifying_key = signing_key.verifying_key();

        // Create a CREATION state proof
        let path_bitset = [0u8; 32]; // No set bits = no sibling hashes
        let existing_leaf_pubkey = [7u8; 32];
        let existing_leaf_hash = [8u8; 32];
        let state_proof = StateProof::creation(
            100,
            path_bitset,
            existing_leaf_pubkey,
            existing_leaf_hash,
            vec![],
        );

        // Create transaction with state proof
        let mut tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42)
            .with_rw_accounts(vec![[3u8; 32]])
            .with_instructions(vec![1, 2, 3])
            .with_fee_payer_state_proof(&state_proof);

        tx.sign(&signing_key.to_bytes()).unwrap();
        let bytes = tx.to_wire();

        let calculated_size = tn_txn_size(&bytes).unwrap();

        // The calculated size should match the actual bytes length
        assert_eq!(calculated_size, bytes.len());
    }

    #[test]
    fn test_tn_txn_size_minimal_transaction() {
        let signing_key = SigningKey::from(&[1u8; 32]);
        let verifying_key = signing_key.verifying_key();

        // Create minimal transaction (no accounts, no instructions)
        let mut tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42);
        tx.sign(&signing_key.to_bytes()).unwrap();
        let bytes = tx.to_wire();

        let calculated_size = tn_txn_size(&bytes).unwrap();

        // The calculated size should match the actual bytes length
        assert_eq!(calculated_size, bytes.len());

        // Should be header size + trailing signature for minimal transaction
        let expected_min_size = core::mem::size_of::<WireTxnHdrV1>() + TN_TXN_SIGNATURE_SZ;
        assert_eq!(calculated_size, expected_min_size);
    }

    #[test]
    fn test_tn_txn_size_invalid_format() {
        // Test with bytes too short for header
        let short_bytes = vec![0u8; 50];
        let result = tn_txn_size(&short_bytes);
        assert!(matches!(result, Err(RpcError::InvalidFormat)));

        // Test with header but missing account data
        let mut bytes = make_valid_txn_bytes();
        bytes.truncate(core::mem::size_of::<WireTxnHdrV1>() + 10); // Truncate to cause missing data
        let result = tn_txn_size(&bytes);
        assert!(matches!(result, Err(RpcError::InvalidFormat)));
    }

    #[test]
    fn test_tn_txn_size_consistency_with_validation() {
        let bytes = make_valid_txn_bytes();

        // Both functions should succeed for valid transactions
        assert!(validate_wire_transaction(&bytes).is_ok());
        assert!(tn_txn_size(&bytes).is_ok());

        // Size should match actual length
        let calculated_size = tn_txn_size(&bytes).unwrap();
        assert_eq!(calculated_size, bytes.len());
    }

    #[test]
    fn test_valid_transaction() {
        let bytes = make_valid_txn_bytes();
        assert!(validate_wire_transaction(&bytes).is_ok());
    }

    #[test]
    fn test_transaction_duplicate_accounts_rejected() {
        let signing_key = SigningKey::from(&[1u8; 32]);
        let fee = signing_key.verifying_key().to_bytes();
        let program = [2u8; 32];
        let a = [3u8; 32];
        let b = [4u8; 32];

        let cases = [
            Transaction::new(fee, fee, 100, 42),
            Transaction::new(fee, program, 100, 42).with_rw_accounts(vec![fee]),
            Transaction::new(fee, program, 100, 42).with_r_accounts(vec![fee]),
            Transaction::new(fee, program, 100, 42).with_rw_accounts(vec![program]),
            Transaction::new(fee, program, 100, 42).with_r_accounts(vec![program]),
            Transaction::new(fee, program, 100, 42).with_rw_accounts(vec![a, a]),
            Transaction::new(fee, program, 100, 42).with_r_accounts(vec![a, a]),
            Transaction::new(fee, program, 100, 42)
                .with_rw_accounts(vec![a])
                .with_r_accounts(vec![a, b]),
        ];

        for mut tx in cases {
            assert!(matches!(tx.validate(), Err(RpcError::DuplicateAccount)));
            assert!(matches!(tx.try_to_wire(), Err(RpcError::DuplicateAccount)));
            assert!(tx.sign(&signing_key.to_bytes()).is_err());
        }
    }

    #[test]
    fn test_oversize_transaction() {
        let mut bytes = make_valid_txn_bytes();
        bytes.resize(32_769, 0);
        let err = validate_wire_transaction(&bytes).unwrap_err();
        assert!(matches!(
            err,
            RpcError::InvalidTransactionSize {
                size: 32_769,
                max_size: 32_768
            }
        ));
    }

    #[test]
    fn test_trailing_bytes() {
        let mut bytes = make_valid_txn_bytes();
        let orig_len = bytes.len();
        // Insert a byte before the signature (trailing bytes between body and signature)
        bytes.insert(orig_len - TN_TXN_SIGNATURE_SZ, 0);
        let err = validate_wire_transaction(&bytes).unwrap_err();
        // Expected size changes due to new wire format (112-byte header instead of 176)
        assert!(matches!(err, RpcError::TrailingBytes { .. }));
    }

    #[test]
    fn test_invalid_transaction_version() {
        let mut bytes = make_valid_txn_bytes();
        // Corrupt the transaction version
        bytes[0] = 0x00; // Invalid version
        let err = validate_wire_transaction(&bytes).unwrap_err();
        assert!(matches!(err, RpcError::InvalidVersion));
    }

    #[test]
    fn test_invalid_flags() {
        // Set invalid flag bits (keeping fee payer proof bit, but adding others)
        let bytes = make_valid_txn_bytes_with_flags(0x07);
        let err = validate_wire_transaction(&bytes).unwrap_err();
        assert!(matches!(err, RpcError::InvalidFlags));
    }

    #[test]
    fn test_invalid_chain_id_zero() {
        let mut bytes = make_valid_txn_bytes();

        /* Modify chain_id field to 0 (chain_id is at offset 108-109 in WireTxnHdrV1) */
        let hdr: &mut WireTxnHdrV1 =
            bytemuck::from_bytes_mut(&mut bytes[0..core::mem::size_of::<WireTxnHdrV1>()]);
        hdr.chain_id = 0;

        let err = validate_wire_transaction(&bytes).unwrap_err();
        assert!(matches!(err, RpcError::InvalidChainId));
    }

    #[test]
    fn test_transaction_too_short() {
        let bytes = vec![0u8; 50]; // Too short for header
        let err = validate_wire_transaction(&bytes).unwrap_err();
        assert!(matches!(err, RpcError::InvalidFormat));
    }

    #[test]
    fn test_transaction_with_state_proof() {
        use crate::tn_state_proof::{StateProof, StateProofType};

        let signing_key = SigningKey::from(&[1u8; 32]);
        let verifying_key = signing_key.verifying_key();

        // Create a CREATION state proof (doesn't require account meta)
        let path_bitset = [0u8; 32]; // No set bits = no sibling hashes
        let existing_leaf_pubkey = [7u8; 32];
        let existing_leaf_hash = [8u8; 32];
        let state_proof = StateProof::creation(
            100,
            path_bitset,
            existing_leaf_pubkey,
            existing_leaf_hash,
            vec![],
        );

        // Create transaction with state proof
        let mut tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42)
            .with_fee_payer_state_proof(&state_proof);

        // Verify flag is set
        assert!(tx.has_fee_payer_state_proof());
        assert_eq!(tx.flags & (1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT), 1);

        tx.sign(&signing_key.to_bytes()).unwrap();
        let bytes = tx.to_wire();

        // Verify state proof is included in wire format
        assert!(bytes.len() > core::mem::size_of::<WireTxnHdrV1>() + TN_TXN_SIGNATURE_SZ);
        assert!(validate_wire_transaction(&bytes).is_ok());

        // Test deserialization
        let decoded_tx = Transaction::from_wire(&bytes).unwrap();
        assert!(decoded_tx.has_fee_payer_state_proof());
        assert!(decoded_tx.fee_payer_state_proof.is_some());

        let decoded_proof = decoded_tx.fee_payer_state_proof.unwrap();
        assert_eq!(decoded_proof.proof_type(), StateProofType::Creation);
        assert_eq!(decoded_proof.slot(), 100);
    }

    #[test]
    fn test_transaction_with_state_proof_serialization_round_trip() {
        use crate::tn_state_proof::StateProof;

        let signing_key = SigningKey::from(&[1u8; 32]);
        let verifying_key = signing_key.verifying_key();

        // Create a creation state proof with some sibling hashes
        let mut path_bitset = [0u8; 32];
        path_bitset[0] = 0b11; // Set first 2 bits for 2 sibling hashes
        let existing_leaf_pubkey = [7u8; 32];
        let existing_leaf_hash = [8u8; 32];
        let sibling_hashes = vec![[9u8; 32], [10u8; 32]];

        let state_proof = StateProof::creation(
            200,
            path_bitset,
            existing_leaf_pubkey,
            existing_leaf_hash,
            sibling_hashes.clone(),
        );

        // Create transaction with complex state proof
        let mut tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42)
            .with_rw_accounts(vec![[3u8; 32], [4u8; 32]])
            .with_r_accounts(vec![[5u8; 32]])
            .with_instructions(vec![1, 2, 3, 4])
            .with_fee_payer_state_proof(&state_proof);

        tx.sign(&signing_key.to_bytes()).unwrap();
        let bytes = tx.to_wire();

        // Test validation
        assert!(validate_wire_transaction(&bytes).is_ok());

        // Test round-trip serialization
        let decoded_tx = Transaction::from_wire(&bytes).unwrap();
        assert_eq!(decoded_tx.fee_payer, tx.fee_payer);
        assert_eq!(decoded_tx.program, tx.program);
        assert_eq!(decoded_tx.rw_accs, tx.rw_accs);
        assert_eq!(decoded_tx.r_accs, tx.r_accs);
        assert_eq!(decoded_tx.instructions, tx.instructions);
        assert_eq!(decoded_tx.flags, tx.flags);
        assert!(decoded_tx.has_fee_payer_state_proof());

        let decoded_proof = decoded_tx.fee_payer_state_proof.unwrap();
        assert_eq!(decoded_proof.slot(), 200);
        assert_eq!(decoded_proof.path_bitset(), &path_bitset);
    }

    #[test]
    fn test_transaction_without_state_proof() {
        let signing_key = SigningKey::from(&[1u8; 32]);
        let verifying_key = signing_key.verifying_key();

        let mut tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42);

        // Verify flag is not set
        assert!(!tx.has_fee_payer_state_proof());
        assert_eq!(tx.flags & (1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT), 0);
        assert!(tx.fee_payer_state_proof.is_none());

        tx.sign(&signing_key.to_bytes()).unwrap();
        let bytes = tx.to_wire();

        assert!(validate_wire_transaction(&bytes).is_ok());

        // Test deserialization
        let decoded_tx = Transaction::from_wire(&bytes).unwrap();
        assert!(!decoded_tx.has_fee_payer_state_proof());
        assert!(decoded_tx.fee_payer_state_proof.is_none());
    }

    #[test]
    fn test_transaction_remove_state_proof() {
        use crate::tn_state_proof::StateProof;

        let signing_key = SigningKey::from(&[1u8; 32]);
        let verifying_key = signing_key.verifying_key();

        // Create a CREATION state proof
        let path_bitset = [0u8; 32];
        let existing_leaf_pubkey = [7u8; 32];
        let existing_leaf_hash = [8u8; 32];
        let state_proof = StateProof::creation(
            100,
            path_bitset,
            existing_leaf_pubkey,
            existing_leaf_hash,
            vec![],
        );

        // Create transaction with state proof, then remove it
        let tx = Transaction::new(verifying_key.to_bytes(), [2u8; 32], 100, 42)
            .with_fee_payer_state_proof(&state_proof)
            .without_fee_payer_state_proof();

        // Verify flag is cleared and state proof is removed
        assert!(!tx.has_fee_payer_state_proof());
        assert_eq!(tx.flags & (1 << TN_TXN_FLAG_HAS_FEE_PAYER_PROOF_BIT), 0);
        assert!(tx.fee_payer_state_proof.is_none());
    }
}