accumulate-sdk 2.1.0

Accumulate Rust SDK (V2/V3 unified) with DevNet-first flows
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
//! Transaction signing utilities for Accumulate protocol
//!
//! This module implements proper binary encoding for transaction signing
//! matching the Go core and Dart SDK implementations.

use super::writer::BinaryWriter;
use sha2::{Digest, Sha256};

/// Signature type enum values matching Go core
pub mod signature_types {
    pub const UNKNOWN: u64 = 0;
    pub const LEGACY_ED25519: u64 = 1;
    pub const ED25519: u64 = 2;
    pub const RCD1: u64 = 3;
    pub const BTC: u64 = 4;
    pub const BTC_LEGACY: u64 = 5;
    pub const ETH: u64 = 6;
    pub const DELEGATED: u64 = 7;
    pub const INTERNAL: u64 = 8;
    pub const RSA_SHA256: u64 = 9;
    pub const ECDSA_SHA256: u64 = 10;
    pub const TYPED_DATA: u64 = 11;
    pub const REMOTE: u64 = 12;
    pub const RECEIPT: u64 = 13;
    pub const PARTITION: u64 = 14;
    pub const SET: u64 = 15;
    pub const AUTHORITY: u64 = 16;
}

/// Transaction type enum values matching Go core
pub mod tx_types {
    pub const CREATE_IDENTITY: u64 = 0x01;
    pub const CREATE_TOKEN_ACCOUNT: u64 = 0x02;
    pub const SEND_TOKENS: u64 = 0x03;
    pub const CREATE_DATA_ACCOUNT: u64 = 0x04;
    pub const WRITE_DATA: u64 = 0x05;
    pub const WRITE_DATA_TO: u64 = 0x06;
    pub const ACME_FAUCET: u64 = 0x07;
    pub const CREATE_TOKEN: u64 = 0x08;
    pub const ISSUE_TOKENS: u64 = 0x09;
    pub const BURN_TOKENS: u64 = 0x0A;
    pub const CREATE_LITE_TOKEN_ACCOUNT: u64 = 0x0B;
    pub const CREATE_KEY_PAGE: u64 = 0x0C;
    pub const CREATE_KEY_BOOK: u64 = 0x0D;
    pub const ADD_CREDITS: u64 = 0x0E;
    pub const UPDATE_KEY_PAGE: u64 = 0x0F;
    pub const LOCK_ACCOUNT: u64 = 0x10;
    pub const BURN_CREDITS: u64 = 0x11;
    pub const TRANSFER_CREDITS: u64 = 0x12;
    pub const UPDATE_ACCOUNT_AUTH: u64 = 0x15;
    pub const UPDATE_KEY: u64 = 0x16;
}

/// KeyPageOperation type enum values matching Go core
/// From protocol/key_page_operations.yml
pub mod key_page_op_types {
    pub const UNKNOWN: u64 = 0;
    pub const UPDATE: u64 = 1;     // UpdateKeyOperation
    pub const REMOVE: u64 = 2;     // RemoveKeyOperation
    pub const ADD: u64 = 3;        // AddKeyOperation
    pub const SET_THRESHOLD: u64 = 4;  // SetThresholdKeyPageOperation
    pub const UPDATE_ALLOWED: u64 = 5; // UpdateAllowedKeyPageOperation
    pub const SET_REJECT_THRESHOLD: u64 = 6;   // SetRejectThresholdKeyPageOperation
    pub const SET_RESPONSE_THRESHOLD: u64 = 7; // SetResponseThresholdKeyPageOperation
}

/// Compute signature metadata hash for ED25519 signatures
///
/// This computes the SHA256 of the binary-encoded signature metadata,
/// which is used as both the transaction initiator AND part of the signing preimage.
///
/// Field order matches Go: protocol/types_gen.go ED25519Signature.MarshalBinary
/// - Field 1: Type (enum = 2 for ED25519)
/// - Field 2: PublicKey (bytes)
/// - Field 3: Signature (bytes) - OMITTED for metadata
/// - Field 4: Signer (URL as string)
/// - Field 5: SignerVersion (uint)
/// - Field 6: Timestamp (uint)
/// - Field 7: Vote (enum)
/// - Field 8: TransactionHash (hash) - OMITTED for metadata (zeros)
/// - Field 9: Memo (string)
/// - Field 10: Data (bytes)
pub fn compute_ed25519_signature_metadata_hash(
    public_key: &[u8],
    signer: &str,
    signer_version: u64,
    timestamp: u64,
) -> [u8; 32] {
    compute_signature_metadata_hash(
        signature_types::ED25519,
        public_key,
        signer,
        signer_version,
        timestamp,
        0, // vote
        None, // memo
        None, // data
    )
}

