moonproof-wallet 0.2.1

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
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
//! Pure-logic recipe builder for shielded (zswap) transfers.
//!
//! Port of the transfer-building slice of
//! `@midnight-ntwrk/wallet-sdk-shielded-wallet/v1/Transacting.ts::makeTransfer`.
//! The ledger adapter (sibling module) consumes the produced
//! [`ShieldedTransferRecipe`] to build a real
//! [`moonproof_ledger::zswap::Offer<ProofPreimage, D>`] + [`Transaction`].
//!
//! # Fee model
//!
//! Shielded offers pay no per-input / per-output overhead in the
//! *shielded* token — the TS reference uses an all-zero
//! `ShieldedCostModel`. Fees are paid in DUST **outside** the shielded
//! offer, via a separate balancing intent built in [`crate::dust`].
//! This mirrors the chain's economics: a zswap offer's binding
//! commitment commits to a zero overall delta (inputs == outputs by
//! value), and the *transaction-level* DUST fee covers the cost of the
//! zk-proofs + unshielded-offer bookkeeping.
//!
//! That's why the balancer runs with [`TransactionCostModel::ZERO`] and
//! the `fee_token` we feed it is a placeholder — with zero overheads,
//! the fee-token phase of [`balance`] is always a no-op.
//!
//! # Output semantics
//!
//! Each recipient output is a fresh [`moonproof_ledger::coin_structure::coin::Info`]
//! with a random nonce, addressed to the recipient's coin / encryption
//! public keys (via a [`ShieldedAddress`]). Change outputs are addressed
//! to the sender's own keys. The recipe keeps them in two separate
//! lists (mirrors `unshielded::transacting::TransferRecipe`) so the
//! ledger adapter can combine them in a well-defined order.

use moonproof_ledger::coin_structure::coin::{Info as CoinInfo, QualifiedInfo, ShieldedTokenType};
use moonproof_ledger::zswap::keys::SecretKeys as ZswapSecretKeys;
use rand::{CryptoRng, Rng};

use crate::address::{ShieldedAddress, ShieldedCoinPublicKey, ShieldedEncryptionPublicKey};
use crate::balancer::{balance, BalanceRequest, Imbalances, SmallestFirstSelector};
use crate::error::{Result, WalletError};
use crate::shielded::state::ShieldedState;
use crate::types::{Amount, CoinRecipe, TokenType, TransactionCostModel};

/// Zero-overhead cost model for the shielded offer — matches TS
/// `ShieldedCostModel`. Shielded transactions pay their fees out-of-band
/// (in DUST), not via per-input / per-output charges in the shielded
/// token.
pub const SHIELDED_COST_MODEL: TransactionCostModel = TransactionCostModel::ZERO;

/// One "send `amount` of `token_type` to `recipient`" instruction.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShieldedTransfer {
    pub amount: u128,
    pub token_type: ShieldedTokenType,
    pub recipient: ShieldedAddress,
}

impl ShieldedTransfer {
    #[inline]
    #[must_use]
    pub fn new(amount: u128, token_type: ShieldedTokenType, recipient: ShieldedAddress) -> Self {
        Self {
            amount,
            token_type,
            recipient,
        }
    }
}

/// One shielded output — a full [`CoinInfo`] (value / type / fresh
/// nonce) addressed to some recipient.
///
/// Carries a cached `token_type_str` for the balancer's `CoinRecipe`
/// trait bound. The cache is a single hex-encoded 32-byte hash so its
/// size is negligible per-output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShieldedOutputSpec {
    pub coin: CoinInfo,
    pub recipient_coin_pk: ShieldedCoinPublicKey,
    pub recipient_enc_pk: ShieldedEncryptionPublicKey,
    token_type_str: TokenType,
}

impl ShieldedOutputSpec {
    #[inline]
    #[must_use]
    pub fn new(
        coin: CoinInfo,
        recipient_coin_pk: ShieldedCoinPublicKey,
        recipient_enc_pk: ShieldedEncryptionPublicKey,
    ) -> Self {
        let token_type_str = token_type_to_wallet_string(&coin.type_);
        Self {
            coin,
            recipient_coin_pk,
            recipient_enc_pk,
            token_type_str,
        }
    }

    /// True if this output is addressed to the wallet's own keys — i.e.
    /// it's a change output we're sending back to ourselves.
    #[must_use]
    pub fn is_self(&self, our_coin_pk: &ShieldedCoinPublicKey) -> bool {
        &self.recipient_coin_pk == our_coin_pk
    }
}

impl CoinRecipe for ShieldedOutputSpec {
    #[inline]
    fn token_type(&self) -> &TokenType {
        &self.token_type_str
    }

    #[inline]
    fn value(&self) -> Amount {
        Amount::from(self.coin.value)
    }
}

/// Balancer-facing wrapper around a [`QualifiedInfo`]. Carries the
/// wallet-domain [`TokenType`] string for the balancer's imbalance keys,
/// plus the full [`QualifiedInfo`] for the ledger adapter.
#[derive(Debug, Clone)]
pub struct ShieldedInputCoin {
    pub qci: QualifiedInfo,
    token_type_str: TokenType,
}

impl ShieldedInputCoin {
    #[must_use]
    pub fn from_qci(qci: QualifiedInfo) -> Self {
        let token_type_str = token_type_to_wallet_string(&qci.type_);
        Self {
            qci,
            token_type_str,
        }
    }
}

impl CoinRecipe for ShieldedInputCoin {
    #[inline]
    fn token_type(&self) -> &TokenType {
        &self.token_type_str
    }

    #[inline]
    fn value(&self) -> Amount {
        Amount::from(self.qci.value)
    }
}

