moonproof-contracts 0.2.2

Node-side host orchestration for the moonproof contract pipeline — providers, deploy/call/maintenance lifecycle, fee balancing, submission, indexer-driven sync
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
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
//! Port of
//! `@midnight-ntwrk/midnight-js-contracts/src/utils/zswap-utils.ts`.
//!
//! Defines the [`EncryptionPublicKeyResolver`] closure signature, the
//! two well-known constants that are load-bearing for the
//! shielded-burn-address path
//! ([`SHIELDED_BURN_COIN_PUBLIC_KEY`] and
//! [`BURN_ENCRYPTION_PUBLIC_KEY`]), the
//! [`CompactZswapLocalState`] / [`CompactZswapOutput`] shape that
//! mirrors the TS `compact-runtime` `ZswapLocalState`, and the
//! [`zswap_state_to_offer`] / [`create_zswap_output`] translators
//! that turn that state into a ledger-typed `UnprovenOffer`.

use std::collections::HashMap;

use moonproof_ledger::base_crypto::hash::HashOutput;
use moonproof_ledger::coin_structure::coin::{
    Info as CoinInfo, QualifiedInfo as QualifiedCoinInfo,
};
use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_ledger::coin_structure::transfer::Recipient;
use moonproof_ledger::onchain_runtime::transcript::Transcript;
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::transient_crypto::proofs::ProofPreimage;
use moonproof_ledger::zswap::ledger::State as ZswapChainState;
use moonproof_ledger::zswap::{Input, Offer, Output, Transient};
use rand::{CryptoRng, Rng};

use crate::error::{ContractRuntimeError, Result};
use crate::types::{CoinPublicKey, EncPublicKey};

/// Re-export of the underlying wallet-side zswap state — kept so
/// existing call sites that need the wallet's view of received coins
/// (`coins`, `pending_outputs`, `merkle_tree`, etc.) can still reach
/// it. The compact-runtime side uses
/// [`CompactZswapLocalState`] instead.
pub use moonproof_ledger::zswap::local::State as ZswapWalletState;

/// The shielded-burn coin public key — all zeros, 32 bytes. Matches
/// TS `SHIELDED_BURN_COIN_PUBLIC_KEY = '0'.repeat(64)`. Coins sent
/// here are unspendable because the corresponding coin secret key is
/// the null key.
pub const SHIELDED_BURN_COIN_PUBLIC_KEY: CoinPublicKey = CoinPublicKey([0u8; 32]);

/// Burn address encryption public key. Derived via SHA-256
/// (`"midnight:burn-encryption-key:{i}"` with `i=9`, the first `i` that
/// maps to a valid Jubjub curve point). Matches TS
/// `BURN_ENCRYPTION_PUBLIC_KEY` exactly. The specific key doesn't
/// matter for spend-ability (the coin secret key is null), but the
/// value must be on-curve so output encryption succeeds.
///
/// Byte-level value: `f5b9fa49d3c4f06582dab6ba45c85f6b1927873105b4c8cf363b9b57ca910f65`.
pub const BURN_ENCRYPTION_PUBLIC_KEY: EncPublicKey = EncPublicKey(const_hex_decode(
    b"f5b9fa49d3c4f06582dab6ba45c85f6b1927873105b4c8cf363b9b57ca910f65",
));

/// Compile-time hex decoder for 64-char hex strings. Panics at const
/// time if the input isn't exactly 64 valid hex chars — so a typo
/// surfaces at build time, not as a silent data corruption.
const fn const_hex_decode(s: &[u8; 64]) -> [u8; 32] {
    let mut out = [0u8; 32];
    let mut i = 0;
    while i < 32 {
        let hi = hex_nibble(s[i * 2]);
        let lo = hex_nibble(s[i * 2 + 1]);
        out[i] = (hi << 4) | lo;
        i += 1;
    }
    out
}

/// One-hex-char to `u8`. Panics on non-hex input (compile-time
/// validation for the constant above).
const fn hex_nibble(c: u8) -> u8 {
    match c {
        b'0'..=b'9' => c - b'0',
        b'a'..=b'f' => c - b'a' + 10,
        b'A'..=b'F' => c - b'A' + 10,
        _ => panic!("invalid hex character"),
    }
}

/// Resolves a [`CoinPublicKey`] to the [`EncPublicKey`] used to seal
/// outputs addressed to that coin key.
///
/// Returning `None` means "I don't know this recipient" — the caller
/// (typically [`zswap_state_to_offer`]) treats that as a hard error
/// because a zswap output with no known encryption key can't be
/// constructed.
///
/// Port of TS `EncryptionPublicKeyResolver`.
pub type EncryptionPublicKeyResolver =
    Box<dyn Fn(CoinPublicKey) -> Option<EncPublicKey> + Send + Sync>;

/// Construct an [`EncryptionPublicKeyResolver`] that resolves:
///
/// 1. The wallet's own coin public key → the wallet's encryption key.
/// 2. The well-known [`SHIELDED_BURN_COIN_PUBLIC_KEY`] → the well-known
///    [`BURN_ENCRYPTION_PUBLIC_KEY`].
/// 3. Any additional caller-supplied mappings.
///
/// Port of TS `createEncryptionPublicKeyResolver`. The Rust port drops
/// the TS "normalise to hex via `parseCoinPublicKeyToHex`" step
/// because the Rust `CoinPublicKey` is a fixed-width `[u8; 32]`
/// newtype — equality is byte-level by construction, no parsing
/// required.
#[expect(
    clippy::implicit_hasher,
    reason = "the map moves into a boxed resolver and callers pass `None`; a hasher type parameter would leave `None` uninferable"
)]
pub fn create_encryption_public_key_resolver(
    wallet_coin_public_key: CoinPublicKey,
    wallet_encryption_public_key: EncPublicKey,
    additional: Option<HashMap<CoinPublicKey, EncPublicKey>>,
) -> EncryptionPublicKeyResolver {
    let additional = additional.unwrap_or_default();
    Box::new(move |coin_public_key: CoinPublicKey| {
        if coin_public_key == wallet_coin_public_key {
            Some(wallet_encryption_public_key)
        } else if coin_public_key == SHIELDED_BURN_COIN_PUBLIC_KEY {
            Some(BURN_ENCRYPTION_PUBLIC_KEY)
        } else {
            additional.get(&coin_public_key).copied()
        }
    })
}

// CompactZswapLocalState / CompactZswapOutput live in
// `moonproof_runtime::zswap_local` so the IR executor can build them
// without depending on the heavy host crate. Re-export here so existing
// `host::utils::zswap_utils::CompactZswap*` call sites keep working.
pub use moonproof_runtime::zswap_local::{CompactZswapLocalState, CompactZswapOutput};

/// Filter a [`CompactZswapLocalState`]'s outputs to the subset owned
/// by `receiver_coin_public_key`. Port of TS `zswapStateToNewCoins` —
/// the wallet calls this after executing a circuit so it can start
/// watching for the produced coins.
#[must_use]
pub fn zswap_state_to_new_coins(
    receiver_coin_public_key: &CoinPublicKey,
    zswap_state: &CompactZswapLocalState,
) -> Vec<CoinInfo> {
    zswap_state
        .outputs
        .iter()
        .filter_map(|out| match &out.recipient {
            Recipient::User(pk) => {
                if pk_matches(pk, receiver_coin_public_key) {
                    Some(out.coin_info)
                } else {
                    None
                }
            }
            Recipient::Contract(_) => None,
        })
        .collect()
}

fn pk_matches(
    ledger_pk: &moonproof_ledger::coin_structure::coin::PublicKey,
    moonproof_pk: &CoinPublicKey,
) -> bool {
    ledger_pk.0 .0 == moonproof_pk.0
}

// =====================================================================
// Output construction
// =====================================================================