/// Compute signature metadata hash for any signature type
pub fn compute_signature_metadata_hash(
    signature_type: u64,
    public_key: &[u8],
    signer: &str,
    signer_version: u64,
    timestamp: u64,
    vote: u64,
    memo: Option<&str>,
    data: Option<&[u8]>,
) -> [u8; 32] {
    let mut writer = BinaryWriter::new();

    // Field 1: Type (enum)
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(signature_type);

    // Field 2: PublicKey (bytes with length prefix)
    if !public_key.is_empty() {
        let _ = writer.write_uvarint(2);
        let _ = writer.write_uvarint(public_key.len() as u64);
        let _ = writer.write_bytes(public_key);
    }

    // Field 3: Signature - OMITTED for metadata

    // Field 4: Signer URL (string with length prefix)
    if !signer.is_empty() {
        let _ = writer.write_uvarint(4);
        let signer_bytes = signer.as_bytes();
        let _ = writer.write_uvarint(signer_bytes.len() as u64);
        let _ = writer.write_bytes(signer_bytes);
    }

    // Field 5: SignerVersion (uint)
    if signer_version != 0 {
        let _ = writer.write_uvarint(5);
        let _ = writer.write_uvarint(signer_version);
    }

    // Field 6: Timestamp (uint)
    if timestamp != 0 {
        let _ = writer.write_uvarint(6);
        let _ = writer.write_uvarint(timestamp);
    }

    // Field 7: Vote (enum)
    if vote != 0 {
        let _ = writer.write_uvarint(7);
        let _ = writer.write_uvarint(vote);
    }

    // Field 8: TransactionHash - OMITTED for metadata (zeros)

    // Field 9: Memo (string)
    if let Some(memo_str) = memo {
        if !memo_str.is_empty() {
            let _ = writer.write_uvarint(9);
            let memo_bytes = memo_str.as_bytes();
            let _ = writer.write_uvarint(memo_bytes.len() as u64);
            let _ = writer.write_bytes(memo_bytes);
        }
    }

    // Field 10: Data (bytes)
    if let Some(data_bytes) = data {
        if !data_bytes.is_empty() {
            let _ = writer.write_uvarint(10);
            let _ = writer.write_uvarint(data_bytes.len() as u64);
            let _ = writer.write_bytes(data_bytes);
        }
    }

    // Hash the encoded metadata
    sha256_bytes(writer.bytes())
}

/// Options for extended transaction header fields (fields 5-7).
#[derive(Debug, Clone, Default)]
pub struct HeaderBinaryOptions {
    /// Expire: at_time as Unix seconds, signed (field 5)
    pub expire_at_time: Option<i64>,
    /// HoldUntil: minor_block number (field 6)
    pub hold_until_minor_block: Option<u64>,
    /// Additional authority URLs (field 7, repeatable)
    pub authorities: Option<Vec<String>>,
}

/// Marshal transaction header to binary format
///
/// Field order matches Go: protocol/types_gen.go TransactionHeader.MarshalBinary
/// - Field 1: Principal (URL as string)
/// - Field 2: Initiator (hash, 32 bytes, no length prefix)
/// - Field 3: Memo (string)
/// - Field 4: Metadata (bytes)
/// - Field 5: Expire (nested: ExpireOptions with field 1 = atTime uint)
/// - Field 6: HoldUntil (nested: HoldUntilOptions with field 1 = minorBlock uint)
/// - Field 7: Authorities (repeatable URL strings)
pub fn marshal_transaction_header(
    principal: &str,
    initiator: &[u8; 32],
    memo: Option<&str>,
    metadata: Option<&[u8]>,
) -> Vec<u8> {
    marshal_transaction_header_full(principal, initiator, memo, metadata, None)
}

/// Marshal transaction header with all fields including extended options (fields 5-7).
pub fn marshal_transaction_header_full(
    principal: &str,
    initiator: &[u8; 32],
    memo: Option<&str>,
    metadata: Option<&[u8]>,
    extended: Option<&HeaderBinaryOptions>,
) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: Principal URL
    let _ = writer.write_uvarint(1);
    let principal_bytes = principal.as_bytes();
    let _ = writer.write_uvarint(principal_bytes.len() as u64);
    let _ = writer.write_bytes(principal_bytes);

    // Field 2: Initiator (32 byte hash, no length prefix)
    // Only write if not all zeros
    let is_zero = initiator.iter().all(|&b| b == 0);
    if !is_zero {
        let _ = writer.write_uvarint(2);
        let _ = writer.write_bytes(initiator);
    }

    // Field 3: Memo
    if let Some(memo_str) = memo {
        if !memo_str.is_empty() {
            let _ = writer.write_uvarint(3);
            let memo_bytes = memo_str.as_bytes();
            let _ = writer.write_uvarint(memo_bytes.len() as u64);
            let _ = writer.write_bytes(memo_bytes);
        }
    }

    // Field 4: Metadata
    if let Some(metadata_bytes) = metadata {
        if !metadata_bytes.is_empty() {
            let _ = writer.write_uvarint(4);
            let _ = writer.write_uvarint(metadata_bytes.len() as u64);
            let _ = writer.write_bytes(metadata_bytes);
        }
    }

    // Fields 5-7: Extended header options
    if let Some(ext) = extended {
        // Field 5: Expire (nested ExpireOptions)
        // Go: writer.WriteValue(5, v.Expire.MarshalBinary)
        // ExpireOptions.MarshalBinary: writer.WriteTime(1, *v.AtTime)
        // WriteTime: writeField(n) then writeInt(n, v.UTC().Unix())
        // writeInt uses binary.PutVarint (signed/zigzag varint)
        if let Some(at_time) = ext.expire_at_time {
            let mut expire_writer = BinaryWriter::new();
            let _ = expire_writer.write_uvarint(1); // ExpireOptions field 1: AtTime
            let _ = expire_writer.write_varint(at_time); // signed varint (zigzag)
            let expire_bytes = expire_writer.into_bytes();

            let _ = writer.write_uvarint(5);
            let _ = writer.write_uvarint(expire_bytes.len() as u64);
            let _ = writer.write_bytes(&expire_bytes);
        }

        // Field 6: HoldUntil (nested HoldUntilOptions)
        if let Some(minor_block) = ext.hold_until_minor_block {
            let mut hold_writer = BinaryWriter::new();
            let _ = hold_writer.write_uvarint(1); // HoldUntilOptions field 1: MinorBlock
            let _ = hold_writer.write_uvarint(minor_block);
            let hold_bytes = hold_writer.into_bytes();

            let _ = writer.write_uvarint(6);
            let _ = writer.write_uvarint(hold_bytes.len() as u64);
            let _ = writer.write_bytes(&hold_bytes);
        }

        // Field 7: Authorities (repeatable URL)
        if let Some(ref authorities) = ext.authorities {
            for auth_url in authorities {
                let _ = writer.write_uvarint(7);
                let auth_bytes = auth_url.as_bytes();
                let _ = writer.write_uvarint(auth_bytes.len() as u64);
                let _ = writer.write_bytes(auth_bytes);
            }
        }
    }

    writer.into_bytes()
}