/// The plan for one shielded transfer: which coins to spend, what
/// recipient outputs to produce, and what change outputs to emit.
///
/// Mirrors [`crate::unshielded::TransferRecipe`] in layout — the
/// ledger adapter concatenates `recipient_outputs` followed by
/// `change_outputs` when building the final zswap offer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShieldedTransferRecipe {
    pub inputs: Vec<QualifiedInfo>,
    pub recipient_outputs: Vec<ShieldedOutputSpec>,
    pub change_outputs: Vec<ShieldedOutputSpec>,
}

impl ShieldedTransferRecipe {
    /// Iterate recipient outputs followed by change outputs. Matches
    /// [`crate::unshielded::TransferRecipe::all_outputs`].
    #[must_use]
    pub fn all_outputs(&self) -> Vec<&ShieldedOutputSpec> {
        let mut out = Vec::with_capacity(self.recipient_outputs.len() + self.change_outputs.len());
        for o in &self.recipient_outputs {
            out.push(o);
        }
        for o in &self.change_outputs {
            out.push(o);
        }
        out
    }

    /// Count of all produced outputs.
    #[inline]
    #[must_use]
    pub fn total_output_count(&self) -> usize {
        self.recipient_outputs.len() + self.change_outputs.len()
    }
}

/// Encode a 32-byte [`ShieldedTokenType`] as the lowercase-hex string
/// the balancer keys on. Inverse of [`token_type_from_wallet_string`].
pub(crate) fn token_type_to_wallet_string(t: &ShieldedTokenType) -> TokenType {
    TokenType::new(hex::encode(t.0 .0))
}

/// Decode the balancer's wallet-domain [`TokenType`] back into a
/// [`ShieldedTokenType`]. Errors if the string isn't 64 hex chars.
pub(crate) fn token_type_from_wallet_string(t: &TokenType) -> Result<ShieldedTokenType> {
    let s = t.as_str();
    let bytes = hex::decode(s).map_err(|e| {
        WalletError::InvalidTokenType(format!("shielded token type `{s}` is not valid hex: {e}"))
    })?;
    let arr = <[u8; 32]>::try_from(bytes.as_slice()).map_err(|_| {
        WalletError::InvalidTokenType(format!(
            "shielded token type `{s}` decoded to {} bytes; expected 32",
            bytes.len()
        ))
    })?;
    Ok(ShieldedTokenType(
        moonproof_ledger::transient_crypto::hash::HashOutput(arr),
    ))
}

/// Build the set of candidate input coins from a [`ShieldedState`] —
/// every confirmed coin whose nullifier isn't already in
/// `pending_spends` (i.e. we haven't locally spent it yet). Order
/// follows the underlying trie's deterministic iteration.
pub(crate) fn candidate_inputs(
    state: &ShieldedState,
    secret_keys: &ZswapSecretKeys,
) -> Vec<ShieldedInputCoin> {
    let pending: std::collections::HashSet<_> = state
        .local()
        .pending_spends
        .iter()
        .map(|(_, sp)| sp.nonce)
        .collect();

    let mut out = Vec::with_capacity(state.local().coins.size());
    for (nullifier, qci) in state.local().coins.iter() {
        if pending.contains(&qci.nonce) {
            continue;
        }
        let _ = nullifier; // sanity-derived from coin+sk via coin_nullifier if we ever need it.
        out.push(ShieldedInputCoin::from_qci(*qci));
    }
    // Keep the parameter live for future use — the TS reference does
    // `coinHashes.updateWithCoins` here; we recompute on demand via
    // [`coin_nullifier`] (used elsewhere).
    let _ = secret_keys;
    out
}

/// Compute the initial imbalances for a set of transfers. Each transfer
/// debits the shielded balance by its `amount`. No fee-token overhead is
/// applied because [`SHIELDED_COST_MODEL`] is zero.
fn initial_imbalances(transfers: &[ShieldedTransfer]) -> Result<Imbalances> {
    let mut imb = Imbalances::new();
    for t in transfers {
        if t.amount == 0 {
            return Err(WalletError::SigningFailed(
                "shielded transfer amount must be positive".to_owned(),
            ));
        }
        let token = token_type_to_wallet_string(&t.token_type);
        let amount = Amount::from(t.amount);
        let cur = imb.get(&token);
        imb.set(
            token,
            cur.checked_sub(amount).ok_or(WalletError::AmountOverflow)?,
        );
    }
    Ok(imb)
}