/// Convert our 32-byte [`EncPublicKey`] newtype into the ledger's
/// [`moonproof_ledger::transient_crypto::encryption::PublicKey`] by
/// deserializing the raw bytes. Returns a deserialize error if the
/// bytes don't decode as a valid Jubjub group element (off-curve).
fn to_ledger_enc_public_key(
    epk: &EncPublicKey,
) -> Result<moonproof_ledger::transient_crypto::encryption::PublicKey> {
    use moonproof_ledger::serialize::Deserializable;
    let mut cursor = &epk.0[..];
    moonproof_ledger::transient_crypto::encryption::PublicKey::deserialize(&mut cursor, 0).map_err(
        |e| ContractRuntimeError::Deserialize {
            context: "EncPublicKey -> encryption::PublicKey",
            source: e,
        },
    )
}

/// Convert our [`CoinPublicKey`] newtype into the ledger's typed
/// `coin::PublicKey`.
fn to_ledger_coin_public_key(
    cpk: &CoinPublicKey,
) -> moonproof_ledger::coin_structure::coin::PublicKey {
    moonproof_ledger::coin_structure::coin::PublicKey(HashOutput(cpk.0))
}

/// Build a single ledger-typed [`Output`] for a circuit-emitted coin
/// move. Port of TS `createZswapOutput`.
///
/// - For contract-recipient outputs, calls
///   `Output::new_contract_owned`. No encryption key is needed —
///   contracts read coin info directly out of the transcript.
/// - For user-recipient outputs, looks up the recipient's
///   encryption public key via the resolver, then calls
///   `Output::new`. Errors with [`ContractRuntimeError::Provider`]
///   when the resolver can't produce a key.
///
/// The `segment` parameter defaults to `0` per TS's
/// `DEFAULT_SEGMENT_NUMBER` constant; the call site reaches the
/// non-zero path only via the optional `segment` arg on
/// [`zswap_state_to_offer`] (currently always `None`).
pub fn create_zswap_output<R: Rng + CryptoRng>(
    rng: &mut R,
    output: &CompactZswapOutput,
    resolver: &EncryptionPublicKeyResolver,
    segment: Option<u16>,
) -> Result<Output<ProofPreimage, InMemoryDB>> {
    match &output.recipient {
        Recipient::Contract(contract) => {
            Output::new_contract_owned(rng, &output.coin_info, segment, *contract).map_err(|e| {
                ContractRuntimeError::Provider {
                    provider: "create_zswap_output::contract",
                    message: format!("Output::new_contract_owned failed: {e:?}"),
                }
            })
        }
        Recipient::User(pk) => {
            let cpk = CoinPublicKey(pk.0 .0);
            let epk_bytes = resolver(cpk).ok_or_else(|| ContractRuntimeError::Provider {
                provider: "create_zswap_output::user",
                message: "Unable to resolve encryption public key for recipient. \
                          Provide a mapping via the encryption_public_key_resolver."
                    .to_owned(),
            })?;
            let epk = to_ledger_enc_public_key(&epk_bytes)?;
            Output::new(rng, &output.coin_info, segment, pk, Some(epk)).map_err(|e| {
                ContractRuntimeError::Provider {
                    provider: "create_zswap_output::user",
                    message: format!("Output::new failed: {e:?}"),
                }
            })
        }
    }
}

// =====================================================================
// zswap_state_to_offer — the main translator
// =====================================================================

/// Optional pair `(contract_address, zswap_chain_state)` threaded
/// into [`zswap_state_to_offer`] when the call needs to spend
/// contract-owned inputs. Mirrors the TS
/// `addressAndChainStateTuple` parameter.
#[derive(Debug, Clone, Copy)]
pub struct ContractInputContext<'a> {
    pub contract_address: ContractAddress,
    pub zswap_chain_state: &'a ZswapChainState<InMemoryDB>,
}

/// Default segment number used by [`zswap_state_to_offer`] for every
/// output / input / transient it constructs. Matches TS
/// `DEFAULT_SEGMENT_NUMBER = 0`.
pub const DEFAULT_SEGMENT_NUMBER: u16 = 0;

/// Translate a [`CompactZswapLocalState`] into a ledger-typed
/// [`Offer`]. Port of TS `zswapStateToOffer`.
///
/// Walks the state's outputs and inputs, classifying each as a pure
/// output (recipient ≠ caller and no matching input), pure input
/// (matching `coin_info` on-chain but no co-located output), or
/// transient (matching co-located input + output that cancels out).
/// Returns `Ok(None)` when the state has no outputs / inputs /
/// transients — the empty case (matches TS `undefined` return).
///
/// # Errors
///
/// - When an output addresses a user the resolver doesn't know
///   about: [`ContractRuntimeError::Provider`].
/// - When a contract-owned input is supplied but no
///   `ContractInputContext` was provided to anchor it against the
///   chain state: [`ContractRuntimeError::Provider`].
pub fn zswap_state_to_offer<R: Rng + CryptoRng>(
    rng: &mut R,
    state: &CompactZswapLocalState,
    resolver: &EncryptionPublicKeyResolver,
    contract_input_ctx: Option<ContractInputContext<'_>>,
) -> Result<Option<Offer<ProofPreimage, InMemoryDB>>> {
    use std::collections::HashMap as StdHashMap;

    // Build outputs first, keyed by serialized coin_info so we can
    // detect input/output collisions and promote them to transients.
    let mut output_map: StdHashMap<CoinInfoKey, Output<ProofPreimage, InMemoryDB>> =
        StdHashMap::new();
    for entry in &state.outputs {
        let key = CoinInfoKey::from(&entry.coin_info);
        let out = create_zswap_output(rng, entry, resolver, Some(DEFAULT_SEGMENT_NUMBER))?;
        output_map.insert(key, out);
    }

    // Build the ChainState's post-block-update view that
    // `Input::new_contract_owned` needs to anchor inputs. The TS
    // version calls `zswapChainState.postBlockUpdate(new Date())`;
    // the Rust analogue is `post_block_update(now)`.
    let rehashed_chain_state = contract_input_ctx.as_ref().map(|c| {
        moonproof_ledger::zswap_post_block_update(
            c.zswap_chain_state,
            moonproof_ledger::base_crypto::time::Timestamp::from_secs(
                moonproof_utils::rt::SystemTime::now()
                    .duration_since(moonproof_utils::rt::UNIX_EPOCH)
                    .map_or(0, |d| d.as_secs()),
            ),
        )
    });

    // Walk inputs. Each input either matches an output (→ transient,
    // remove from output_map) or stands alone (→ input).
    let mut input_vec: Vec<Input<ProofPreimage, InMemoryDB>> = Vec::new();
    let mut transient_vec: Vec<Transient<ProofPreimage, InMemoryDB>> = Vec::new();
    for qcoin in &state.inputs {
        let key = CoinInfoKey::from_qualified(qcoin);
        if let Some(matched_output) = output_map.remove(&key) {
            let transient = Transient::new_from_contract_owned_output(
                rng,
                qcoin,
                Some(DEFAULT_SEGMENT_NUMBER),
                matched_output,
            )
            .map_err(|e| ContractRuntimeError::Provider {
                provider: "zswap_state_to_offer::transient",
                message: format!("Transient::new_from_contract_owned_output failed: {e:?}"),
            })?;
            transient_vec.push(transient);
        } else {
            let ctx = contract_input_ctx
                .as_ref()
                .ok_or(ContractRuntimeError::Provider {
                    provider: "zswap_state_to_offer::input",
                    message: "input has no co-located output and no \
                              ContractInputContext was provided — non-transient \
                              inputs require an anchored chain state"
                        .to_owned(),
                })?;
            let chain_state = rehashed_chain_state
                .as_ref()
                .expect("rehashed chain state present whenever ctx is");
            let input = Input::new_contract_owned(
                rng,
                qcoin,
                Some(DEFAULT_SEGMENT_NUMBER),
                ctx.contract_address,
                &chain_state.coin_coms,
            )
            .map_err(|e| ContractRuntimeError::Provider {
                provider: "zswap_state_to_offer::input",
                message: format!("Input::new_contract_owned failed: {e:?}"),
            })?;
            input_vec.push(input);
        }
    }

    let outputs: Vec<Output<ProofPreimage, InMemoryDB>> = output_map.into_values().collect();
    Ok(Offer::new(input_vec, outputs, transient_vec))
}

/// The segment a guaranteed Zswap item is built for.
pub const GUARANTEED_SEGMENT_NUMBER: u16 = 0;