/// Marshal AddCredits transaction body to binary format
///
/// Field order matches Go: protocol/types_gen.go AddCredits.MarshalBinary
/// - Field 1: Type (enum)
/// - Field 2: Recipient (URL as string)
/// - Field 3: Amount (BigInt)
/// - Field 4: Oracle (uint)
pub fn marshal_add_credits_body(
    recipient: &str,
    amount: u64,
    oracle: u64,
) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: Type (AddCredits = 0x0E)
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(tx_types::ADD_CREDITS);

    // Field 2: Recipient URL
    let _ = writer.write_uvarint(2);
    let recipient_bytes = recipient.as_bytes();
    let _ = writer.write_uvarint(recipient_bytes.len() as u64);
    let _ = writer.write_bytes(recipient_bytes);

    // Field 3: Amount (BigInt - encode as length-prefixed big-endian bytes)
    if amount > 0 {
        let _ = writer.write_uvarint(3);
        let amount_bytes = amount_to_bigint_bytes(amount);
        let _ = writer.write_uvarint(amount_bytes.len() as u64);
        let _ = writer.write_bytes(&amount_bytes);
    }

    // Field 4: Oracle
    if oracle > 0 {
        let _ = writer.write_uvarint(4);
        let _ = writer.write_uvarint(oracle);
    }

    writer.into_bytes()
}

/// Marshal SendTokens transaction body to binary format
///
/// Field order matches Go: protocol/types_gen.go SendTokens.MarshalBinary
/// - Field 1: Type (enum)
/// - Field 2: Hash (optional) - skipped
/// - Field 3: Meta (optional) - skipped
/// - Field 4: To (repeated TokenRecipient)
pub fn marshal_send_tokens_body(
    recipients: &[(String, u64)], // (url, amount)
) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: Type (SendTokens = 0x03)
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(tx_types::SEND_TOKENS);

    // Field 4: To (repeated TokenRecipient)
    for (url, amount) in recipients {
        let recipient_bytes = marshal_token_recipient(url, *amount);
        let _ = writer.write_uvarint(4);
        let _ = writer.write_uvarint(recipient_bytes.len() as u64);
        let _ = writer.write_bytes(&recipient_bytes);
    }

    writer.into_bytes()
}

/// Marshal CreateIdentity transaction body to binary format
///
/// Field order matches Go: protocol/types_gen.go CreateIdentity.MarshalBinary
/// - Field 1: Type (enum)
/// - Field 2: Url (URL as string)
/// - Field 3: KeyHash (bytes)
/// - Field 4: KeyBookUrl (URL as string)
pub fn marshal_create_identity_body(
    url: &str,
    key_hash: &[u8],
    key_book_url: &str,
) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: Type (CreateIdentity = 0x01)
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(tx_types::CREATE_IDENTITY);

    // Field 2: Url
    let _ = writer.write_uvarint(2);
    let url_bytes = url.as_bytes();
    let _ = writer.write_uvarint(url_bytes.len() as u64);
    let _ = writer.write_bytes(url_bytes);

    // Field 3: KeyHash (bytes with length prefix)
    if !key_hash.is_empty() {
        let _ = writer.write_uvarint(3);
        let _ = writer.write_uvarint(key_hash.len() as u64);
        let _ = writer.write_bytes(key_hash);
    }

    // Field 4: KeyBookUrl
    let _ = writer.write_uvarint(4);
    let book_bytes = key_book_url.as_bytes();
    let _ = writer.write_uvarint(book_bytes.len() as u64);
    let _ = writer.write_bytes(book_bytes);

    writer.into_bytes()
}

/// Marshal CreateDataAccount transaction body to binary format
///
/// Field order matches Go: protocol/types_gen.go CreateDataAccount.MarshalBinary
/// - Field 1: Type (enum)
/// - Field 2: Url (URL as string)
/// - Field 3: Authorities (repeated URLs)
pub fn marshal_create_data_account_body(url: &str) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: Type (CreateDataAccount = 0x04)
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(tx_types::CREATE_DATA_ACCOUNT);

    // Field 2: Url
    if !url.is_empty() {
        let _ = writer.write_uvarint(2);
        let url_bytes = url.as_bytes();
        let _ = writer.write_uvarint(url_bytes.len() as u64);
        let _ = writer.write_bytes(url_bytes);
    }

    writer.into_bytes()
}

/// Marshal WriteData transaction body to binary format
///
/// Field order matches Go: protocol/types_gen.go WriteData.MarshalBinary
/// - Field 1: Type (enum)
/// - Field 2: Entry (nested DataEntry)
/// - Field 3: Scratch (bool, optional)
/// - Field 4: WriteToState (bool, optional)
pub fn marshal_write_data_body(entries_hex: &[String], scratch: bool, write_to_state: bool) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: Type (WriteData = 0x05)
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(tx_types::WRITE_DATA);

    // Field 2: Entry (nested DataEntry)
    if !entries_hex.is_empty() {
        let entry_bytes = marshal_data_entry(entries_hex);
        let _ = writer.write_uvarint(2);
        let _ = writer.write_uvarint(entry_bytes.len() as u64);
        let _ = writer.write_bytes(&entry_bytes);
    }

    // Field 3: Scratch (only if true)
    if scratch {
        let _ = writer.write_uvarint(3);
        let _ = writer.write_uvarint(1); // true = 1
    }

    // Field 4: WriteToState (only if true)
    if write_to_state {
        let _ = writer.write_uvarint(4);
        let _ = writer.write_uvarint(1); // true = 1
    }

    writer.into_bytes()
}