/// Build a shielded transfer recipe.
///
/// - `rng` must be cryptographically secure — used to generate fresh
///   nonces for every produced [`CoinInfo`].
/// - `state` supplies the candidate input pool (excluding locally-pending
///   spends).
/// - `secret_keys` is the spender's [`ZswapSecretKeys`]; used to
///   reconstruct coin nullifiers when needed (the recipe itself stays
///   in terms of `QualifiedInfo`).
/// - `transfers` is a non-empty list of `(amount, type, recipient)`
///   instructions. Amounts of zero are rejected.
///
/// Errors:
///
/// - [`WalletError::InsufficientFunds`] if the balancer can't close a
///   deficit for some token.
/// - [`WalletError::AmountOverflow`] if any amount overflows the
///   balancer's signed-i128 representation.
/// - [`WalletError::InvalidTokenType`] if a produced change output
///   carries a token whose hex form can't be recovered (shouldn't
///   happen in practice — the round-trip through
///   [`token_type_to_wallet_string`] / [`token_type_from_wallet_string`]
///   is lossless for any 32-byte hash).
pub fn build_shielded_transfer_recipe<R: Rng + CryptoRng + ?Sized>(
    rng: &mut R,
    state: &ShieldedState,
    secret_keys: &ZswapSecretKeys,
    transfers: &[ShieldedTransfer],
) -> Result<ShieldedTransferRecipe> {
    if transfers.is_empty() {
        return Ok(ShieldedTransferRecipe {
            inputs: Vec::new(),
            recipient_outputs: Vec::new(),
            change_outputs: Vec::new(),
        });
    }

    // 1. Recipient outputs. Each gets a fresh nonce so the on-chain
    //    commitment doesn't collide with anything else.
    let mut recipient_outputs: Vec<ShieldedOutputSpec> = Vec::with_capacity(transfers.len());
    for t in transfers {
        if t.amount == 0 {
            return Err(WalletError::SigningFailed(
                "shielded transfer amount must be positive".to_owned(),
            ));
        }
        let coin = CoinInfo::new(rng, t.amount, t.token_type);
        recipient_outputs.push(ShieldedOutputSpec::new(
            coin,
            t.recipient.coin_public_key.clone(),
            t.recipient.encryption_public_key.clone(),
        ));
    }

    // 2. Initial imbalances: we're short `amount` of every transfer's
    //    token until the balancer pulls inputs.
    let initial = initial_imbalances(transfers)?;

    balance_with_change(
        rng,
        state,
        secret_keys,
        initial,
        Imbalances::new(),
        recipient_outputs,
    )
}

/// Build the shielded half of a swap: an offer whose inputs exceed its
/// change by exactly `desired_inputs`, plus an unfunded output for each
/// of `desired_outputs`. The counterparty's offer closes both
/// imbalances; nothing here pays for the outputs.
///
/// Mirrors `TransactingCapabilityImplementation.initSwap` in
/// midnight-wallet's shielded wallet: the guaranteed section is
/// balanced from empty imbalances towards `desired_inputs` as the
/// target, and the desired outputs are merged in afterwards.
///
/// # Errors
///
/// - [`WalletError::InvalidAmount`] when any input or output amount is
///   zero, or when both lists are empty.
/// - [`WalletError::InsufficientFunds`] when the wallet's available
///   coins cannot cover `desired_inputs`.
pub fn build_shielded_init_swap_recipe<R: Rng + CryptoRng + ?Sized>(
    rng: &mut R,
    state: &ShieldedState,
    secret_keys: &ZswapSecretKeys,
    desired_inputs: &[(ShieldedTokenType, u128)],
    desired_outputs: &[ShieldedTransfer],
) -> Result<ShieldedTransferRecipe> {
    if desired_inputs.is_empty() && desired_outputs.is_empty() {
        return Err(WalletError::InvalidAmount(
            "a shielded swap needs at least one input or output".to_owned(),
        ));
    }
    if desired_outputs.iter().any(|t| t.amount == 0) {
        return Err(WalletError::InvalidAmount(
            "shielded swap output amounts must be positive".to_owned(),
        ));
    }
    if desired_inputs.iter().any(|(_, amount)| *amount == 0) {
        return Err(WalletError::InvalidAmount(
            "shielded swap input amounts must be positive".to_owned(),
        ));
    }

    let recipient_outputs: Vec<ShieldedOutputSpec> = desired_outputs
        .iter()
        .map(|t| {
            ShieldedOutputSpec::new(
                CoinInfo::new(rng, t.amount, t.token_type),
                t.recipient.coin_public_key.clone(),
                t.recipient.encryption_public_key.clone(),
            )
        })
        .collect();

    let mut target = Imbalances::new();
    for (token_type, amount) in desired_inputs {
        let token = token_type_to_wallet_string(token_type);
        let total = target
            .get(&token)
            .checked_add(Amount::from(*amount))
            .ok_or(WalletError::AmountOverflow)?;
        target.set(token, total);
    }

    balance_with_change(
        rng,
        state,
        secret_keys,
        Imbalances::new(),
        target,
        recipient_outputs,
    )
}

/// Select the wallet's coins that move `initial` to `target`, returning
/// change to the wallet's own keys, and wrap them with
/// `recipient_outputs` into a recipe.
fn balance_with_change<R: Rng + CryptoRng + ?Sized>(
    rng: &mut R,
    state: &ShieldedState,
    secret_keys: &ZswapSecretKeys,
    initial: Imbalances,
    target: Imbalances,
    recipient_outputs: Vec<ShieldedOutputSpec>,
) -> Result<ShieldedTransferRecipe> {
    // 3. Candidate coins. Wrapped with the wallet TokenType so the
    //    balancer can key on them.
    let coins = candidate_inputs(state, secret_keys);

    // 4. Change-output builder: change goes back to the sender's own
    //    coin / encryption public keys.
    let our_coin_pk = ShieldedCoinPublicKey(state.coin_public_key().0 .0);
    let enc_pk_bytes = encode_encryption_public_key(&state.encryption_public_key())?;
    let our_enc_pk = ShieldedEncryptionPublicKey(enc_pk_bytes);

    // The balancer's fee_token is irrelevant when overheads are zero,
    // but we still must supply a value — use a synthetic sentinel that
    // can never match a real shielded token hex.
    let placeholder_fee_token = TokenType::new("shielded-fee-placeholder");
    let br = {
        let rng_cell = RngCell { rng };
        balance(BalanceRequest {
            coins,
            initial_imbalances: initial,
            target_imbalances: target,
            cost_model: SHIELDED_COST_MODEL,
            fee_token: placeholder_fee_token,
            selector: &SmallestFirstSelector,
            create_output: |r| {
                // Safe: the balancer only emits positive-valued change.
                let v = u128::try_from(r.value.max(crate::types::Amount::ZERO)).unwrap_or(0);
                // The balancer only echoes token types it received from
                // our own candidate inputs, which we always populated
                // via `token_type_to_wallet_string`; the inverse thus
                // never fails at runtime. If it ever did, we'd emit a
                // zero-hash placeholder so the mismatch surfaces at
                // well-formedness time rather than silently corrupting
                // the recipe.
                let tt = token_type_from_wallet_string(&r.token_type).unwrap_or(ShieldedTokenType(
                    moonproof_ledger::transient_crypto::hash::HashOutput([0u8; 32]),
                ));
                let coin = CoinInfo::new(rng_cell.rng, v, tt);
                ShieldedOutputSpec::new(coin, our_coin_pk.clone(), our_enc_pk.clone())
            },
            is_coin_equal: |a, b| a.qci.nonce == b.qci.nonce,
        })?
    };

    let inputs: Vec<QualifiedInfo> = br.inputs.into_iter().map(|w| w.qci).collect();

    Ok(ShieldedTransferRecipe {
        inputs,
        recipient_outputs,
        change_outputs: br.outputs,
    })
}