/// One call's shielded activity, the input to
/// [`zswap_calls_to_segmented_offer`].
#[derive(Clone, Copy)]
pub struct ZswapCallContribution<'a> {
    /// The contract whose circuit ran. `None` only for a state whose
    /// owner is unknown, which can pair inputs into transients but not
    /// spend a settled coin.
    pub contract_address: Option<ContractAddress>,
    pub zswap_local_state: &'a CompactZswapLocalState,
    /// The owner's own view of the commitment tree, needed only to spend
    /// a coin settled on chain.
    pub zswap_chain_state: Option<&'a ZswapChainState<InMemoryDB>>,
    pub partitioned_transcript: PartitionedTranscriptRef<'a>,
}

/// A transaction's shielded offers, one per segment kind.
pub struct SegmentedOffers {
    pub guaranteed: Option<Offer<ProofPreimage, InMemoryDB>>,
    /// Built for the segment passed to
    /// [`zswap_calls_to_segmented_offer`].
    pub fallible: Option<Offer<ProofPreimage, InMemoryDB>>,
}

/// A call's transcript, split into its guaranteed and fallible halves.
pub type PartitionedTranscriptRef<'a> = (
    Option<&'a Transcript<InMemoryDB>>,
    Option<&'a Transcript<InMemoryDB>>,
);

/// Which segment kind a coin movement belongs to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum SegmentKind {
    Guaranteed,
    Fallible,
}

impl SegmentKind {
    fn number(self, fallible_segment: u16) -> u16 {
        match self {
            SegmentKind::Guaranteed => GUARANTEED_SEGMENT_NUMBER,
            SegmentKind::Fallible => fallible_segment,
        }
    }
}

/// The segment of the first transcript half that claims an item.
/// Guaranteed takes precedence over fallible, across every transcript
/// the owner produced: its local state accumulates over its calls, so a
/// later call reports coins only an earlier call's transcript claims.
fn segment_for_match(
    claims: impl Fn(&Transcript<InMemoryDB>) -> bool,
    transcripts: &[PartitionedTranscriptRef<'_>],
    what: impl FnOnce() -> String,
) -> Result<SegmentKind> {
    if transcripts
        .iter()
        .any(|(guaranteed, _)| guaranteed.is_some_and(&claims))
    {
        return Ok(SegmentKind::Guaranteed);
    }
    if transcripts
        .iter()
        .any(|(_, fallible)| fallible.is_some_and(&claims))
    {
        return Ok(SegmentKind::Fallible);
    }
    if transcripts
        .iter()
        .any(|(guaranteed, fallible)| guaranteed.is_some() && fallible.is_some())
    {
        return Err(ContractRuntimeError::Provider {
            provider: "zswap_calls_to_segmented_offer",
            message: format!(
                "{} is not present in either segment of the partitioned transcript; the local \
                 zswap state does not match the contract's declared effects",
                what()
            ),
        });
    }
    Ok(SegmentKind::Guaranteed)
}

/// The ledger routes an output by the union of a transcript's claimed
/// receives and spends: a contract-owned output is a receive, a
/// user-bound one a spend.
fn segment_for_commitment(
    commitment: &moonproof_ledger::coin_structure::coin::Commitment,
    transcripts: &[PartitionedTranscriptRef<'_>],
) -> Result<SegmentKind> {
    segment_for_match(
        |t| {
            t.effects.claimed_shielded_receives.member(commitment)
                || t.effects.claimed_shielded_spends.member(commitment)
        },
        transcripts,
        || format!("shielded commitment {}", hex::encode(commitment.0 .0)),
    )
}

fn segment_for_nullifier(
    nullifier: &moonproof_ledger::coin_structure::coin::Nullifier,
    transcripts: &[PartitionedTranscriptRef<'_>],
) -> Result<SegmentKind> {
    segment_for_match(
        |t| t.effects.claimed_nullifiers.member(nullifier),
        transcripts,
        || format!("shielded nullifier {}", hex::encode(nullifier.0 .0)),
    )
}

/// One owner's shielded activity across the call tree: coins unioned by
/// identity, since each call's local state is a view of one growing
/// accumulator, and every transcript the owner produced.
struct OwnerActivity<'a> {
    owner: Option<ContractAddress>,
    chain_state: Option<&'a ZswapChainState<InMemoryDB>>,
    outputs: indexmap::IndexMap<
        moonproof_ledger::coin_structure::coin::Commitment,
        &'a CompactZswapOutput,
    >,
    inputs: indexmap::IndexMap<(CoinInfoKey, u64), QualifiedCoinInfo>,
    transcripts: Vec<PartitionedTranscriptRef<'a>>,
}

fn group_by_owner<'a>(contributions: &[ZswapCallContribution<'a>]) -> Vec<OwnerActivity<'a>> {
    let mut owners: indexmap::IndexMap<Option<ContractAddress>, OwnerActivity<'a>> =
        indexmap::IndexMap::new();
    for contribution in contributions {
        let activity = owners
            .entry(contribution.contract_address)
            .or_insert_with(|| OwnerActivity {
                owner: contribution.contract_address,
                chain_state: None,
                outputs: indexmap::IndexMap::new(),
                inputs: indexmap::IndexMap::new(),
                transcripts: Vec::new(),
            });
        // Only a spend of a settled coin needs the chain state, so the call
        // reporting that spend is not necessarily the one that carried it.
        if activity.chain_state.is_none() {
            activity.chain_state = contribution.zswap_chain_state;
        }
        activity
            .transcripts
            .push(contribution.partitioned_transcript);
        for output in &contribution.zswap_local_state.outputs {
            activity
                .outputs
                .insert(output.coin_info.commitment(&output.recipient), output);
        }
        for input in &contribution.zswap_local_state.inputs {
            activity
                .inputs
                .insert((CoinInfoKey::from_qualified(input), input.mt_index), *input);
        }
    }
    owners.into_values().collect()
}

#[derive(Default)]
struct SegmentBucket {
    inputs: indexmap::IndexMap<
        moonproof_ledger::coin_structure::coin::Nullifier,
        Input<ProofPreimage, InMemoryDB>,
    >,
    outputs: indexmap::IndexMap<
        moonproof_ledger::coin_structure::coin::Commitment,
        Output<ProofPreimage, InMemoryDB>,
    >,
    transients: indexmap::IndexMap<
        moonproof_ledger::coin_structure::coin::Commitment,
        Transient<ProofPreimage, InMemoryDB>,
    >,
}

impl SegmentBucket {
    fn into_offer(self) -> Option<Offer<ProofPreimage, InMemoryDB>> {
        Offer::new(
            self.inputs.into_values().collect(),
            self.outputs.into_values().collect(),
            self.transients.into_values().collect(),
        )
    }
}