/// Marshal a DataEntry (DoubleHash type)
///
/// Field order:
/// - Field 1: Type (enum = 3 for DoubleHash)
/// - Field 2: Data (repeated bytes)
fn marshal_data_entry(entries_hex: &[String]) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: Type (DoubleHash = 3)
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(3); // DataEntryType.DoubleHash

    // Field 2: Data (repeated bytes)
    for entry_hex in entries_hex {
        if let Ok(data) = hex::decode(entry_hex) {
            let _ = writer.write_uvarint(2);
            let _ = writer.write_uvarint(data.len() as u64);
            let _ = writer.write_bytes(&data);
        }
    }

    writer.into_bytes()
}

/// Marshal CreateTokenAccount transaction body to binary format
///
/// Field order matches Go: protocol/types_gen.go CreateTokenAccount.MarshalBinary
/// - Field 1: Type (enum)
/// - Field 2: Url (URL as string)
/// - Field 3: TokenUrl (URL as string)
/// - Field 4: Authorities (repeated URLs)
pub fn marshal_create_token_account_body(
    url: &str,
    token_url: &str,
) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: Type (CreateTokenAccount = 0x02)
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(tx_types::CREATE_TOKEN_ACCOUNT);

    // Field 2: Url
    if !url.is_empty() {
        let _ = writer.write_uvarint(2);
        let url_bytes = url.as_bytes();
        let _ = writer.write_uvarint(url_bytes.len() as u64);
        let _ = writer.write_bytes(url_bytes);
    }

    // Field 3: TokenUrl
    if !token_url.is_empty() {
        let _ = writer.write_uvarint(3);
        let token_bytes = token_url.as_bytes();
        let _ = writer.write_uvarint(token_bytes.len() as u64);
        let _ = writer.write_bytes(token_bytes);
    }

    writer.into_bytes()
}

/// Marshal a TokenRecipient
fn marshal_token_recipient(url: &str, amount: u64) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: URL
    let _ = writer.write_uvarint(1);
    let url_bytes = url.as_bytes();
    let _ = writer.write_uvarint(url_bytes.len() as u64);
    let _ = writer.write_bytes(url_bytes);

    // Field 2: Amount
    if amount > 0 {
        let _ = writer.write_uvarint(2);
        let amount_bytes = amount_to_bigint_bytes(amount);
        let _ = writer.write_uvarint(amount_bytes.len() as u64);
        let _ = writer.write_bytes(&amount_bytes);
    }

    writer.into_bytes()
}

/// Convert u64 amount to big-endian bytes (minimal encoding)
fn amount_to_bigint_bytes(mut value: u64) -> Vec<u8> {
    if value == 0 {
        return vec![];
    }

    let mut bytes = Vec::new();
    while value > 0 {
        bytes.push((value & 0xFF) as u8);
        value >>= 8;
    }
    bytes.reverse(); // Convert to big-endian
    bytes
}

/// Marshal CreateToken transaction body to binary format
///
/// Field order matches Go: protocol/user_transactions.yml CreateToken
/// - Field 1: Type (enum 0x08)
/// - Field 2: Url (URL)
/// - Field 4: Symbol (string) - note: field 3 is skipped per Go spec
/// - Field 5: Precision (uint)
/// - Field 6: Properties (URL, optional)
/// - Field 7: SupplyLimit (BigInt, optional)
pub fn marshal_create_token_body(url: &str, symbol: &str, precision: u64, supply_limit: Option<u64>) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: Type (CreateToken = 0x08)
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(tx_types::CREATE_TOKEN);

    // Field 2: Url
    if !url.is_empty() {
        let _ = writer.write_uvarint(2);
        let url_bytes = url.as_bytes();
        let _ = writer.write_uvarint(url_bytes.len() as u64);
        let _ = writer.write_bytes(url_bytes);
    }

    // Field 4: Symbol (note: field 3 is not used)
    if !symbol.is_empty() {
        let _ = writer.write_uvarint(4);
        let symbol_bytes = symbol.as_bytes();
        let _ = writer.write_uvarint(symbol_bytes.len() as u64);
        let _ = writer.write_bytes(symbol_bytes);
    }

    // Field 5: Precision (always write, even if 0 - it's a valid value)
    let _ = writer.write_uvarint(5);
    let _ = writer.write_uvarint(precision);

    // Field 7: SupplyLimit (optional)
    if let Some(limit) = supply_limit {
        if limit > 0 {
            let _ = writer.write_uvarint(7);
            let limit_bytes = amount_to_bigint_bytes(limit);
            let _ = writer.write_uvarint(limit_bytes.len() as u64);
            let _ = writer.write_bytes(&limit_bytes);
        }
    }

    writer.into_bytes()
}

/// Marshal IssueTokens transaction body to binary format
///
/// Field order matches Go: protocol/user_transactions.yml IssueTokens
/// - Field 1: Type (enum 0x09)
/// - Field 4: To (repeated TokenRecipient)
pub fn marshal_issue_tokens_body(recipients: &[(&str, u64)]) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: Type (IssueTokens = 0x09)
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(tx_types::ISSUE_TOKENS);

    // Field 4: To (repeated TokenRecipient)
    for (url, amount) in recipients {
        let recipient_bytes = marshal_token_recipient(url, *amount);
        let _ = writer.write_uvarint(4);
        let _ = writer.write_uvarint(recipient_bytes.len() as u64);
        let _ = writer.write_bytes(&recipient_bytes);
    }

    writer.into_bytes()
}