/// Tiny helper struct to carry an `&mut R` into a closure without
/// triggering the borrow checker's move-vs-reborrow warnings. `FnMut`
/// can borrow mutably from `self` of the capture, so this just provides
/// a stable storage slot.
struct RngCell<'r, R: Rng + CryptoRng + ?Sized> {
    rng: &'r mut R,
}

/// Serialize an encryption public key into the 32-byte form expected by
/// [`ShieldedEncryptionPublicKey`]. The ledger's `encryption::PublicKey`
/// exposes `to_bytes_le` via its underlying `EmbeddedGroupAffine` — we
/// use the standard `Serializable` path so the result matches what
/// `@midnight-ntwrk/wallet-sdk-address-format` consumes on the TS side.
fn encode_encryption_public_key(
    pk: &moonproof_ledger::transient_crypto::encryption::PublicKey,
) -> Result<[u8; 32]> {
    use moonproof_ledger::serialize::Serializable;
    let mut buf = Vec::with_capacity(32);
    pk.serialize(&mut buf)
        .map_err(|e| WalletError::Serialization(format!("encryption PublicKey::serialize: {e}")))?;
    <[u8; 32]>::try_from(buf.as_slice()).map_err(|_| {
        WalletError::Serialization(format!(
            "encryption PublicKey serialized to {} bytes; expected 32",
            buf.len()
        ))
    })
}