/// Build a transaction's guaranteed and fallible shielded offers from
/// the shielded activity of every call in its call tree. Port of
/// midnight-js 5's `zswapCallsToSegmentedOffer`.
///
/// A coin sent to a contract is credited only if that contract claims
/// the receive in the same transaction, so a callee's coins reach the
/// offers as the root's do, and each contract-owned input is bound to
/// the contract that spent it. Routing follows the ledger's own
/// (`midnight-ledger/ledger/src/construct.rs`), applied per owner:
///
/// - an output goes where a transcript claims its commitment as a
///   receive or a spend;
/// - an input goes where a transcript claims its nullifier;
/// - an input that pairs with an output of the same coin and owner,
///   anywhere in the tree, becomes a transient in the output's segment.
///
/// The fallible offer is built for `fallible_segment`, the segment of
/// the intent carrying the calls.
///
/// # Errors
///
/// - A coin movement no transcript half claims while both halves exist.
/// - One commitment claimed in different segments by two owners.
/// - A settled coin spent without a known owner or owner chain state.
/// - An output to a user the resolver has no encryption key for.
pub fn zswap_calls_to_segmented_offer<R: Rng + CryptoRng>(
    rng: &mut R,
    contributions: &[ZswapCallContribution<'_>],
    resolver: &EncryptionPublicKeyResolver,
    fallible_segment: u16,
) -> Result<SegmentedOffers> {
    let activities = group_by_owner(contributions);
    let mut offers = OfferAssembly {
        fallible_segment,
        buckets: std::collections::HashMap::new(),
        segment_of_output: std::collections::HashMap::new(),
        commitments_by_coin: std::collections::HashMap::new(),
    };
    // Outputs first, so that a coin created and spent in the same
    // transaction is known by the time its input folds into a transient.
    for activity in &activities {
        offers.add_outputs(rng, activity, resolver)?;
    }
    for activity in &activities {
        offers.add_inputs(rng, activity)?;
    }
    let mut buckets = offers.buckets;
    Ok(SegmentedOffers {
        guaranteed: buckets
            .remove(&SegmentKind::Guaranteed)
            .and_then(SegmentBucket::into_offer),
        fallible: buckets
            .remove(&SegmentKind::Fallible)
            .and_then(SegmentBucket::into_offer),
    })
}

/// The offers [`zswap_calls_to_segmented_offer`] fills, one owner at a
/// time.
struct OfferAssembly {
    fallible_segment: u16,
    buckets: std::collections::HashMap<SegmentKind, SegmentBucket>,
    segment_of_output:
        std::collections::HashMap<moonproof_ledger::coin_structure::coin::Commitment, SegmentKind>,
    commitments_by_coin: std::collections::HashMap<
        CoinInfoKey,
        Vec<moonproof_ledger::coin_structure::coin::Commitment>,
    >,
}

impl OfferAssembly {
    /// Bucket an owner's outputs, keyed by commitment: one coin sent by
    /// one contract and received by another collapses to a single offer
    /// output, since the ledger rejects a repeated commitment.
    fn add_outputs<R: Rng + CryptoRng>(
        &mut self,
        rng: &mut R,
        activity: &OwnerActivity<'_>,
        resolver: &EncryptionPublicKeyResolver,
    ) -> Result<()> {
        for (commitment, output) in &activity.outputs {
            let segment = segment_for_commitment(commitment, &activity.transcripts)?;
            if let Some(already) = self.segment_of_output.get(commitment) {
                // A guaranteed call cannot contain a fallible one, so both
                // sides of a send/receive pair must agree.
                if *already != segment {
                    return Err(ContractRuntimeError::Provider {
                        provider: "zswap_calls_to_segmented_offer",
                        message: format!(
                            "shielded commitment {} is claimed in the {already:?} segment by one \
                             call and the {segment:?} segment by another; the calls' transcripts \
                             disagree",
                            hex::encode(commitment.0 .0)
                        ),
                    });
                }
                continue;
            }
            self.segment_of_output.insert(*commitment, segment);
            self.commitments_by_coin
                .entry(CoinInfoKey::from(&output.coin_info))
                .or_default()
                .push(*commitment);
            let built = create_zswap_output(
                rng,
                output,
                resolver,
                Some(segment.number(self.fallible_segment)),
            )?;
            self.buckets
                .entry(segment)
                .or_default()
                .outputs
                .insert(*commitment, built);
        }
        Ok(())
    }

    /// Bucket an owner's inputs: each pairs into a transient with an
    /// output of the same coin and owner anywhere in the tree, or is a
    /// settled coin spent against the owner's commitment tree.
    fn add_inputs<R: Rng + CryptoRng>(
        &mut self,
        rng: &mut R,
        activity: &OwnerActivity<'_>,
    ) -> Result<()> {
        let mut rehashed: Option<ZswapChainState<InMemoryDB>> = None;
        for qcoin in activity.inputs.values() {
            let coin = CoinInfo::from(qcoin);
            let own_commitment = match activity.owner {
                Some(address) => Some(coin.commitment(&Recipient::Contract(address))),
                None => sole_commitment_for(&coin, &self.commitments_by_coin)?,
            };
            if let Some((commitment, segment)) = own_commitment
                .and_then(|c| self.segment_of_output.get(&c).map(|segment| (c, *segment)))
            {
                self.add_transient(rng, &coin, commitment, segment)?;
                continue;
            }
            // A settled coin proves against the commitment tree as its
            // owner sees it, and its nullifier binds that owner.
            let Some(address) = activity.owner else {
                return Err(ContractRuntimeError::Provider {
                    provider: "zswap_calls_to_segmented_offer",
                    message: "a call that spends a settled shielded coin must name the contract \
                              that spent it, since the nullifier binds the spender"
                        .to_owned(),
                });
            };
            let chain_state =
                activity
                    .chain_state
                    .ok_or_else(|| ContractRuntimeError::Provider {
                        provider: "zswap_calls_to_segmented_offer",
                        message: format!(
                            "contract {} spends a shielded coin with no co-located output, and no \
                     anchoring chain state (ContractInputContext) was provided; non-transient \
                     inputs require an anchored chain state",
                            moonproof_runtime::state::contract_address_to_hex(&address)
                        ),
                    })?;
            let tree = rehashed.get_or_insert_with(|| {
                moonproof_ledger::zswap_post_block_update(
                    chain_state,
                    moonproof_ledger::base_crypto::time::Timestamp::from_secs(
                        moonproof_utils::rt::SystemTime::now()
                            .duration_since(moonproof_utils::rt::UNIX_EPOCH)
                            .map_or(0, |d| d.as_secs()),
                    ),
                )
            });
            let nullifier = coin.nullifier(
                &moonproof_ledger::coin_structure::transfer::SenderEvidence::Contract(address),
            );
            let segment = segment_for_nullifier(&nullifier, &activity.transcripts)?;
            let input = Input::new_contract_owned(
                rng,
                qcoin,
                Some(segment.number(self.fallible_segment)),
                address,
                &tree.coin_coms,
            )
            .map_err(|e| ContractRuntimeError::Provider {
                provider: "zswap_calls_to_segmented_offer",
                message: format!("Input::new_contract_owned failed: {e:?}"),
            })?;
            self.buckets
                .entry(segment)
                .or_default()
                .inputs
                .insert(nullifier, input);
        }
        Ok(())
    }

    /// Replace the output `commitment` names with a transient spending it.
    fn add_transient<R: Rng + CryptoRng>(
        &mut self,
        rng: &mut R,
        coin: &CoinInfo,
        commitment: moonproof_ledger::coin_structure::coin::Commitment,
        segment: SegmentKind,
    ) -> Result<()> {
        let bucket = self.buckets.entry(segment).or_default();
        let output = bucket.outputs.shift_remove(&commitment).ok_or_else(|| {
            ContractRuntimeError::Provider {
                provider: "zswap_calls_to_segmented_offer",
                message: format!(
                    "no bucketed output for transient commitment {}",
                    hex::encode(commitment.0 .0)
                ),
            }
        })?;
        // The transient's input proves against a tree holding only its own
        // output, at index 0
        // (`zswap/src/construct.rs::new_from_contract_owned_output`); the
        // reported `mt_index` is a position among the transaction's
        // commitments and names the wrong leaf there.
        let transient = Transient::new_from_contract_owned_output(
            rng,
            &coin.qualify(0),
            Some(segment.number(self.fallible_segment)),
            output,
        )
        .map_err(|e| ContractRuntimeError::Provider {
            provider: "zswap_calls_to_segmented_offer",
            message: format!("Transient::new_from_contract_owned_output failed: {e:?}"),
        })?;
        bucket.transients.insert(commitment, transient);
        Ok(())
    }
}

/// The output an input of unknown owner pairs with, found by coin
/// contents alone. Several candidates cannot be told apart.
fn sole_commitment_for(
    coin: &CoinInfo,
    commitments_by_coin: &std::collections::HashMap<
        CoinInfoKey,
        Vec<moonproof_ledger::coin_structure::coin::Commitment>,
    >,
) -> Result<Option<moonproof_ledger::coin_structure::coin::Commitment>> {
    match commitments_by_coin
        .get(&CoinInfoKey::from(coin))
        .map(Vec::as_slice)
    {
        None | Some([]) => Ok(None),
        Some([only]) => Ok(Some(*only)),
        Some(candidates) => Err(ContractRuntimeError::Provider {
            provider: "zswap_calls_to_segmented_offer",
            message: format!(
                "ambiguous transient: {} outputs carry the coin of an input whose spending \
                 contract is unknown, so the pair cannot be identified",
                candidates.len()
            ),
        }),
    }
}

/// Check that every coin the offers address to a contract is claimed as
/// received by that contract, per segment, exactly as many times as the
/// offers carry it. The ledger enforces the same equality after proving
/// but reports only an error code; checking here names both sides.
/// Port of midnight-js 5's `assertReceivesMatchClaims`.
///
/// `calls` pairs each call's contract with its partitioned transcript.
///
/// # Errors
///
/// When the offered and claimed counts differ for some coin.
pub fn assert_receives_match_claims(
    calls: &[(ContractAddress, PartitionedTranscriptRef<'_>)],
    offers: &SegmentedOffers,
) -> Result<()> {
    type Key = (
        u8,
        moonproof_ledger::coin_structure::coin::Commitment,
        ContractAddress,
    );
    let mut counts: indexmap::IndexMap<Key, (usize, usize)> = indexmap::IndexMap::new();
    for (segment, offer) in [(0u8, &offers.guaranteed), (1u8, &offers.fallible)] {
        let Some(offer) = offer else { continue };
        let outputs = offer
            .outputs
            .iter()
            .map(|o| (o.coin_com, o.contract_address.as_ref().map(|a| **a)));
        let transients = offer
            .transient
            .iter()
            .map(|t| (t.coin_com, t.contract_address.as_ref().map(|a| **a)));
        for (commitment, address) in outputs.chain(transients) {
            if let Some(address) = address {
                counts.entry((segment, commitment, address)).or_default().0 += 1;
            }
        }
    }
    for (address, (guaranteed, fallible)) in calls {
        for (segment, half) in [(0u8, guaranteed), (1u8, fallible)] {
            let Some(transcript) = half else { continue };
            for commitment in transcript.effects.claimed_shielded_receives.iter() {
                counts
                    .entry((segment, **commitment, *address))
                    .or_default()
                    .1 += 1;
            }
        }
    }
    let differences: Vec<String> = counts
        .iter()
        .filter(|(_, (offered, claimed))| offered != claimed)
        .map(|((segment, commitment, address), (offered, claimed))| {
            format!(
                "  segment {segment} / {} / {}: offered {offered}, claimed {claimed}",
                hex::encode(commitment.0 .0),
                moonproof_runtime::state::contract_address_to_hex(address)
            )
        })
        .collect();
    if differences.is_empty() {
        return Ok(());
    }
    Err(ContractRuntimeError::Provider {
        provider: "assert_receives_match_claims",
        message: format!(
            "a shielded coin addressed to a contract must be claimed as received by that \
             contract as many times as the offers carry it, and these do not match; the ledger \
             rejects such a transaction after proving. Offer count vs claim count:\n{}",
            differences.join("\n")
        ),
    })
}

/// Equality key for matching an [`Input`] against an [`Output`]
/// produced by the same circuit execution. Mirrors the TS
/// `serializeCoinInfo` / `serializeQualifiedShieldedCoinInfo` pattern
/// of "drop `mt_index`, hash the rest".
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
struct CoinInfoKey {
    nonce: HashOutput,
    type_bytes: [u8; 32],
    value: u128,
}

impl CoinInfoKey {
    fn from(info: &CoinInfo) -> Self {
        Self {
            nonce: info.nonce.0,
            type_bytes: info.type_.0 .0,
            value: info.value,
        }
    }
    fn from_qualified(info: &QualifiedCoinInfo) -> Self {
        Self {
            nonce: info.nonce.0,
            type_bytes: info.type_.0 .0,
            value: info.value,
        }
    }
}

// =====================================================================
// encryption_public_key_resolver_for_zswap_state
// =====================================================================

/// Construct an [`EncryptionPublicKeyResolver`] for a
/// [`CompactZswapLocalState`], validating that the state's coin
/// public key matches the wallet's (otherwise the wallet can't decrypt
/// produced outputs). Port of TS
/// `encryptionPublicKeyResolverForZswapState`.
#[expect(
    clippy::implicit_hasher,
    reason = "the map moves into a boxed resolver and callers pass `None`; a hasher type parameter would leave `None` uninferable"
)]
pub fn encryption_public_key_resolver_for_zswap_state(
    zswap_state: &CompactZswapLocalState,
    wallet_coin_public_key: CoinPublicKey,
    wallet_encryption_public_key: EncPublicKey,
    additional: Option<HashMap<CoinPublicKey, EncPublicKey>>,
) -> Result<EncryptionPublicKeyResolver> {
    if zswap_state.coin_public_key != wallet_coin_public_key {
        return Err(ContractRuntimeError::Provider {
            provider: "encryption_public_key_resolver_for_zswap_state",
            message: "Unable to lookup encryption public key (Unsupported coin) — \
                      zswap state's coin_public_key doesn't match the wallet's"
                .to_owned(),
        });
    }
    Ok(create_encryption_public_key_resolver(
        wallet_coin_public_key,
        wallet_encryption_public_key,
        additional,
    ))
}

#[allow(dead_code)]
fn _unused_to_ledger_coin_public_key_anchor() {
    // Silence dead_code warning when only some code paths use it.
    let _ = to_ledger_coin_public_key;
}

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

    #[test]
    fn burn_constants_match_ts_exactly() {
        // SHIELDED_BURN_COIN_PUBLIC_KEY is the all-zeros 32-byte key.
        assert_eq!(SHIELDED_BURN_COIN_PUBLIC_KEY.0, [0u8; 32]);
        assert_eq!(SHIELDED_BURN_COIN_PUBLIC_KEY.to_hex(), "0".repeat(64));
    }

    #[test]
    fn burn_encryption_key_matches_ts_byte_sequence() {
        // Reference bytes from the TS constant.
        let expected =
            hex::decode("f5b9fa49d3c4f06582dab6ba45c85f6b1927873105b4c8cf363b9b57ca910f65")
                .unwrap();
        assert_eq!(BURN_ENCRYPTION_PUBLIC_KEY.0.as_ref(), expected.as_slice());
    }

    #[test]
    fn resolver_returns_wallet_key_for_self_lookup() {
        let wallet_coin_key = CoinPublicKey([0x11; 32]);
        let wallet_enc_key = EncPublicKey([0x22; 32]);
        let resolver = create_encryption_public_key_resolver(wallet_coin_key, wallet_enc_key, None);
        assert_eq!(resolver(wallet_coin_key), Some(wallet_enc_key));
    }

    #[test]
    fn resolver_resolves_shielded_burn_address() {
        let wallet_coin_key = CoinPublicKey([0x11; 32]);
        let wallet_enc_key = EncPublicKey([0x22; 32]);
        let resolver = create_encryption_public_key_resolver(wallet_coin_key, wallet_enc_key, None);
        assert_eq!(
            resolver(SHIELDED_BURN_COIN_PUBLIC_KEY),
            Some(BURN_ENCRYPTION_PUBLIC_KEY),
        );
    }

    #[test]
    fn resolver_honours_additional_mappings() {
        let wallet_coin_key = CoinPublicKey([0x11; 32]);
        let wallet_enc_key = EncPublicKey([0x22; 32]);
        let other_coin_key = CoinPublicKey([0x33; 32]);
        let other_enc_key = EncPublicKey([0x44; 32]);
        let mut additional = HashMap::new();
        additional.insert(other_coin_key, other_enc_key);
        let resolver = create_encryption_public_key_resolver(
            wallet_coin_key,
            wallet_enc_key,
            Some(additional),
        );
        assert_eq!(resolver(other_coin_key), Some(other_enc_key));
    }

    #[test]
    fn resolver_returns_none_for_unknown_key() {
        let wallet_coin_key = CoinPublicKey([0x11; 32]);
        let wallet_enc_key = EncPublicKey([0x22; 32]);
        let resolver = create_encryption_public_key_resolver(wallet_coin_key, wallet_enc_key, None);
        assert_eq!(resolver(CoinPublicKey([0xff; 32])), None);
    }

    /// ports: `utils/zswap-utils.test.ts::createEncryptionPublicKeyResolver precedence::wallet key takes precedence over additional-mapping override for the wallet cpk`
    /// ports: `enc-pub-key-resolver.test.ts::createEncryptionPublicKeyResolver and encryptionPublicKeyResolverForZswapState normalize mappings`
    /// ports: `enc-pub-key-resolver.test.ts::deployContract forwards additionalCoinEncPublicKeyMappings to submitDeployTx`
    /// ports: `enc-pub-key-resolver.test.ts::createCircuitCallTxInterface includes additional mappings from TransactionContext in call options`
    /// (the Rust port pipes `additional_coin_enc_public_key_mappings`
    /// through `deploy_contract` → `unproven_deploy_tx` and `call_tx` →
    /// `unproven_call_tx` via the same struct field — the TS forwarding
    /// tests are reduced to the typed-field plumbing this test
    /// covers, plus the precedence assertion below.)
    ///
    /// Security-critical: the upstream TS comment cites issue #745.
    /// A DApp-supplied mapping must NOT be able to redirect the
    /// wallet's own outputs to an attacker-controlled key, even if
    /// the mapping explicitly tries to override the wallet cpk →
    /// wallet epk binding.
    #[test]
    fn wallet_key_precedence_blocks_additional_mapping_hijack() {
        let wallet_coin_key = CoinPublicKey([0x11; 32]);
        let wallet_enc_key = EncPublicKey([0x22; 32]);
        let malicious_epk = EncPublicKey([0xEE; 32]);
        let mut malicious_mapping = HashMap::new();
        // A DApp-supplied mapping that attempts to hijack the wallet
        // cpk → its own epk binding.
        malicious_mapping.insert(wallet_coin_key, malicious_epk);
        let resolver = create_encryption_public_key_resolver(
            wallet_coin_key,
            wallet_enc_key,
            Some(malicious_mapping),
        );
        // The resolver must still return the wallet's real epk —
        // not the malicious one.
        assert_eq!(resolver(wallet_coin_key), Some(wallet_enc_key));
        assert_ne!(resolver(wallet_coin_key), Some(malicious_epk));
    }

    /// ports: `utils/zswap-utils.test.ts::createEncryptionPublicKeyResolver precedence::burn encryption key takes precedence over additional-mapping override for the burn cpk`
    #[test]
    fn burn_key_precedence_blocks_additional_mapping_hijack() {
        let wallet_coin_key = CoinPublicKey([0x11; 32]);
        let wallet_enc_key = EncPublicKey([0x22; 32]);
        let malicious_epk = EncPublicKey([0xEE; 32]);
        let mut malicious_mapping = HashMap::new();
        // A DApp-supplied mapping that tries to redirect the burn
        // address to a key the attacker controls — would let stolen
        // funds be spent if it took effect.
        malicious_mapping.insert(SHIELDED_BURN_COIN_PUBLIC_KEY, malicious_epk);
        let resolver = create_encryption_public_key_resolver(
            wallet_coin_key,
            wallet_enc_key,
            Some(malicious_mapping),
        );
        assert_eq!(
            resolver(SHIELDED_BURN_COIN_PUBLIC_KEY),
            Some(BURN_ENCRYPTION_PUBLIC_KEY),
        );
    }

    // -----------------------------------------------------------------
    // Ports of the remaining `utils/zswap-utils.test.ts` cases that
    // operate on Rust-side types. The TS variant exercises
    // `serializeCoinInfo` / `deserializeCoinInfo` (a TS-specific JSON
    // serializer with bigint round-tripping) — those don't have a
    // Rust port because Rust callers operate on typed `CoinInfo`
    // values directly. The remaining test categories — empty-state,
    // matched input/output → transient, contract-input requires
    // chain-state, etc. — all port over.
    // -----------------------------------------------------------------

    use moonproof_ledger::coin_structure::coin::{Info as CoinInfo, Nonce};
    use moonproof_ledger::coin_structure::transfer::Recipient;
    use rand::rngs::StdRng;
    use rand::SeedableRng;

    fn dummy_coin_public_key(nonce: u8) -> CoinPublicKey {
        CoinPublicKey([nonce; 32])
    }

    fn dummy_contract_address(
        nonce: u8,
    ) -> moonproof_ledger::coin_structure::contract::ContractAddress {
        moonproof_ledger::coin_structure::contract::ContractAddress(
            moonproof_ledger::base_crypto::hash::HashOutput([nonce; 32]),
        )
    }

    fn dummy_coin_info(value: u128, nonce_byte: u8) -> CoinInfo {
        // Use the native shielded token type.
        CoinInfo {
            nonce: Nonce(moonproof_ledger::base_crypto::hash::HashOutput(
                [nonce_byte; 32],
            )),
            type_: moonproof_ledger::coin_structure::coin::ShieldedTokenType(
                moonproof_ledger::base_crypto::hash::HashOutput([0u8; 32]),
            ),
            value,
        }
    }

    /// ports: `utils/zswap-utils.test.ts::should return undefined offer for empty zswap state - changed in ledger 6`
    #[test]
    fn empty_zswap_state_returns_no_offer() {
        let state = CompactZswapLocalState::empty(dummy_coin_public_key(0xAA));
        let resolver = create_encryption_public_key_resolver(
            dummy_coin_public_key(0xAA),
            EncPublicKey([0x11; 32]),
            None,
        );
        let mut rng = StdRng::seed_from_u64(0);
        let offer = zswap_state_to_offer(&mut rng, &state, &resolver, None).unwrap();
        assert!(
            offer.is_none(),
            "empty zswap state must produce no offer (TS returns undefined)"
        );
    }

    /// ports: `utils/zswap-utils.test.ts::createEncryptionPublicKeyResolver::should return undefined for unknown coin public key`
    /// — exercised through the create-output path.
    ///
    /// `create_zswap_output` errors when the recipient is a user
    /// whose CPK the resolver can't map to an EPK.
    #[test]
    fn create_zswap_output_errors_for_unknown_user_recipient() {
        let wallet_coin_key = dummy_coin_public_key(0xAA);
        let wallet_enc_key = EncPublicKey([0x11; 32]);
        let unknown_pk = moonproof_ledger::coin_structure::coin::PublicKey(
            moonproof_ledger::base_crypto::hash::HashOutput([0xBB; 32]),
        );
        let resolver = create_encryption_public_key_resolver(wallet_coin_key, wallet_enc_key, None);

        let output = CompactZswapOutput {
            coin_info: dummy_coin_info(50, 1),
            recipient: Recipient::User(unknown_pk),
        };
        let mut rng = StdRng::seed_from_u64(1);
        let err = create_zswap_output(&mut rng, &output, &resolver, Some(0)).unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains("Unable to resolve encryption public key"),
            "{msg}"
        );
    }

    /// ports: `utils/zswap-utils.test.ts::should not require encryption key for contract-owned outputs`
    ///
    /// Contract-owned outputs skip the resolver — they store the
    /// `coin_info` verbatim in the public transcript so the receiving
    /// contract can read it without decryption.
    #[test]
    fn contract_owned_output_does_not_consult_resolver() {
        let wallet_coin_key = dummy_coin_public_key(0xAA);
        let wallet_enc_key = EncPublicKey([0x11; 32]);
        let resolver = create_encryption_public_key_resolver(wallet_coin_key, wallet_enc_key, None);
        let output = CompactZswapOutput {
            coin_info: dummy_coin_info(100, 2),
            recipient: Recipient::Contract(dummy_contract_address(0xCC)),
        };
        let mut rng = StdRng::seed_from_u64(2);
        // Should not error even though the resolver doesn't know this
        // contract address — contracts don't need an encryption key.
        let out = create_zswap_output(&mut rng, &output, &resolver, Some(0)).unwrap();
        // Contract address must round-trip into the output's
        // contract_address slot.
        let stored = out
            .contract_address
            .as_ref()
            .expect("contract-owned output must carry the contract address");
        assert_eq!(**stored, dummy_contract_address(0xCC));
    }

    /// `zswap_state_to_offer` errors loudly when a non-transient
    /// input has no anchoring chain state — input commitments need
    /// the zswap chain state's merkle tree to construct the input's
    /// merkle proof.
    #[test]
    fn zswap_state_to_offer_errors_when_input_has_no_chain_state() {
        let mut state = CompactZswapLocalState::empty(dummy_coin_public_key(0xAA));
        // An input with no co-located output and no contract context.
        state
            .inputs
            .push(moonproof_ledger::coin_structure::coin::QualifiedInfo {
                nonce: Nonce(moonproof_ledger::base_crypto::hash::HashOutput([0x33; 32])),
                type_: moonproof_ledger::coin_structure::coin::ShieldedTokenType(
                    moonproof_ledger::base_crypto::hash::HashOutput([0u8; 32]),
                ),
                value: 100,
                mt_index: 0,
            });
        let resolver = create_encryption_public_key_resolver(
            dummy_coin_public_key(0xAA),
            EncPublicKey([0x11; 32]),
            None,
        );
        let mut rng = StdRng::seed_from_u64(3);
        let err = zswap_state_to_offer(&mut rng, &state, &resolver, None).unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains("ContractInputContext"),
            "expected the diagnostic to mention ContractInputContext, got: {msg}"
        );
    }

    /// ports: `utils/zswap-utils.test.ts::should return only coins meant for provided wallet in zswapStateToNewCoins`
    #[test]
    fn zswap_state_to_new_coins_filters_to_recipient() {
        let wallet_pk = moonproof_ledger::coin_structure::coin::PublicKey(
            moonproof_ledger::base_crypto::hash::HashOutput([0xAA; 32]),
        );
        let wallet_coin_key = CoinPublicKey([0xAA; 32]);
        let other_pk = moonproof_ledger::coin_structure::coin::PublicKey(
            moonproof_ledger::base_crypto::hash::HashOutput([0xBB; 32]),
        );
        let mut state = CompactZswapLocalState::empty(wallet_coin_key);
        state.outputs.push(CompactZswapOutput {
            coin_info: dummy_coin_info(10, 1),
            recipient: Recipient::User(wallet_pk),
        });
        state.outputs.push(CompactZswapOutput {
            coin_info: dummy_coin_info(20, 2),
            recipient: Recipient::User(other_pk),
        });
        state.outputs.push(CompactZswapOutput {
            coin_info: dummy_coin_info(30, 3),
            recipient: Recipient::Contract(dummy_contract_address(0xCC)),
        });
        let new_coins = zswap_state_to_new_coins(&wallet_coin_key, &state);
        assert_eq!(new_coins.len(), 1);
        assert_eq!(new_coins[0].value, 10);
    }

    /// End-to-end: derive `ZswapSecretKeys` from the genesis seed
    /// (the same path the live integration test uses), encrypt a
    /// coin to the wallet's `enc_public_key()` after a 32-byte
    /// `EncPublicKey` round-trip (the same path
    /// `create_zswap_output` exercises), and decrypt with the
    /// wallet's `encryption_secret_key`. This is the strongest
    /// possible local proof that the indexer's wallet-relevance
    /// scan SHOULD pick up our mint outputs.
    ///
    /// If this test passes but the live wallet-indexer fails to
    /// surface our mint via `shieldedTransactions`, the bug is
    /// definitely on the harness side (wallet-indexer
    /// staleness/scan), not in our pipeline.
    #[test]
    fn zswap_secret_keys_pipeline_round_trips_encryption() {
        use moonproof_ledger::serialize::Serializable;
        use moonproof_ledger::zswap::keys::{SecretKeys as ZswapSecretKeys, Seed as ZswapSeed};
        use rand::rngs::StdRng;
        use rand::SeedableRng;

        // Same seed shape as the genesis wallet — 32 bytes,
        // `0x00..01` ending in 0x01.
        let mut seed_bytes = [0u8; 32];
        seed_bytes[31] = 0x01;
        let seed = ZswapSeed::from(seed_bytes);
        let zswap_keys = ZswapSecretKeys::from(seed);

        // The path our live test uses to build wallet_enc_key.
        let mut bytes = Vec::with_capacity(32);
        zswap_keys
            .enc_public_key()
            .serialize(&mut bytes)
            .expect("serialize wallet enc_public_key");
        assert_eq!(bytes.len(), 32);
        let arr: [u8; 32] = bytes.try_into().unwrap();
        let wallet_enc_key = EncPublicKey(arr);

        // Round-trip through to_ledger_enc_public_key — same as
        // `create_zswap_output`.
        let target_epk = to_ledger_enc_public_key(&wallet_enc_key).expect("round-trip wallet epk");
        // Sanity: round-tripped EPK equals the original.
        assert_eq!(zswap_keys.enc_public_key(), target_epk);

        // Encrypt a CoinInfo to the round-tripped EPK — what
        // `Output::new(... Some(target_epk))` does internally via
        // `CoinCiphertext::new(rng, coin, target_epk)`.
        let mut rng = StdRng::seed_from_u64(0x1234_5678);
        let coin = moonproof_ledger::coin_structure::coin::Info {
            nonce: moonproof_ledger::coin_structure::coin::Nonce(
                moonproof_ledger::base_crypto::hash::HashOutput([0xAB; 32]),
            ),
            type_: moonproof_ledger::coin_structure::coin::ShieldedTokenType(
                moonproof_ledger::base_crypto::hash::HashOutput([0; 32]),
            ),
            value: 1_000_000,
        };
        let ciphertext = moonproof_ledger::zswap::CoinCiphertext::new(&mut rng, &coin, target_epk);

        // Decrypt with the wallet's secret key — what the
        // indexer's `can_decrypt_v8` does to flag a transaction as
        // relevant for our viewing key.
        let ledger_ciph: moonproof_ledger::transient_crypto::encryption::Ciphertext =
            ciphertext.into();
        let decrypted: Option<moonproof_ledger::coin_structure::coin::Info> =
            zswap_keys.encryption_secret_key.decrypt(&ledger_ciph);
        let decrypted = decrypted.expect(
            "decryption with the wallet's encryption_secret_key must succeed against a \
             ciphertext encrypted to the round-tripped enc_public_key — if this fails, \
             the bug is in our pipeline; if this passes but the live test fails, the \
             bug is in the harness's wallet-indexer scan",
        );
        assert_eq!(
            decrypted, coin,
            "decrypted coin info must match the encrypted plaintext"
        );
    }

    /// Round-tripping an `encryption::PublicKey` through
    /// `EncPublicKey`'s 32-byte storage and back must preserve
    /// decryption correctness — i.e. a coin encrypted to the
    /// round-tripped public key must decrypt with the original
    /// secret key. Without this guarantee the indexer's viewing-key
    /// match would silently fail for every output the call-tx
    /// pipeline emits, masking a critical bug as "wallet didn't see
    /// the coin".
    #[test]
    fn enc_pubkey_byte_roundtrip_preserves_decryption() {
        use moonproof_ledger::serialize::Serializable;
        use rand::rngs::StdRng;
        use rand::SeedableRng;
        let mut rng = StdRng::seed_from_u64(0xABCD);
        let sk = moonproof_ledger::transient_crypto::encryption::SecretKey::new(&mut rng);
        let pk_orig = sk.public_key();

        // Serialize → 32 bytes → wrap in our newtype.
        let mut bytes = Vec::new();
        pk_orig
            .serialize(&mut bytes)
            .expect("serialize encryption public key");
        assert_eq!(
            bytes.len(),
            32,
            "encryption::PublicKey must serialize to exactly 32 bytes"
        );
        let arr: [u8; 32] = bytes.try_into().unwrap();
        let epk = EncPublicKey(arr);

        // Round-trip through to_ledger_enc_public_key.
        let pk_round = to_ledger_enc_public_key(&epk).expect("round-trip");
        assert_eq!(pk_orig, pk_round, "round-tripped public key must match");

        // Encrypt a coin to the round-tripped public key.
        let coin = moonproof_ledger::coin_structure::coin::Info {
            nonce: moonproof_ledger::coin_structure::coin::Nonce(
                moonproof_ledger::base_crypto::hash::HashOutput([0x11; 32]),
            ),
            type_: moonproof_ledger::coin_structure::coin::ShieldedTokenType(
                moonproof_ledger::base_crypto::hash::HashOutput([0; 32]),
            ),
            value: 12345,
        };
        let ciphertext = moonproof_ledger::zswap::CoinCiphertext::new(&mut rng, &coin, pk_round);

        // Decrypt with the ORIGINAL secret key — this is what the
        // indexer's wallet-relevance scan does.
        let ledger_ciph: moonproof_ledger::transient_crypto::encryption::Ciphertext =
            ciphertext.into();
        let decrypted: Option<moonproof_ledger::coin_structure::coin::Info> =
            sk.decrypt(&ledger_ciph);
        let decrypted = decrypted.expect(
            "decryption with the original secret key must succeed against a \
             ciphertext encrypted to the round-tripped public key — without \
             this guarantee, the indexer can't surface our coin via \
             shieldedTransactions",
        );
        assert_eq!(
            decrypted, coin,
            "decrypted coin must match the encrypted plaintext"
        );
    }

    /// `encryption_public_key_resolver_for_zswap_state` rejects a
    /// state whose `coin_public_key` doesn't match the wallet's —
    /// matches TS's `Unable to lookup encryption public key
    /// (Unsupported coin)` error.
    #[test]
    fn encryption_resolver_for_zswap_state_rejects_mismatched_cpk() {
        let state = CompactZswapLocalState::empty(dummy_coin_public_key(0xAA));
        // The resolver type doesn't impl Debug (it's a Box<dyn Fn>),
        // so we can't `.unwrap_err()` directly. Match on the error
        // variant instead.
        let result = encryption_public_key_resolver_for_zswap_state(
            &state,
            dummy_coin_public_key(0xBB), // mismatched
            EncPublicKey([0x11; 32]),
            None,
        );
        match result {
            Ok(_) => panic!("mismatched coin public keys must error"),
            Err(err) => {
                let msg = format!("{err}");
                assert!(msg.contains("Unsupported coin"), "{msg}");
            }
        }
    }

    /// ports: `utils/zswap-utils.test.ts::should create correct number of outputs when no inputs`
    ///
    /// One output, no inputs, no chain-state context → offer carries
    /// exactly one output and zero inputs / transients.
    #[test]
    fn zswap_state_to_offer_creates_outputs_only_when_no_inputs() {
        let wallet_coin_key = dummy_coin_public_key(0xAA);
        let wallet_pk = moonproof_ledger::coin_structure::coin::PublicKey(
            moonproof_ledger::base_crypto::hash::HashOutput([0xAA; 32]),
        );
        let mut state = CompactZswapLocalState::empty(wallet_coin_key);
        state.outputs.push(CompactZswapOutput {
            coin_info: dummy_coin_info(100, 1),
            recipient: Recipient::User(wallet_pk),
        });
        let resolver = create_encryption_public_key_resolver(
            wallet_coin_key,
            BURN_ENCRYPTION_PUBLIC_KEY,
            None,
        );
        let mut rng = StdRng::seed_from_u64(0x10);
        let offer = zswap_state_to_offer(&mut rng, &state, &resolver, None)
            .unwrap()
            .expect("non-empty state must produce an offer");
        assert_eq!(offer.outputs.len(), 1, "exactly one output");
        assert_eq!(offer.inputs.len(), 0, "no inputs without anchored context");
        assert_eq!(offer.transient.len(), 0, "no transients without inputs");
    }

    /// ports: `utils/zswap-utils.test.ts::should handle zero value outputs correctly`
    ///
    /// A zero-value output is still a valid output — the offer
    /// carries it without erroring, and the contract-recipient
    /// branch doesn't consult the resolver (so a zero-value
    /// contract-owned output round-trips even with no resolver
    /// mapping for that contract address).
    #[test]
    fn zswap_state_to_offer_handles_zero_value_contract_output() {
        let wallet_coin_key = dummy_coin_public_key(0xAA);
        let mut state = CompactZswapLocalState::empty(wallet_coin_key);
        state.outputs.push(CompactZswapOutput {
            coin_info: dummy_coin_info(0, 7),
            recipient: Recipient::Contract(dummy_contract_address(0xCC)),
        });
        let resolver = create_encryption_public_key_resolver(
            wallet_coin_key,
            BURN_ENCRYPTION_PUBLIC_KEY,
            None,
        );
        let mut rng = StdRng::seed_from_u64(0x11);
        let offer = zswap_state_to_offer(&mut rng, &state, &resolver, None)
            .unwrap()
            .expect("zero-value output is still a valid output");
        assert_eq!(offer.outputs.len(), 1);
        assert_eq!(offer.inputs.len(), 0);
        assert_eq!(offer.transient.len(), 0);
    }

    /// ports: `utils/zswap-utils.test.ts::should create transient for single matching input-output pair`
    ///
    /// When `inputs` and `outputs` share a coin (same nonce / type /
    /// value), the offer collapses both into a single Transient
    /// instead of a (input, output) pair. This avoids consulting the
    /// chain state for the input — transients carry their own proof
    /// via the co-located output.
    #[test]
    fn zswap_state_to_offer_creates_transient_for_matching_pair() {
        let wallet_coin_key = dummy_coin_public_key(0xAA);
        let coin = dummy_coin_info(100, 5);
        let mut state = CompactZswapLocalState::empty(wallet_coin_key);
        // Same coin appears as both an input (qualified with
        // mt_index) and an output to a contract recipient.
        state
            .inputs
            .push(moonproof_ledger::coin_structure::coin::QualifiedInfo {
                nonce: coin.nonce,
                type_: coin.type_,
                value: coin.value,
                mt_index: 0,
            });
        state.outputs.push(CompactZswapOutput {
            coin_info: coin,
            recipient: Recipient::Contract(dummy_contract_address(0xCC)),
        });
        let resolver = create_encryption_public_key_resolver(
            wallet_coin_key,
            BURN_ENCRYPTION_PUBLIC_KEY,
            None,
        );
        let mut rng = StdRng::seed_from_u64(0x12);
        // No ContractInputContext required — the matching output
        // lets `zswap_state_to_offer` route through the transient
        // path before consulting the chain state.
        let offer = zswap_state_to_offer(&mut rng, &state, &resolver, None)
            .unwrap()
            .expect("matched input/output pair produces an offer");
        assert_eq!(
            offer.transient.len(),
            1,
            "co-located input + output collapses to one transient"
        );
        assert_eq!(
            offer.inputs.len(),
            0,
            "no leftover input — the input matched the output"
        );
        assert_eq!(
            offer.outputs.len(),
            0,
            "no leftover output — the output matched the input"
        );
    }

    /// ports: `utils/zswap-utils.test.ts::should create transient with zero delta for zero value matching pair`
    ///
    /// Zero-value matching input/output pairs still produce a
    /// transient — the value is zero on both sides, so the delta is
    /// zero, but the transient still records the coin's nonce/type
    /// so the kernel can audit the spend.
    #[test]
    fn zswap_state_to_offer_creates_transient_for_zero_value_matching_pair() {
        let wallet_coin_key = dummy_coin_public_key(0xAA);
        let coin = dummy_coin_info(0, 9);
        let mut state = CompactZswapLocalState::empty(wallet_coin_key);
        state
            .inputs
            .push(moonproof_ledger::coin_structure::coin::QualifiedInfo {
                nonce: coin.nonce,
                type_: coin.type_,
                value: coin.value,
                mt_index: 0,
            });
        state.outputs.push(CompactZswapOutput {
            coin_info: coin,
            recipient: Recipient::Contract(dummy_contract_address(0xCC)),
        });
        let resolver = create_encryption_public_key_resolver(
            wallet_coin_key,
            BURN_ENCRYPTION_PUBLIC_KEY,
            None,
        );
        let mut rng = StdRng::seed_from_u64(0x13);
        let offer = zswap_state_to_offer(&mut rng, &state, &resolver, None)
            .unwrap()
            .expect("zero-value matched pair still produces an offer");
        assert_eq!(offer.transient.len(), 1);
        assert_eq!(offer.inputs.len(), 0);
        assert_eq!(offer.outputs.len(), 0);
    }
}