/// Compute transaction hash using binary encoding
///
/// Based on Go: protocol/transaction_hash.go:27-71
/// Transaction hash = SHA256(SHA256(header_binary) + SHA256(body_binary))
pub fn compute_transaction_hash(header_bytes: &[u8], body_bytes: &[u8]) -> [u8; 32] {
    let header_hash = sha256_bytes(header_bytes);
    let body_hash = sha256_bytes(body_bytes);

    let mut combined = Vec::with_capacity(64);
    combined.extend_from_slice(&header_hash);
    combined.extend_from_slice(&body_hash);

    sha256_bytes(&combined)
}

/// Create signing preimage
///
/// Based on Go: protocol/signature_utils.go:50-57
/// signingHash = SHA256(sigMdHash + txnHash)
pub fn create_signing_preimage(
    signature_metadata_hash: &[u8; 32],
    transaction_hash: &[u8; 32],
) -> [u8; 32] {
    let mut combined = Vec::with_capacity(64);
    combined.extend_from_slice(signature_metadata_hash);
    combined.extend_from_slice(transaction_hash);

    sha256_bytes(&combined)
}

/// SHA256 hash helper
pub fn sha256_bytes(data: &[u8]) -> [u8; 32] {
    let mut hasher = Sha256::new();
    hasher.update(data);
    let result = hasher.finalize();
    let mut output = [0u8; 32];
    output.copy_from_slice(&result);
    output
}

// =============================================================================
// WRITEDATA SPECIAL HASH COMPUTATION
// =============================================================================

/// Compute WriteData body hash using special Merkle algorithm
///
/// Based on Go: protocol/transaction_hash.go:91-114
/// 1. Marshal WriteData body with Entry=nil (only Type, Scratch, WriteToState)
/// 2. Compute Merkle hash of [SHA256(marshaledBody), entryHash]
pub fn compute_write_data_body_hash(entries_hex: &[String], scratch: bool, write_to_state: bool) -> [u8; 32] {
    // Marshal body WITHOUT entry
    let body_without_entry = marshal_write_data_body_without_entry(scratch, write_to_state);
    let body_part_hash = sha256_bytes(&body_without_entry);

    // Compute entry hash
    let entry_hash = if entries_hex.is_empty() {
        [0u8; 32]
    } else {
        compute_data_entry_hash(entries_hex)
    };

    // Merkle hash of [bodyPartHash, entryHash]
    merkle_hash(&[body_part_hash, entry_hash])
}

/// Marshal WriteData body without entry (Entry = nil)
fn marshal_write_data_body_without_entry(scratch: bool, write_to_state: bool) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: Type (WriteData = 0x05)
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(tx_types::WRITE_DATA);

    // Field 2: Entry - OMITTED (nil)

    // Field 3: Scratch
    if scratch {
        let _ = writer.write_uvarint(3);
        let _ = writer.write_uvarint(1);
    }

    // Field 4: WriteToState
    if write_to_state {
        let _ = writer.write_uvarint(4);
        let _ = writer.write_uvarint(1);
    }

    writer.into_bytes()
}

/// Compute WriteDataTo body hash using special Merkle algorithm
///
/// Same algorithm as WriteData but with Type=WRITE_DATA_TO and Recipient included
/// Based on Go: protocol/transaction_hash.go WriteDataTo.GetHash()
pub fn compute_write_data_to_body_hash(recipient: &str, entries_hex: &[String]) -> [u8; 32] {
    // Marshal body WITHOUT entry (but WITH recipient)
    let body_without_entry = marshal_write_data_to_body_without_entry(recipient);
    let body_part_hash = sha256_bytes(&body_without_entry);

    // Compute entry hash
    let entry_hash = if entries_hex.is_empty() {
        [0u8; 32]
    } else {
        compute_data_entry_hash(entries_hex)
    };

    // Merkle hash of [bodyPartHash, entryHash]
    merkle_hash(&[body_part_hash, entry_hash])
}

/// Marshal WriteDataTo body without entry (Entry = nil)
/// Includes Type and Recipient, but NOT Entry
fn marshal_write_data_to_body_without_entry(recipient: &str) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: Type (WriteDataTo = 0x06)
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(tx_types::WRITE_DATA_TO);

    // Field 2: Recipient URL
    let url_bytes = recipient.as_bytes();
    let _ = writer.write_uvarint(2);
    let _ = writer.write_uvarint(url_bytes.len() as u64);
    let _ = writer.write_bytes(url_bytes);

    // Field 3: Entry - OMITTED (nil)

    writer.into_bytes()
}

/// Compute hash for a DataEntry
///
/// Based on Go: protocol/data_entry.go
/// DoubleHashDataEntry: SHA256(MerkleHash(SHA256(data1), SHA256(data2), ...))
fn compute_data_entry_hash(entries_hex: &[String]) -> [u8; 32] {
    if entries_hex.is_empty() {
        return [0u8; 32];
    }

    // Collect SHA256 hashes of each data item
    let mut data_hashes: Vec<[u8; 32]> = Vec::new();
    for entry_hex in entries_hex {
        if let Ok(data) = hex::decode(entry_hex) {
            data_hashes.push(sha256_bytes(&data));
        }
    }

    if data_hashes.is_empty() {
        return [0u8; 32];
    }

    // Compute Merkle hash of data hashes
    let merkle_root = merkle_hash(&data_hashes);

    // For DoubleHash: return SHA256(merkleRoot)
    sha256_bytes(&merkle_root)
}