/// Derive the sender's own [`ShieldedAddress`] from a [`ShieldedState`].
/// Useful for self-transfer tests and for call sites that want to route
/// change somewhere other than the state's own keys.
pub fn own_shielded_address(state: &ShieldedState) -> Result<ShieldedAddress> {
    let coin_pk = ShieldedCoinPublicKey(state.coin_public_key().0 .0);
    let enc_pk_bytes = encode_encryption_public_key(&state.encryption_public_key())?;
    let enc_pk = ShieldedEncryptionPublicKey(enc_pk_bytes);
    Ok(ShieldedAddress::new(coin_pk, enc_pk))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::abstractions::NetworkId;
    use moonproof_ledger::coin_structure::coin::{
        Nonce, PublicKey as CoinPublicKey, ShieldedTokenType,
    };
    use moonproof_ledger::serialize::Serializable;
    use moonproof_ledger::transient_crypto::hash::HashOutput;
    use moonproof_ledger::zswap::keys::Seed as ZswapSeed;
    use rand::rngs::StdRng;
    use rand::SeedableRng;

    fn keys_from_byte(b: u8) -> ZswapSecretKeys {
        ZswapSecretKeys::from(ZswapSeed::from([b; 32]))
    }

    fn recipient_for(keys: &ZswapSecretKeys) -> ShieldedAddress {
        let coin_pk = ShieldedCoinPublicKey(keys.coin_public_key().0 .0);
        let mut enc_buf = Vec::new();
        keys.enc_public_key().serialize(&mut enc_buf).unwrap();
        let enc_pk = ShieldedEncryptionPublicKey(<[u8; 32]>::try_from(enc_buf.as_slice()).unwrap());
        ShieldedAddress::new(coin_pk, enc_pk)
    }

    fn mk_tt(byte: u8) -> ShieldedTokenType {
        ShieldedTokenType(HashOutput([byte; 32]))
    }

    /// Seed a state by manually inserting `QualifiedInfo`s into the
    /// coins map via the ledger-side `insert_coin` path — a minimal
    /// substitute for a full `apply(offer)` round-trip. Returns the
    /// wrapping `ShieldedState`.
    fn seed_state_with_coins(
        keys: &ZswapSecretKeys,
        coins: &[(u128, ShieldedTokenType)],
    ) -> ShieldedState {
        // Build a ZswapLocalState with each coin inserted. Each
        // insert_coin advances first_free and updates the Merkle tree.
        let mut local = moonproof_ledger::zswap::local::State::<
            moonproof_ledger::storage::db::InMemoryDB,
        >::new();
        for (value, type_) in coins {
            let info = CoinInfo {
                nonce: Nonce(HashOutput({
                    // Deterministic nonce from value + type so the
                    // balancer's selection order is reproducible in
                    // snapshot tests.
                    let mut b = [0u8; 32];
                    b[0] = value.to_le_bytes()[0];
                    b[1] = type_.0 .0[0];
                    b
                })),
                type_: *type_,
                value: *value,
            };
            local = local.insert_coin(keys, info).expect("insert_coin");
        }
        ShieldedState::init(local, keys, NetworkId::Undeployed)
    }

    #[test]
    fn empty_transfer_list_yields_empty_recipe() {
        let keys = keys_from_byte(0x01);
        let state = ShieldedState::init_empty(&keys, NetworkId::Undeployed);
        let mut rng = StdRng::seed_from_u64(1);
        let r = build_shielded_transfer_recipe(&mut rng, &state, &keys, &[]).unwrap();
        assert_eq!(r.inputs, [] as [QualifiedInfo; 0]);
        assert_eq!(r.recipient_outputs, [] as [ShieldedOutputSpec; 0]);
        assert_eq!(r.change_outputs, [] as [ShieldedOutputSpec; 0]);
    }

    #[test]
    fn zero_amount_transfer_errors() {
        let keys = keys_from_byte(0x02);
        let state = ShieldedState::init_empty(&keys, NetworkId::Undeployed);
        let mut rng = StdRng::seed_from_u64(2);
        let transfers = vec![ShieldedTransfer::new(0, mk_tt(0x11), recipient_for(&keys))];
        let err = build_shielded_transfer_recipe(&mut rng, &state, &keys, &transfers).unwrap_err();
        assert!(matches!(err, WalletError::SigningFailed(_)));
    }

    #[test]
    fn insufficient_funds_errors() {
        let keys = keys_from_byte(0x03);
        let state = seed_state_with_coins(&keys, &[(10, mk_tt(0x11))]);
        let mut rng = StdRng::seed_from_u64(3);
        // Transfer more than we have.
        let transfers = vec![ShieldedTransfer::new(
            1_000,
            mk_tt(0x11),
            recipient_for(&keys_from_byte(0xAA)),
        )];
        let err = build_shielded_transfer_recipe(&mut rng, &state, &keys, &transfers).unwrap_err();
        assert!(matches!(err, WalletError::InsufficientFunds { .. }));
    }

    #[test]
    fn single_transfer_pulls_input_and_emits_one_recipient_output() {
        let keys = keys_from_byte(0x04);
        let state = seed_state_with_coins(&keys, &[(1_000, mk_tt(0x22))]);
        let mut rng = StdRng::seed_from_u64(4);
        let recipient = recipient_for(&keys_from_byte(0xBB));
        let transfers = vec![ShieldedTransfer::new(500, mk_tt(0x22), recipient.clone())];

        let r = build_shielded_transfer_recipe(&mut rng, &state, &keys, &transfers).unwrap();
        assert_eq!(r.inputs.len(), 1);
        assert_eq!(r.inputs[0].value, 1_000);
        assert_eq!(r.recipient_outputs.len(), 1);
        assert_eq!(r.recipient_outputs[0].coin.value, 500);
        assert_eq!(r.recipient_outputs[0].coin.type_, mk_tt(0x22));
        assert_eq!(
            r.recipient_outputs[0].recipient_coin_pk,
            recipient.coin_public_key
        );
        assert_eq!(
            r.recipient_outputs[0].recipient_enc_pk,
            recipient.encryption_public_key
        );
        // Change output: 1000 - 500 = 500 back to sender.
        assert_eq!(r.change_outputs.len(), 1);
        assert_eq!(r.change_outputs[0].coin.value, 500);
        assert_eq!(r.change_outputs[0].coin.type_, mk_tt(0x22));
        assert!(r.change_outputs[0].is_self(&ShieldedCoinPublicKey(keys.coin_public_key().0 .0)));
    }

    #[test]
    fn transfer_spending_exact_balance_emits_no_change() {
        let keys = keys_from_byte(0x05);
        let state = seed_state_with_coins(&keys, &[(500, mk_tt(0x33))]);
        let mut rng = StdRng::seed_from_u64(5);
        let recipient = recipient_for(&keys_from_byte(0xCC));
        let transfers = vec![ShieldedTransfer::new(500, mk_tt(0x33), recipient)];

        let r = build_shielded_transfer_recipe(&mut rng, &state, &keys, &transfers).unwrap();
        assert_eq!(r.inputs.len(), 1);
        assert_eq!(r.recipient_outputs.len(), 1);
        assert!(
            r.change_outputs.is_empty(),
            "balancer should emit no change when input equals output value"
        );
    }

    #[test]
    fn multiple_transfers_same_token_balance_correctly() {
        let keys = keys_from_byte(0x06);
        let state = seed_state_with_coins(&keys, &[(1_000, mk_tt(0x44)), (2_000, mk_tt(0x44))]);
        let mut rng = StdRng::seed_from_u64(6);
        let r1 = recipient_for(&keys_from_byte(0xD1));
        let r2 = recipient_for(&keys_from_byte(0xD2));
        let transfers = vec![
            ShieldedTransfer::new(700, mk_tt(0x44), r1),
            ShieldedTransfer::new(500, mk_tt(0x44), r2),
        ];

        let r = build_shielded_transfer_recipe(&mut rng, &state, &keys, &transfers).unwrap();
        assert_eq!(r.recipient_outputs.len(), 2);
        assert_eq!(r.recipient_outputs[0].coin.value, 700);
        assert_eq!(r.recipient_outputs[1].coin.value, 500);
        // 1_000 pulled first (smallest-first); 700+500 = 1_200 > 1_000 so
        // a second input pulls; total excess (3_000 - 1_200 = 1_800) goes
        // to change.
        assert_ne!(r.inputs, [] as [QualifiedInfo; 0]);
        let input_total: u128 = r.inputs.iter().map(|q| q.value).sum();
        let change_total: u128 = r.change_outputs.iter().map(|o| o.coin.value).sum();
        assert_eq!(input_total, 700 + 500 + change_total);
    }

    #[test]
    fn multi_token_transfer_creates_recipient_output_per_transfer() {
        let keys = keys_from_byte(0x07);
        let state = seed_state_with_coins(&keys, &[(1_000, mk_tt(0x55)), (1_000, mk_tt(0x66))]);
        let mut rng = StdRng::seed_from_u64(7);
        let transfers = vec![
            ShieldedTransfer::new(300, mk_tt(0x55), recipient_for(&keys_from_byte(0xE1))),
            ShieldedTransfer::new(400, mk_tt(0x66), recipient_for(&keys_from_byte(0xE2))),
        ];

        let r = build_shielded_transfer_recipe(&mut rng, &state, &keys, &transfers).unwrap();
        assert_eq!(r.recipient_outputs.len(), 2);
        assert_eq!(r.recipient_outputs[0].coin.type_, mk_tt(0x55));
        assert_eq!(r.recipient_outputs[1].coin.type_, mk_tt(0x66));
        // Both inputs needed (one per token type).
        assert_eq!(r.inputs.len(), 2);
    }

    #[test]
    fn change_outputs_route_back_to_sender_coin_pk() {
        let keys = keys_from_byte(0x08);
        let state = seed_state_with_coins(&keys, &[(1_000_000, mk_tt(0x77))]);
        let mut rng = StdRng::seed_from_u64(8);
        let transfers = vec![ShieldedTransfer::new(
            123,
            mk_tt(0x77),
            recipient_for(&keys_from_byte(0xF1)),
        )];

        let r = build_shielded_transfer_recipe(&mut rng, &state, &keys, &transfers).unwrap();
        let our_pk = ShieldedCoinPublicKey(keys.coin_public_key().0 .0);
        for o in &r.change_outputs {
            assert!(
                o.is_self(&our_pk),
                "every change output must be addressed to the sender"
            );
        }
    }

    #[test]
    fn all_outputs_returns_recipients_first_then_change() {
        let keys = keys_from_byte(0x09);
        let state = seed_state_with_coins(&keys, &[(1_000, mk_tt(0x88))]);
        let mut rng = StdRng::seed_from_u64(9);
        let transfers = vec![ShieldedTransfer::new(
            300,
            mk_tt(0x88),
            recipient_for(&keys_from_byte(0xA1)),
        )];
        let r = build_shielded_transfer_recipe(&mut rng, &state, &keys, &transfers).unwrap();
        let all = r.all_outputs();
        assert_eq!(all.len(), r.total_output_count());
        for (i, ro) in r.recipient_outputs.iter().enumerate() {
            assert_eq!(all[i], ro);
        }
        for (i, co) in r.change_outputs.iter().enumerate() {
            assert_eq!(all[r.recipient_outputs.len() + i], co);
        }
    }

    #[test]
    fn fresh_nonces_are_generated_per_output() {
        let keys = keys_from_byte(0x0A);
        let state = seed_state_with_coins(&keys, &[(1_000, mk_tt(0x99))]);
        let mut rng = StdRng::seed_from_u64(10);
        let transfers = vec![ShieldedTransfer::new(
            500,
            mk_tt(0x99),
            recipient_for(&keys_from_byte(0xAA)),
        )];
        let r = build_shielded_transfer_recipe(&mut rng, &state, &keys, &transfers).unwrap();
        let all = r.all_outputs();
        // All nonces must differ — no nonce reuse.
        let mut seen = std::collections::HashSet::new();
        for o in &all {
            assert!(
                seen.insert(o.coin.nonce),
                "nonce reused: {:?}",
                o.coin.nonce
            );
        }
    }

    #[test]
    fn token_type_wallet_string_round_trips() {
        let tt = mk_tt(0xAB);
        let s = token_type_to_wallet_string(&tt);
        let back = token_type_from_wallet_string(&s).unwrap();
        assert_eq!(back, tt);
    }

    #[test]
    fn own_shielded_address_matches_wallet_keys() {
        let keys = keys_from_byte(0x0B);
        let state = ShieldedState::init_empty(&keys, NetworkId::Undeployed);
        let addr = own_shielded_address(&state).unwrap();
        assert_eq!(addr.coin_public_key.0, keys.coin_public_key().0 .0);
    }

    #[test]
    fn pending_spends_excluded_from_candidate_inputs() {
        // Seed a state with one coin, then "spend" it so it moves to
        // pending_spends. candidate_inputs must skip it.
        let keys = keys_from_byte(0x0C);
        let state = seed_state_with_coins(&keys, &[(1_000, mk_tt(0xAB))]);
        // Pull the qci out and forge a spend via the ledger API.
        let (nullifier, qci) = state.local().coins.iter().next().unwrap();
        let mut rng = StdRng::seed_from_u64(12);
        let (new_local, _input) = state
            .local()
            .spend(&mut rng, &keys, &qci, None)
            .expect("spend");
        let _ = nullifier;
        let state_after = ShieldedState::init(new_local, &keys, NetworkId::Undeployed);
        assert_eq!(state_after.pending_spend_count(), 1);
        let candidates = candidate_inputs(&state_after, &keys);
        assert!(
            candidates.is_empty(),
            "pending-spent coin must not appear in candidates"
        );
    }

    #[test]
    fn amount_close_to_u128_max_errors_overflow() {
        let keys = keys_from_byte(0x0D);
        let state = ShieldedState::init_empty(&keys, NetworkId::Undeployed);
        let mut rng = StdRng::seed_from_u64(13);
        let transfers = vec![ShieldedTransfer::new(
            u128::MAX,
            mk_tt(0x01),
            recipient_for(&keys_from_byte(0x02)),
        )];
        let err = build_shielded_transfer_recipe(&mut rng, &state, &keys, &transfers).unwrap_err();
        assert!(
            matches!(
                err,
                WalletError::AmountOverflow | WalletError::InsufficientFunds { .. }
            ),
            "expected AmountOverflow or InsufficientFunds, got {err:?}"
        );
    }

    /// Regression test: the shielded transfer pipeline must accept
    /// inputs whose `type_` is a non-NIGHT custom shielded token (the
    /// kind a `MintExecutable` deploys). Prior to this assertion
    /// landing, the only existing live-harness mint→spend coverage
    /// was end-to-end and only ran with the harness up; this is the
    /// pure-Rust unit-test counterpart that exercises the same
    /// invariant offline.
    ///
    /// The custom token type is deliberately distinct from the all-
    /// zeros NIGHT sentinel: a recipe whose token accounting silently
    /// fell back to NIGHT would still pass the equality check on
    /// `mk_tt(0x..)`, so we assert both the explicit non-NIGHT
    /// invariant *and* the recipe carries the same custom type
    /// through inputs / recipient / change.
    #[test]
    fn shielded_transfer_handles_custom_token_type_input() {
        const NIGHT_SHIELDED: ShieldedTokenType = ShieldedTokenType(HashOutput([0u8; 32]));
        let custom = mk_tt(0xC1);
        assert_ne!(
            custom.0 .0, NIGHT_SHIELDED.0 .0,
            "test fixture must use a non-NIGHT custom token"
        );

        let keys = keys_from_byte(0x10);
        // Seed with two coins of the SAME custom color so the balancer
        // has a non-trivial selection to make. If the balancer
        // accidentally normalized to NIGHT it'd see 0 inputs of the
        // requested color and InsufficientFunds.
        let state = seed_state_with_coins(&keys, &[(800, custom), (300, custom)]);
        let mut rng = StdRng::seed_from_u64(0x10);
        let recipient = recipient_for(&keys_from_byte(0xC2));
        let transfers = vec![ShieldedTransfer::new(700, custom, recipient.clone())];

        let r = build_shielded_transfer_recipe(&mut rng, &state, &keys, &transfers)
            .expect("recipe must build for a custom-token transfer");

        // Inputs: at least one selected, all carrying the custom type.
        assert!(!r.inputs.is_empty(), "must select at least one input");
        for input in &r.inputs {
            assert_eq!(
                input.type_, custom,
                "every selected input must match the requested custom token type"
            );
            assert_ne!(
                input.type_, NIGHT_SHIELDED,
                "no NIGHT-shaped inputs allowed"
            );
        }

        // Recipient output: exactly one, of the custom type.
        assert_eq!(r.recipient_outputs.len(), 1);
        assert_eq!(r.recipient_outputs[0].coin.value, 700);
        assert_eq!(
            r.recipient_outputs[0].coin.type_, custom,
            "recipient output must carry the custom token type"
        );

        // Change is custom-typed too — non-trivial when total selected
        // inputs exceed the transfer amount.
        let inputs_sum: u128 = r.inputs.iter().map(|i| i.value).sum();
        let recipient_sum: u128 = r.recipient_outputs.iter().map(|o| o.coin.value).sum();
        if inputs_sum > recipient_sum {
            assert!(
                !r.change_outputs.is_empty(),
                "change must be emitted when inputs exceed recipient amount"
            );
            for change in &r.change_outputs {
                assert_eq!(
                    change.coin.type_, custom,
                    "change must preserve the custom token type"
                );
            }
        }
    }

    /// The ledger's `Offer<ProofPreimage>` accounting tracks per-token
    /// imbalances. When the input AND output(s) are non-NIGHT, the
    /// imbalance for the custom token must zero out — otherwise the
    /// resulting tx would fail the binding-commitment check at submit.
    /// This is the offline analogue of the live mint→spend leg.
    #[test]
    fn shielded_transfer_offer_balances_for_custom_token_type() {
        let custom = mk_tt(0xCC);
        let keys = keys_from_byte(0x11);
        let state = seed_state_with_coins(&keys, &[(1_000, custom)]);
        let mut rng = StdRng::seed_from_u64(0x11);
        let recipient = recipient_for(&keys_from_byte(0xDD));
        let transfers = vec![ShieldedTransfer::new(400, custom, recipient)];

        let r = build_shielded_transfer_recipe(&mut rng, &state, &keys, &transfers)
            .expect("recipe must build");

        // Sum inputs and outputs for the custom color and assert the
        // resulting imbalance is zero. Recipient + change must equal
        // the total input value.
        let inputs_sum: u128 = r
            .inputs
            .iter()
            .filter(|i| i.type_ == custom)
            .map(|i| i.value)
            .sum();
        let recipient_sum: u128 = r
            .recipient_outputs
            .iter()
            .filter(|o| o.coin.type_ == custom)
            .map(|o| o.coin.value)
            .sum();
        let change_sum: u128 = r
            .change_outputs
            .iter()
            .filter(|o| o.coin.type_ == custom)
            .map(|o| o.coin.value)
            .sum();
        assert_eq!(
            inputs_sum,
            recipient_sum + change_sum,
            "shielded recipe must balance for the custom token type \
             (inputs: {inputs_sum}, recipient: {recipient_sum}, change: {change_sum})"
        );
    }

    #[test]
    fn coin_public_key_round_trips_through_our_coin_pk_sentinel() {
        // Regression: ensure our representation of the wallet's coin
        // public key matches the ShieldedCoinPublicKey address byte
        // shape. Load-bearing: the ledger-adapter layer routes change
        // outputs by reconstructing ShieldedCoinPublicKey from this.
        let keys = keys_from_byte(0x0E);
        let pk: CoinPublicKey = keys.coin_public_key();
        let addr_bytes = ShieldedCoinPublicKey(pk.0 .0);
        assert_eq!(addr_bytes.0, pk.0 .0);
    }

    fn input_minus_change(r: &ShieldedTransferRecipe, tt: ShieldedTokenType) -> u128 {
        let spent: u128 = r
            .inputs
            .iter()
            .filter(|c| c.type_ == tt)
            .map(|c| c.value)
            .sum();
        let change: u128 = r
            .change_outputs
            .iter()
            .filter(|o| o.coin.type_ == tt)
            .map(|o| o.coin.value)
            .sum();
        spent - change
    }

    #[test]
    fn init_swap_commits_exactly_the_desired_inputs() {
        let keys = keys_from_byte(0x10);
        let state = seed_state_with_coins(&keys, &[(1_000, mk_tt(0x51))]);
        let mut rng = StdRng::seed_from_u64(10);
        let r =
            build_shielded_init_swap_recipe(&mut rng, &state, &keys, &[(mk_tt(0x51), 300)], &[])
                .unwrap();
        assert_eq!(r.inputs.len(), 1);
        assert_eq!(input_minus_change(&r, mk_tt(0x51)), 300);
        assert_eq!(r.recipient_outputs, [] as [ShieldedOutputSpec; 0]);
        let own = ShieldedCoinPublicKey(keys.coin_public_key().0 .0);
        assert!(r.change_outputs.iter().all(|o| o.is_self(&own)));
    }

    #[test]
    fn init_swap_leaves_desired_outputs_unfunded() {
        let keys = keys_from_byte(0x11);
        let state = seed_state_with_coins(&keys, &[(1_000, mk_tt(0x52))]);
        let mut rng = StdRng::seed_from_u64(11);
        let wanted = ShieldedTransfer::new(750, mk_tt(0x53), recipient_for(&keys));
        let r = build_shielded_init_swap_recipe(
            &mut rng,
            &state,
            &keys,
            &[(mk_tt(0x52), 400)],
            std::slice::from_ref(&wanted),
        )
        .unwrap();
        assert_eq!(input_minus_change(&r, mk_tt(0x52)), 400);
        assert_eq!(r.recipient_outputs.len(), 1);
        assert_eq!(r.recipient_outputs[0].coin.value, 750);
        assert_eq!(r.recipient_outputs[0].coin.type_, mk_tt(0x53));
        assert!(
            r.inputs.iter().all(|c| c.type_ != mk_tt(0x53)),
            "the wallet must not pay for an output it wants to receive"
        );
    }

    #[test]
    fn init_swap_with_outputs_only_spends_nothing() {
        let keys = keys_from_byte(0x12);
        let state = seed_state_with_coins(&keys, &[(1_000, mk_tt(0x54))]);
        let mut rng = StdRng::seed_from_u64(12);
        let wanted = ShieldedTransfer::new(10, mk_tt(0x54), recipient_for(&keys));
        let r = build_shielded_init_swap_recipe(&mut rng, &state, &keys, &[], &[wanted]).unwrap();
        assert_eq!(r.inputs, [] as [QualifiedInfo; 0]);
        assert_eq!(r.change_outputs, [] as [ShieldedOutputSpec; 0]);
        assert_eq!(r.recipient_outputs.len(), 1);
    }

    #[test]
    fn init_swap_sums_repeated_input_tokens() {
        let keys = keys_from_byte(0x13);
        let state = seed_state_with_coins(&keys, &[(500, mk_tt(0x55)), (600, mk_tt(0x55))]);
        let mut rng = StdRng::seed_from_u64(13);
        let r = build_shielded_init_swap_recipe(
            &mut rng,
            &state,
            &keys,
            &[(mk_tt(0x55), 300), (mk_tt(0x55), 400)],
            &[],
        )
        .unwrap();
        assert_eq!(input_minus_change(&r, mk_tt(0x55)), 700);
    }

    #[test]
    fn init_swap_rejects_zero_amounts_and_empty_requests() {
        let keys = keys_from_byte(0x14);
        let state = seed_state_with_coins(&keys, &[(1_000, mk_tt(0x56))]);
        let mut rng = StdRng::seed_from_u64(14);
        let zero_in =
            build_shielded_init_swap_recipe(&mut rng, &state, &keys, &[(mk_tt(0x56), 0)], &[]);
        assert!(matches!(zero_in, Err(WalletError::InvalidAmount(_))));
        let zero_out = build_shielded_init_swap_recipe(
            &mut rng,
            &state,
            &keys,
            &[],
            &[ShieldedTransfer::new(0, mk_tt(0x56), recipient_for(&keys))],
        );
        assert!(matches!(zero_out, Err(WalletError::InvalidAmount(_))));
        let empty = build_shielded_init_swap_recipe(&mut rng, &state, &keys, &[], &[]);
        assert!(matches!(empty, Err(WalletError::InvalidAmount(_))));
    }

    #[test]
    fn init_swap_beyond_the_balance_is_insufficient_funds() {
        let keys = keys_from_byte(0x15);
        let state = seed_state_with_coins(&keys, &[(100, mk_tt(0x57))]);
        let mut rng = StdRng::seed_from_u64(15);
        let err =
            build_shielded_init_swap_recipe(&mut rng, &state, &keys, &[(mk_tt(0x57), 101)], &[])
                .unwrap_err();
        assert!(matches!(err, WalletError::InsufficientFunds { .. }));
    }
}