/// Compute Merkle hash of a list of hashes
///
/// Based on Go: pkg/database/merkle/hasher.go MerkleHash()
/// Uses a cascading binary tree algorithm
fn merkle_hash(hashes: &[[u8; 32]]) -> [u8; 32] {
    if hashes.is_empty() {
        return [0u8; 32];
    }

    if hashes.len() == 1 {
        return hashes[0];
    }

    // Use the Merkle cascade algorithm from Go
    let mut pending: Vec<Option<[u8; 32]>> = Vec::new();

    for hash in hashes {
        let mut current = *hash;
        let mut i = 0;
        loop {
            // Extend pending if needed
            if i >= pending.len() {
                pending.push(Some(current));
                break;
            }

            // If slot is empty, put hash there
            if pending[i].is_none() {
                pending[i] = Some(current);
                break;
            }

            // Combine hashes and carry to next level
            current = combine_hashes(&pending[i].unwrap(), &current);
            pending[i] = None;
            i += 1;
        }
    }

    // Combine remaining pending hashes
    let mut anchor: Option<[u8; 32]> = None;
    for v in &pending {
        if anchor.is_none() {
            anchor = *v;
        } else if let Some(val) = v {
            anchor = Some(combine_hashes(val, &anchor.unwrap()));
        }
    }

    anchor.unwrap_or([0u8; 32])
}

/// Combine two hashes: SHA256(left + right)
fn combine_hashes(left: &[u8; 32], right: &[u8; 32]) -> [u8; 32] {
    let mut combined = Vec::with_capacity(64);
    combined.extend_from_slice(left);
    combined.extend_from_slice(right);
    sha256_bytes(&combined)
}

// =============================================================================
// UPDATE KEY PAGE ENCODING
// =============================================================================

/// Marshal KeySpecParams to binary format
///
/// Field order matches Go: protocol/key_page_operations.yml KeySpecParams
/// - Field 1: KeyHash (bytes)
/// - Field 2: Delegate (URL, optional)
pub fn marshal_key_spec_params(key_hash: &[u8], delegate: Option<&str>) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: KeyHash (bytes with length prefix)
    if !key_hash.is_empty() {
        let _ = writer.write_uvarint(1);
        let _ = writer.write_uvarint(key_hash.len() as u64);
        let _ = writer.write_bytes(key_hash);
    }

    // Field 2: Delegate URL (optional)
    if let Some(delegate_url) = delegate {
        if !delegate_url.is_empty() {
            let _ = writer.write_uvarint(2);
            let delegate_bytes = delegate_url.as_bytes();
            let _ = writer.write_uvarint(delegate_bytes.len() as u64);
            let _ = writer.write_bytes(delegate_bytes);
        }
    }

    writer.into_bytes()
}

/// Marshal a KeyPageOperation to binary format
///
/// Each operation type has different fields after the type enum:
/// - AddKeyOperation (type=3): Field 2: Entry (KeySpecParams)
/// - RemoveKeyOperation (type=2): Field 2: Entry (KeySpecParams)
/// - UpdateKeyOperation (type=1): Field 2: OldEntry, Field 3: NewEntry
/// - SetThresholdKeyPageOperation (type=4): Field 2: Threshold (uint)
/// - SetRejectThresholdKeyPageOperation (type=6): Field 2: Threshold (uint)
/// - SetResponseThresholdKeyPageOperation (type=7): Field 2: Threshold (uint)
/// - UpdateAllowedKeyPageOperation (type=5): Field 2: Allow[], Field 3: Deny[]
pub fn marshal_key_page_operation(
    op_type: &str,
    key_hash: Option<&[u8]>,
    delegate: Option<&str>,
    old_key_hash: Option<&[u8]>,
    new_key_hash: Option<&[u8]>,
    threshold: Option<u64>,
) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Map operation type string to enum value
    let op_type_num = match op_type {
        "add" => key_page_op_types::ADD,
        "remove" => key_page_op_types::REMOVE,
        "update" => key_page_op_types::UPDATE,
        "setThreshold" => key_page_op_types::SET_THRESHOLD,
        "setRejectThreshold" => key_page_op_types::SET_REJECT_THRESHOLD,
        "setResponseThreshold" => key_page_op_types::SET_RESPONSE_THRESHOLD,
        "updateAllowed" => key_page_op_types::UPDATE_ALLOWED,
        _ => key_page_op_types::UNKNOWN,
    };

    // Field 1: Type (enum)
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(op_type_num);

    match op_type {
        "add" | "remove" => {
            // Field 2: Entry (KeySpecParams)
            if let Some(hash) = key_hash {
                let entry_bytes = marshal_key_spec_params(hash, delegate);
                let _ = writer.write_uvarint(2);
                let _ = writer.write_uvarint(entry_bytes.len() as u64);
                let _ = writer.write_bytes(&entry_bytes);
            }
        }
        "update" => {
            // Field 2: OldEntry (KeySpecParams)
            if let Some(old_hash) = old_key_hash {
                let old_entry_bytes = marshal_key_spec_params(old_hash, None);
                let _ = writer.write_uvarint(2);
                let _ = writer.write_uvarint(old_entry_bytes.len() as u64);
                let _ = writer.write_bytes(&old_entry_bytes);
            }
            // Field 3: NewEntry (KeySpecParams)
            if let Some(new_hash) = new_key_hash {
                let new_entry_bytes = marshal_key_spec_params(new_hash, delegate);
                let _ = writer.write_uvarint(3);
                let _ = writer.write_uvarint(new_entry_bytes.len() as u64);
                let _ = writer.write_bytes(&new_entry_bytes);
            }
        }
        "setThreshold" | "setRejectThreshold" | "setResponseThreshold" => {
            // Field 2: Threshold (uint)
            if let Some(thresh) = threshold {
                let _ = writer.write_uvarint(2);
                let _ = writer.write_uvarint(thresh);
            }
        }
        "updateAllowed" => {
            // TODO: Implement Allow/Deny arrays when needed
            // Field 2: Allow (repeated TransactionType)
            // Field 3: Deny (repeated TransactionType)
        }
        _ => {}
    }

    writer.into_bytes()
}

/// Marshal UpdateKeyPage transaction body to binary format
///
/// Field order matches Go: protocol/user_transactions.yml UpdateKeyPage
/// - Field 1: Type (enum 0x0F)
/// - Field 2: Operation (repeated KeyPageOperation)
pub fn marshal_update_key_page_body(operations: &[Vec<u8>]) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: Type (UpdateKeyPage = 0x0F)
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(tx_types::UPDATE_KEY_PAGE);

    // Field 2: Operation (repeated, each as nested value)
    for op_bytes in operations {
        let _ = writer.write_uvarint(2);
        let _ = writer.write_uvarint(op_bytes.len() as u64);
        let _ = writer.write_bytes(op_bytes);
    }

    writer.into_bytes()
}

/// Marshal CreateKeyPage transaction body to binary format
///
/// Field order matches Go: protocol/user_transactions.yml CreateKeyPage
/// - Field 1: Type (enum, 0x0C)
/// - Field 2: Keys (repeated KeySpec, each as nested sub-message)
pub fn marshal_create_key_page_body(key_hashes: &[Vec<u8>]) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: Type (CreateKeyPage = 0x0C)
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(tx_types::CREATE_KEY_PAGE);

    // Field 2: Keys (repeated KeySpec, each as nested value)
    for key_hash in key_hashes {
        let key_spec_bytes = marshal_key_spec_params(key_hash, None);
        let _ = writer.write_uvarint(2);
        let _ = writer.write_uvarint(key_spec_bytes.len() as u64);
        let _ = writer.write_bytes(&key_spec_bytes);
    }

    writer.into_bytes()
}

/// Marshal BurnTokens transaction body to binary format
///
/// Field order matches Go: protocol/user_transactions.yml BurnTokens
/// - Field 1: Type (enum, 0x0A)
/// - Field 2: Amount (BigInt)
pub fn marshal_burn_tokens_body(amount: u64) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: Type (BurnTokens = 0x0A)
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(tx_types::BURN_TOKENS);

    // Field 2: Amount (BigInt, big-endian bytes)
    if amount > 0 {
        let _ = writer.write_uvarint(2);
        let amount_bytes = amount_to_bigint_bytes(amount);
        let _ = writer.write_uvarint(amount_bytes.len() as u64);
        let _ = writer.write_bytes(&amount_bytes);
    }

    writer.into_bytes()
}

/// Marshal CreateKeyBook transaction body to binary format
///
/// Field order matches Go: protocol/user_transactions.yml CreateKeyBook
/// - Field 1: Type (enum, 0x0D)
/// - Field 2: Url (URL as string)
/// - Field 3: PublicKeyHash (bytes)
pub fn marshal_create_key_book_body(url: &str, public_key_hash: &[u8]) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: Type (CreateKeyBook = 0x0D)
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(tx_types::CREATE_KEY_BOOK);

    // Field 2: Url
    let url_bytes = url.as_bytes();
    let _ = writer.write_uvarint(2);
    let _ = writer.write_uvarint(url_bytes.len() as u64);
    let _ = writer.write_bytes(url_bytes);

    // Field 3: PublicKeyHash (bytes)
    if !public_key_hash.is_empty() {
        let _ = writer.write_uvarint(3);
        let _ = writer.write_uvarint(public_key_hash.len() as u64);
        let _ = writer.write_bytes(public_key_hash);
    }

    writer.into_bytes()
}

/// Marshal UpdateKey transaction body to binary format
///
/// Field order matches Go: protocol/user_transactions.yml UpdateKey
/// - Field 1: Type (enum, 0x16)
/// - Field 2: NewKeyHash (bytes)
pub fn marshal_update_key_body(new_key_hash: &[u8]) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: Type (UpdateKey = 0x16)
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(tx_types::UPDATE_KEY);

    // Field 2: NewKeyHash (bytes)
    if !new_key_hash.is_empty() {
        let _ = writer.write_uvarint(2);
        let _ = writer.write_uvarint(new_key_hash.len() as u64);
        let _ = writer.write_bytes(new_key_hash);
    }

    writer.into_bytes()
}

/// Marshal BurnCredits transaction body to binary format
///
/// Field order matches Go: protocol/user_transactions.yml BurnCredits
/// - Field 1: Type (enum, 0x11)
/// - Field 2: Amount (uint64)
pub fn marshal_burn_credits_body(amount: u64) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: Type (BurnCredits = 0x11)
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(tx_types::BURN_CREDITS);

    // Field 2: Amount (uint64, NOT BigInt)
    if amount > 0 {
        let _ = writer.write_uvarint(2);
        let _ = writer.write_uvarint(amount);
    }

    writer.into_bytes()
}

/// Marshal TransferCredits transaction body to binary format
///
/// Field order matches Go: protocol/user_transactions.yml TransferCredits
/// - Field 1: Type (enum, 0x12)
/// - Field 2: To (repeated CreditRecipient)
pub fn marshal_transfer_credits_body(recipients: &[(&str, u64)]) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: Type (TransferCredits = 0x12)
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(tx_types::TRANSFER_CREDITS);

    // Field 2: To (repeated CreditRecipient)
    for (url, amount) in recipients {
        let recipient_bytes = marshal_credit_recipient(url, *amount);
        let _ = writer.write_uvarint(2);
        let _ = writer.write_uvarint(recipient_bytes.len() as u64);
        let _ = writer.write_bytes(&recipient_bytes);
    }

    writer.into_bytes()
}

/// Marshal a CreditRecipient to binary
/// Go CreditRecipient: Field 1=Url, Field 2=Amount (uint64)
fn marshal_credit_recipient(url: &str, amount: u64) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: URL
    let url_bytes = url.as_bytes();
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(url_bytes.len() as u64);
    let _ = writer.write_bytes(url_bytes);

    // Field 2: Amount (uint64, NOT BigInt)
    if amount > 0 {
        let _ = writer.write_uvarint(2);
        let _ = writer.write_uvarint(amount);
    }

    writer.into_bytes()
}

/// Marshal WriteDataTo transaction body to binary format
///
/// Field order matches Go: protocol/user_transactions.yml WriteDataTo
/// - Field 1: Type (enum, 0x06)
/// - Field 2: Recipient (URL)
/// - Field 3: Entry (nested DataEntry)
pub fn marshal_write_data_to_body(recipient: &str, entries_hex: &[String]) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: Type (WriteDataTo = 0x06)
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(tx_types::WRITE_DATA_TO);

    // Field 2: Recipient URL
    let url_bytes = recipient.as_bytes();
    let _ = writer.write_uvarint(2);
    let _ = writer.write_uvarint(url_bytes.len() as u64);
    let _ = writer.write_bytes(url_bytes);

    // Field 3: Entry (nested DataEntry)
    if !entries_hex.is_empty() {
        let entry_bytes = marshal_data_entry(entries_hex);
        let _ = writer.write_uvarint(3);
        let _ = writer.write_uvarint(entry_bytes.len() as u64);
        let _ = writer.write_bytes(&entry_bytes);
    }

    writer.into_bytes()
}

/// Marshal LockAccount transaction body to binary format
///
/// Field order matches Go: protocol/user_transactions.yml LockAccount
/// - Field 1: Type (enum, 0x10)
/// - Field 2: Height (uint64)
pub fn marshal_lock_account_body(height: u64) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: Type (LockAccount = 0x10)
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(tx_types::LOCK_ACCOUNT);

    // Field 2: Height (uint64)
    if height > 0 {
        let _ = writer.write_uvarint(2);
        let _ = writer.write_uvarint(height);
    }

    writer.into_bytes()
}

/// AccountAuthOperation type constants (matches Go AccountAuthOperationType)
pub mod account_auth_op_types {
    pub const ENABLE: u64 = 1;
    pub const DISABLE: u64 = 2;
    pub const ADD_AUTHORITY: u64 = 3;
    pub const REMOVE_AUTHORITY: u64 = 4;
}

/// Marshal UpdateAccountAuth transaction body to binary format
///
/// Field order matches Go: protocol/user_transactions.yml UpdateAccountAuth
/// - Field 1: Type (enum, 0x15)
/// - Field 2: Operations (repeated AccountAuthOperation)
pub fn marshal_update_account_auth_body(operations: &[(&str, &str)]) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: Type (UpdateAccountAuth = 0x15)
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(tx_types::UPDATE_ACCOUNT_AUTH);

    // Field 2: Operations (repeated)
    for (op_type, authority_url) in operations {
        let op_bytes = marshal_account_auth_operation(op_type, authority_url);
        let _ = writer.write_uvarint(2);
        let _ = writer.write_uvarint(op_bytes.len() as u64);
        let _ = writer.write_bytes(&op_bytes);
    }

    writer.into_bytes()
}

/// Marshal a single AccountAuthOperation to binary
/// Go: Field 1=Type (enum), Field 2=Authority (URL)
fn marshal_account_auth_operation(op_type: &str, authority_url: &str) -> Vec<u8> {
    let mut writer = BinaryWriter::new();

    // Field 1: Type (AccountAuthOperationType enum)
    let type_num = match op_type {
        "enable" => account_auth_op_types::ENABLE,
        "disable" => account_auth_op_types::DISABLE,
        "add" | "addAuthority" => account_auth_op_types::ADD_AUTHORITY,
        "remove" | "removeAuthority" => account_auth_op_types::REMOVE_AUTHORITY,
        _ => 0,
    };
    let _ = writer.write_uvarint(1);
    let _ = writer.write_uvarint(type_num);

    // Field 2: Authority URL
    if !authority_url.is_empty() {
        let url_bytes = authority_url.as_bytes();
        let _ = writer.write_uvarint(2);
        let _ = writer.write_uvarint(url_bytes.len() as u64);
        let _ = writer.write_bytes(url_bytes);
    }

    writer.into_bytes()
}

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

    #[test]
    fn test_signature_metadata_hash() {
        let public_key = [1u8; 32];
        let signer = "acc://test.acme/book/1";
        let signer_version = 1;
        let timestamp = 1234567890000u64;

        let hash = compute_ed25519_signature_metadata_hash(
            &public_key,
            signer,
            signer_version,
            timestamp,
        );

        // Should produce a 32-byte hash
        assert_eq!(hash.len(), 32);

        // Same inputs should produce same hash
        let hash2 = compute_ed25519_signature_metadata_hash(
            &public_key,
            signer,
            signer_version,
            timestamp,
        );
        assert_eq!(hash, hash2);
    }

    #[test]
    fn test_transaction_hash() {
        let header = b"test header";
        let body = b"test body";

        let hash = compute_transaction_hash(header, body);
        assert_eq!(hash.len(), 32);

        // Deterministic
        let hash2 = compute_transaction_hash(header, body);
        assert_eq!(hash, hash2);
    }

    #[test]
    fn test_signing_preimage() {
        let sig_hash = [1u8; 32];
        let tx_hash = [2u8; 32];

        let preimage = create_signing_preimage(&sig_hash, &tx_hash);
        assert_eq!(preimage.len(), 32);
    }

    #[test]
    fn test_amount_encoding() {
        // Test various amounts
        assert_eq!(amount_to_bigint_bytes(0), vec![] as Vec<u8>);
        assert_eq!(amount_to_bigint_bytes(1), vec![1]);
        assert_eq!(amount_to_bigint_bytes(255), vec![255]);
        assert_eq!(amount_to_bigint_bytes(256), vec![1, 0]);
        assert_eq!(amount_to_bigint_bytes(0x123456), vec![0x12, 0x34, 0x56]);
    }
}