moonproof-wallet 0.2.2

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
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
//! Balancing a transaction someone else built: the wallet supplies the
//! shielded and unshielded inputs and outputs that close every token
//! imbalance, segment by segment, books what it spends, then pays the
//! fee in Dust unless told not to.
//!
//! Port of `WalletFacade.balanceUnprovenTransaction`,
//! `balanceUnboundTransaction` and `balanceFinalizedTransaction` in
//! midnight-wallet's facade, and of the sub-wallet balancing they
//! compose. One imbalance map, [`Transaction::balance`], drives all
//! three; what differs is where each part may go:
//!
//! - Shielded value always travels in a standalone zswap leg (a
//!   guaranteed offer for segment 0, a fallible offer per other
//!   segment), proven on its own and merged in.
//! - Unshielded value of an unproven or unbound transaction is added in
//!   place, to the intents that carry the imbalance: a contract's
//!   unshielded receive must be met inside its own intent. A sealed
//!   transaction's intents are bound and cannot change, so its
//!   guaranteed imbalance is met by a new intent, and a fallible one
//!   cannot be met at all.
//! - The Dust fee is priced on everything that will be submitted
//!   together: the base, the balancing legs and the fee leg itself.
//!
//! Every function signs the wallet's unshielded inputs, so the result
//! needs only proving (and, for a proven base, sealing) to be ready to
//! submit.

use std::collections::{BTreeMap, BTreeSet};

use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::coin_structure::coin::TokenType as LedgerTokenType;
use moonproof_ledger::ledger::structure::{Intent, ProofKind, StandardTransaction, Transaction};
use moonproof_ledger::serialize::Serializable;
use moonproof_ledger::signatures::Signature;
use moonproof_ledger::storage::arena::Sp;
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
use moonproof_ledger::storage::Storable;
use moonproof_ledger::transient_crypto::commitment::PedersenRandomness;
use moonproof_ledger::transient_crypto::proofs::ProvingProvider;
use rand::rngs::OsRng;
use rand::{CryptoRng, Rng};

use crate::balancer::Imbalances;
use crate::dust::find_available_segment_id;
use crate::error::{Result, WalletError};
use crate::facade::state::FacadeState;
use crate::facade::submission::{finalize_recipe, FinalizedTransaction, ProvenTransaction};
use crate::facade::transfer::{
    balance_dust_fee, build_dust_balancing_tx, sign_unshielded_inputs, FeeContext, TransferOptions,
    TransferSigningKeys, UnprovenTransaction, UnprovenTransactionRecipe,
};
use crate::shielded::build_shielded_balancing_tx;
use crate::types::Amount;
use crate::unshielded::ledger_adapter::merge_into_offer;
use crate::unshielded::sync::token_type_from_ledger;
use crate::unshielded::{build_unshielded_balancing_recipe, UnshieldedState};

/// Per `(token, segment)` imbalance of a transaction, as
/// [`Transaction::balance`] reports it: positive is a surplus the
/// wallet collects, negative a deficit it pays.
pub type TransactionImbalances = BTreeMap<(LedgerTokenType, u16), i128>;

/// A proven, unbound transaction balanced by this wallet: `base` with
/// its unshielded imbalances closed in place and signed, plus the
/// unproven leg carrying the shielded balancing and the Dust fee.
/// [`UnboundBalancingRecipe::complete`] (or
/// [`finalize_unbound_recipe`]) turns it into the submittable form.
#[derive(Debug, Clone)]
pub struct UnboundBalancingRecipe {
    pub base: ProvenTransaction,
    pub balancing: Option<UnprovenTransaction>,
}

/// A sealed transaction and the signed, unproven leg that balances it
/// and pays its fee. [`SealedBalancingRecipe::complete`] (or
/// [`finalize_sealed_recipe`]) merges the proven leg in.
#[derive(Debug, Clone)]
pub struct SealedBalancingRecipe {
    pub original: FinalizedTransaction,
    pub balancing: Option<UnprovenTransaction>,
}

impl UnboundBalancingRecipe {
    /// Seal `base` and merge in `proven_balancing`, the
    /// [`Self::balancing`] leg once proven and sealed.
    ///
    /// # Errors
    /// [`WalletError::SigningFailed`] when a leg was built but none is
    /// given, and [`WalletError::Serialization`] when the merge fails.
    pub fn complete(
        self,
        proven_balancing: Option<FinalizedTransaction>,
    ) -> Result<FinalizedTransaction> {
        let sealed = self.base.seal(OsRng);
        merge_proven_leg(sealed, self.balancing.is_some(), proven_balancing)
    }
}

impl SealedBalancingRecipe {
    /// Merge `proven_balancing`, the [`Self::balancing`] leg once proven
    /// and sealed, into the original.
    ///
    /// # Errors
    /// As [`UnboundBalancingRecipe::complete`].
    pub fn complete(
        self,
        proven_balancing: Option<FinalizedTransaction>,
    ) -> Result<FinalizedTransaction> {
        merge_proven_leg(self.original, self.balancing.is_some(), proven_balancing)
    }
}

fn merge_proven_leg(
    sealed: FinalizedTransaction,
    leg_expected: bool,
    leg: Option<FinalizedTransaction>,
) -> Result<FinalizedTransaction> {
    match (leg_expected, leg) {
        (false, _) => Ok(sealed),
        (true, Some(leg)) => sealed.merge(&leg).map_err(|e| {
            WalletError::Serialization(format!("merge the proven balancing leg: {e:?}"))
        }),
        (true, None) => Err(WalletError::SigningFailed(
            "the recipe has a balancing leg, but no proven leg was given".to_owned(),
        )),
    }
}

/// Balance an unproven transaction: close its shielded and unshielded
/// imbalances, pay its fee when `options.pay_fees` is set, and sign the
/// wallet's inputs. The result is ready for
/// [`crate::facade::finalize_recipe`].
///
/// Returns the recipe and the facade with the spends booked and the
/// wallet's shielded change watched for.
///
/// # Errors
/// - [`WalletError::InsufficientFunds`] when the wallet cannot close an
///   imbalance or pay the fee.
/// - [`WalletError::SigningFailed`] when an imbalanced segment has no
///   intent to carry the wallet's unshielded offer, or that intent is
///   already signed.
pub fn balance_unproven_transaction<R>(
    rng: &mut R,
    state: FacadeState,
    tx: UnprovenTransaction,
    keys: &TransferSigningKeys<'_>,
    options: &TransferOptions,
) -> Result<(UnprovenTransactionRecipe, FacadeState)>
where
    R: Rng + CryptoRng,
{
    let imbalances = imbalances_of(&tx)?;
    let (shielded_leg, tx, mut facade) =
        balance_tokens_in_place(rng, state, tx, &imbalances, keys)?;
    let mut tx = merge_unproven(Some(tx), shielded_leg)?
        .ok_or_else(|| WalletError::Serialization("balancing lost the transaction".to_owned()))?;
    if options.pay_fees {
        let (dust, paid) = balance_dust_fee(
            rng,
            facade.dust.clone(),
            keys.dust_secret_key,
            &tx,
            &fee_context(&facade, options),
        )?;
        facade = facade.with_dust(dust);
        tx = paid;
    }
    let transaction = sign_unshielded_inputs(tx, keys.night_signing_key, rng)?;
    Ok((UnprovenTransactionRecipe { transaction }, facade))
}

/// Balance a proven, unbound transaction: its unshielded imbalances are
/// closed in place and its intents signed, while the shielded balancing
/// and, when `options.pay_fees` is set, the Dust fee go into one
/// unproven leg. Proving that leg and sealing `base` with it yields the
/// submittable transaction ([`finalize_unbound_recipe`]).
///
/// Returns the recipe and the facade with the spends booked.
///
/// # Errors
/// As [`balance_unproven_transaction`].
pub fn balance_unbound_recipe<R>(
    rng: &mut R,
    state: FacadeState,
    base: ProvenTransaction,
    keys: &TransferSigningKeys<'_>,
    options: &TransferOptions,
) -> Result<(UnboundBalancingRecipe, FacadeState)>
where
    R: Rng + CryptoRng,
{
    let imbalances = imbalances_of(&base)?;
    let (shielded_leg, base, facade) =
        balance_tokens_in_place(rng, state, base, &imbalances, keys)?;
    let base = sign_unshielded_inputs(base, keys.night_signing_key, rng)?;
    let (balancing, facade) = add_fee_leg(rng, facade, &base, shielded_leg, keys, options)?;
    let balancing = balancing
        .map(|leg| sign_unshielded_inputs(leg, keys.night_signing_key, rng))
        .transpose()?;
    Ok((UnboundBalancingRecipe { base, balancing }, facade))
}

/// Balance a sealed transaction. Its intents are bound, so everything
/// the wallet adds goes into one unproven leg: the shielded balancing,
/// a new intent whose guaranteed offer closes the guaranteed unshielded
/// imbalance, and, when `options.pay_fees` is set, the Dust fee.
///
/// Returns the recipe and the facade with the spends booked.
///
/// # Errors
/// - [`WalletError::InsufficientFunds`] as [`balance_unproven_transaction`].
/// - [`WalletError::SigningFailed`] when a fallible segment lacks
///   unshielded value: only its own intent could carry the offer that
///   pays it, and that intent is sealed.
pub fn balance_sealed_recipe<R>(
    rng: &mut R,
    state: FacadeState,
    original: FinalizedTransaction,
    keys: &TransferSigningKeys<'_>,
    options: &TransferOptions,
) -> Result<(SealedBalancingRecipe, FacadeState)>
where
    R: Rng + CryptoRng,
{
    let imbalances = imbalances_of(&original)?;
    let network = state.network_id().as_str().to_owned();
    let (shielded_leg, shielded) = build_shielded_balancing_tx(
        rng,
        state.shielded.clone(),
        keys.shielded_secret_keys,
        &imbalances,
        &network,
    )?;
    let mut facade = state.with_shielded(shielded);

    let unshielded = unshielded_imbalances_by_segment(&imbalances);
    if let Some((segment, _)) = unshielded
        .iter()
        .find(|(segment, imb)| **segment != 0 && imb.iter().any(|(_, v)| v < Amount::ZERO))
    {
        return Err(WalletError::SigningFailed(format!(
            "segment {segment} of the sealed transaction lacks unshielded value; only its own \
             intent could pay it, and that intent is bound"
        )));
    }
    let unshielded_leg = match unshielded.get(&0) {
        Some(guaranteed) => {
            let (leg, booked) = unshielded_balancing_intent(
                &original,
                guaranteed.clone(),
                facade.unshielded.clone(),
                keys,
                options.ttl,
                &network,
            )?;
            facade = facade.with_unshielded(booked);
            leg
        }
        None => None,
    };
    let tokens_leg = merge_unproven(shielded_leg, unshielded_leg)?;
    let (balancing, facade) = add_fee_leg(rng, facade, &original, tokens_leg, keys, options)?;
    let balancing = balancing
        .map(|leg| sign_unshielded_inputs(leg, keys.night_signing_key, rng))
        .transpose()?;
    Ok((
        SealedBalancingRecipe {
            original,
            balancing,
        },
        facade,
    ))
}

/// Prove the balancing leg of `recipe` with `prover`, seal the base and
/// merge the two: the transaction ready to submit.
///
/// # Errors
/// Proving and merge errors.
pub async fn finalize_unbound_recipe<P: ProvingProvider + Send + 'static>(
    recipe: UnboundBalancingRecipe,
    prover: P,
) -> Result<FinalizedTransaction> {
    let leg = prove_leg(recipe.balancing.as_ref(), prover).await?;
    recipe.complete(leg)
}

/// Prove the balancing leg of `recipe` with `prover` and merge it into
/// the original: the transaction ready to submit.
///
/// # Errors
/// Proving and merge errors.
pub async fn finalize_sealed_recipe<P: ProvingProvider + Send + 'static>(
    recipe: SealedBalancingRecipe,
    prover: P,
) -> Result<FinalizedTransaction> {
    let leg = prove_leg(recipe.balancing.as_ref(), prover).await?;
    recipe.complete(leg)
}

async fn prove_leg<P: ProvingProvider + Send + 'static>(
    leg: Option<&UnprovenTransaction>,
    prover: P,
) -> Result<Option<FinalizedTransaction>> {
    let Some(leg) = leg else {
        return Ok(None);
    };
    let recipe = UnprovenTransactionRecipe {
        transaction: leg.clone(),
    };
    Ok(Some(finalize_recipe(&recipe, prover).await?.transaction))
}

/// The imbalance map of `tx`.
///
/// # Errors
/// [`WalletError::Serialization`] when the ledger cannot total it.
pub fn imbalances_of<P, B>(
    tx: &Transaction<Signature, P, B, InMemoryDB>,
) -> Result<TransactionImbalances>
where
    P: ProofKind<InMemoryDB>,
    B: Storable<InMemoryDB>,
    Transaction<Signature, P, B, InMemoryDB>: Serializable,
{
    tx.balance(None).map_err(|e| {
        WalletError::Serialization(format!("total the transaction's imbalances: {e:?}"))
    })
}

/// A transaction whose intents are not yet bound, unproven or proven:
/// the shapes whose intents the wallet may still extend.
type Unbound<P> = Transaction<Signature, P, PedersenRandomness, InMemoryDB>;

/// Shielded leg plus in-place unshielded balancing, the part the
/// unproven and unbound cases share.
fn balance_tokens_in_place<R, P>(
    rng: &mut R,
    state: FacadeState,
    tx: Unbound<P>,
    imbalances: &TransactionImbalances,
    keys: &TransferSigningKeys<'_>,
) -> Result<(Option<UnprovenTransaction>, Unbound<P>, FacadeState)>
where
    R: Rng + CryptoRng,
    P: ProofKind<InMemoryDB>,
{
    let network = state.network_id().as_str().to_owned();
    let (shielded_leg, shielded) = build_shielded_balancing_tx(
        rng,
        state.shielded.clone(),
        keys.shielded_secret_keys,
        imbalances,
        &network,
    )?;
    let (tx, unshielded) =
        balance_unshielded_in_place(tx, imbalances, state.unshielded.clone(), keys)?;
    Ok((
        shielded_leg,
        tx,
        state.with_shielded(shielded).with_unshielded(unshielded),
    ))
}

/// Close each segment's unshielded imbalance inside the intent that
/// carries it: segment `s`'s in the fallible offer of intent `s`, the
/// guaranteed segment's in the guaranteed offer of the lowest intent.
/// Fallible segments go first, as midnight-wallet's
/// `#balanceUnboundishTransaction` does, each against the UTXOs the
/// previous ones left unbooked.
fn balance_unshielded_in_place<P>(
    tx: Unbound<P>,
    imbalances: &TransactionImbalances,
    state: UnshieldedState,
    keys: &TransferSigningKeys<'_>,
) -> Result<(Unbound<P>, UnshieldedState)>
where
    P: ProofKind<InMemoryDB>,
{
    let by_segment = unshielded_imbalances_by_segment(imbalances);
    if by_segment.is_empty() {
        return Ok((tx, state));
    }
    let Transaction::Standard(stx) = tx else {
        return Ok((tx, state));
    };
    let first_intent = stx.intents.keys().min();
    let mut ordered: Vec<(u16, Imbalances)> = by_segment.into_iter().collect();
    ordered.sort_by_key(|(segment, _)| (*segment == 0, *segment));

    let mut intents = stx.intents.clone();
    let mut state = state;
    for (segment, segment_imbalances) in ordered {
        let carrier = if segment == 0 {
            first_intent
        } else {
            Some(segment)
        };
        let Some(mut intent) = carrier.and_then(|s| intents.get(&s).map(|i| (*i).clone())) else {
            return Err(WalletError::SigningFailed(format!(
                "segment {segment} is unshielded-imbalanced but the transaction has no intent \
                 to carry the offer that balances it"
            )));
        };
        let recipe =
            build_unshielded_balancing_recipe(&state, keys.sender_owner, segment_imbalances)?;
        if recipe.inputs.is_empty() && recipe.change_outputs.is_empty() {
            continue;
        }
        for input in &recipe.inputs {
            state = state.spend_by_id(input.id())?;
        }
        let offer_slot = if segment == 0 {
            &mut intent.guaranteed_unshielded_offer
        } else {
            &mut intent.fallible_unshielded_offer
        };
        let merged = merge_into_offer(offer_slot.as_deref(), &recipe, keys.night_verifying_key)?;
        *offer_slot = Some(Sp::new(merged));
        if let Some(carrier) = carrier {
            intents = intents.insert(carrier, intent);
        }
    }
    Ok((
        Transaction::Standard(StandardTransaction {
            network_id: stx.network_id.clone(),
            intents,
            guaranteed_coins: stx.guaranteed_coins.clone(),
            fallible_coins: stx.fallible_coins.clone(),
            binding_randomness: stx.binding_randomness,
        }),
        state,
    ))
}

/// The unshielded part of `imbalances`, grouped per segment, without
/// the zero entries.
fn unshielded_imbalances_by_segment(
    imbalances: &TransactionImbalances,
) -> BTreeMap<u16, Imbalances> {
    let mut by_segment: BTreeMap<u16, Imbalances> = BTreeMap::new();
    for ((token, segment), value) in imbalances {
        let LedgerTokenType::Unshielded(raw) = token else {
            continue;
        };
        if *value == 0 {
            continue;
        }
        let token = token_type_from_ledger(raw);
        let segment_imbalances = by_segment.entry(*segment).or_default();
        let current = segment_imbalances.get(&token);
        segment_imbalances.set(token, current + Amount::from(*value));
    }
    by_segment
}

/// A standalone intent whose guaranteed offer closes `guaranteed`, the
/// guaranteed unshielded imbalance of the sealed `original`, at the
/// first segment `original` leaves free. It takes the TTL of
/// `original`'s first intent, as midnight-wallet's
/// `balanceFinalizedTransaction` does, so it expires with what it
/// balances.
fn unshielded_balancing_intent(
    original: &FinalizedTransaction,
    guaranteed: Imbalances,
    state: UnshieldedState,
    keys: &TransferSigningKeys<'_>,
    fallback_ttl: Timestamp,
    network: &str,
) -> Result<(Option<UnprovenTransaction>, UnshieldedState)> {
    let recipe = build_unshielded_balancing_recipe(&state, keys.sender_owner, guaranteed)?;
    if recipe.inputs.is_empty() && recipe.change_outputs.is_empty() {
        return Ok((None, state));
    }
    let mut state = state;
    for input in &recipe.inputs {
        state = state.spend_by_id(input.id())?;
    }
    let (used, ttl) = match original {
        Transaction::Standard(stx) => {
            let used: BTreeSet<u16> = stx.intents.keys().collect();
            let ttl = used
                .first()
                .and_then(|s| stx.intents.get(s))
                .map_or(fallback_ttl, |intent| intent.ttl);
            (used, ttl)
        }
        Transaction::ClaimRewards(_) => (BTreeSet::new(), fallback_ttl),
    };
    let segment = find_available_segment_id(&used).ok_or_else(|| {
        WalletError::SigningFailed("no free segment for the unshielded balancing intent".to_owned())
    })?;
    let offer = merge_into_offer(None, &recipe, keys.night_verifying_key)?;
    let intent: Intent<Signature, _, PedersenRandomness, InMemoryDB> = Intent::new(
        &mut OsRng,
        Some(offer),
        None,
        vec![],
        vec![],
        vec![],
        None,
        ttl,
    );
    let intents: StorageHashMap<u16, _, InMemoryDB> = StorageHashMap::new().insert(segment, intent);
    Ok((
        Some(Transaction::from_intents(network.to_owned(), intents)),
        state,
    ))
}

/// Append the Dust fee leg for `base` submitted with `tokens_leg` when
/// `options.pay_fees` is set. The fee is priced on the two together,
/// and the leg takes a segment neither uses.
fn add_fee_leg<R, P, B>(
    rng: &mut R,
    facade: FacadeState,
    base: &Transaction<Signature, P, B, InMemoryDB>,
    tokens_leg: Option<UnprovenTransaction>,
    keys: &TransferSigningKeys<'_>,
    options: &TransferOptions,
) -> Result<(Option<UnprovenTransaction>, FacadeState)>
where
    R: Rng + CryptoRng,
    P: ProofKind<InMemoryDB>,
    B: Storable<InMemoryDB>
        + moonproof_ledger::ledger::structure::PedersenDowngradeable<InMemoryDB>
        + Serializable,
{
    if !options.pay_fees {
        return Ok((tokens_leg, facade));
    }
    let combined = match &tokens_leg {
        Some(leg) => base
            .erase_proofs()
            .merge(&leg.erase_proofs())
            .map_err(|e| {
                WalletError::Serialization(format!(
                    "size the balanced transaction for its fee: {e:?}"
                ))
            })?,
        None => base.erase_proofs(),
    };
    let (dust, fee_leg) = build_dust_balancing_tx(
        rng,
        facade.dust.clone(),
        keys.dust_secret_key,
        &combined,
        &fee_context(&facade, options),
    )?;
    let facade = facade.with_dust(dust);
    Ok((merge_unproven(tokens_leg, fee_leg)?, facade))
}

fn fee_context<'a>(facade: &'a FacadeState, options: &TransferOptions) -> FeeContext<'a> {
    FeeContext {
        current_time: options.current_time,
        ttl: options.ttl,
        network_id: facade.network_id().as_str(),
        ledger_parameters: facade.ledger_parameters(),
    }
}

fn merge_unproven(
    a: Option<UnprovenTransaction>,
    b: Option<UnprovenTransaction>,
) -> Result<Option<UnprovenTransaction>> {
    match (a, b) {
        (Some(a), Some(b)) => a
            .merge(&b)
            .map(Some)
            .map_err(|e| WalletError::Serialization(format!("merge balancing legs: {e:?}"))),
        (Some(x), None) | (None, Some(x)) => Ok(Some(x)),
        (None, None) => Ok(None),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::abstractions::NetworkId;
    use crate::dust::DustState;
    use crate::shielded::ShieldedState;
    use crate::types::TokenType;
    use crate::unshielded::ledger_adapter::{signing_key_from_bytes, NoopProvingProvider};
    use crate::unshielded::{UnshieldedUpdate, UnshieldedUtxo, UtxoId, UtxoMeta, UtxoWithMeta};
    use moonproof_ledger::base_crypto::time::Duration;
    use moonproof_ledger::coin_structure::coin::{
        Info as CoinInfo, Nonce, ShieldedTokenType, UnshieldedTokenType, UserAddress, NIGHT,
    };
    use moonproof_ledger::coin_structure::contract::ContractAddress;
    use moonproof_ledger::ledger::dust::{DustParameters, DustSecretKey};
    use moonproof_ledger::ledger::structure::{
        ProofMarker, ProofPreimageMarker, SignatureKind, UnshieldedOffer, UtxoOutput, UtxoSpend,
    };
    use moonproof_ledger::onchain_runtime::cost_model::INITIAL_COST_MODEL;
    use moonproof_ledger::signatures::{SigningKey, VerifyingKey};
    use moonproof_ledger::transient_crypto::hash::HashOutput;
    use moonproof_ledger::zswap::keys::{SecretKeys as ZswapSecretKeys, Seed as ZswapSeed};
    use moonproof_ledger::zswap::{Offer as ZswapOffer, Output as ZswapOutput};
    use rand::rngs::StdRng;
    use rand::SeedableRng;

    const NETWORK: &str = "undeployed";
    const TOKEN_T: [u8; 32] = [0x7A; 32];

    struct Keys {
        zswap: ZswapSecretKeys,
        dust: DustSecretKey,
        signing: SigningKey,
        verifying: VerifyingKey,
        owner: [u8; 32],
    }

    impl Keys {
        fn new(byte: u8) -> Self {
            let signing = signing_key_from_bytes(&[byte; 32]).unwrap();
            let verifying = signing.verifying_key();
            let owner = UserAddress::from(verifying.clone()).0 .0;
            Self {
                zswap: ZswapSecretKeys::from(ZswapSeed::from([byte; 32])),
                dust: DustSecretKey::derive_secret_key(&[byte; 32]),
                signing,
                verifying,
                owner,
            }
        }

        fn transfer(&self) -> TransferSigningKeys<'_> {
            TransferSigningKeys {
                shielded_secret_keys: &self.zswap,
                dust_secret_key: &self.dust,
                night_signing_key: &self.signing,
                night_verifying_key: &self.verifying,
                sender_owner: self.owner,
            }
        }
    }

    fn options(pay_fees: bool) -> TransferOptions {
        TransferOptions {
            ttl: Timestamp::from_secs(3_600),
            current_time: Timestamp::from_secs(0),
            pay_fees,
        }
    }

    fn shielded_token() -> ShieldedTokenType {
        ShieldedTokenType(HashOutput([0xAB; 32]))
    }

    fn token_t() -> UnshieldedTokenType {
        UnshieldedTokenType(HashOutput(TOKEN_T))
    }

    /// A facade for `keys` holding one shielded coin of `shielded`
    /// value (when non-zero) and the given `(token, value)` UTXOs.
    fn facade(keys: &Keys, shielded: u128, utxos: &[(&str, u128)]) -> FacadeState {
        let network = NetworkId::Undeployed;
        let mut local = moonproof_ledger::zswap::local::State::<InMemoryDB>::new();
        if shielded > 0 {
            let coin = CoinInfo {
                nonce: Nonce(HashOutput([0x55; 32])),
                type_: shielded_token(),
                value: shielded,
            };
            local = local.insert_coin(&keys.zswap, coin).unwrap();
        }
        let created: Vec<UtxoWithMeta> = utxos
            .iter()
            .enumerate()
            .map(|(i, (token, value))| {
                UtxoWithMeta::new(
                    UnshieldedUtxo::new(
                        UtxoId::new([0x10 + u8::try_from(i).unwrap(); 32], 0),
                        *value,
                        TokenType::new(*token),
                        keys.owner,
                    ),
                    UtxoMeta::new(0, false),
                )
            })
            .collect();
        let unshielded = crate::unshielded::UnshieldedState::empty()
            .apply_update(&UnshieldedUpdate::success(created, vec![]))
            .unwrap();
        let dust = DustState::init_empty(
            DustParameters {
                night_dust_ratio: 1_000,
                generation_decay_rate: 1,
                dust_grace_period: Duration::from_secs(60),
            },
            &keys.dust,
            network.clone(),
        );
        FacadeState::new(
            ShieldedState::init(local, &keys.zswap, network.clone()),
            unshielded,
            dust,
            network,
        )
    }

    fn offer(
        inputs: Vec<UtxoSpend>,
        outputs: Vec<UtxoOutput>,
    ) -> UnshieldedOffer<Signature, InMemoryDB> {
        UnshieldedOffer {
            inputs: inputs.into(),
            outputs: outputs.into(),
            signatures: Vec::<Signature>::new().into(),
        }
    }

    fn output(type_: UnshieldedTokenType, value: u128, owner: [u8; 32]) -> UtxoOutput {
        UtxoOutput {
            value,
            owner: UserAddress(HashOutput(owner)),
            type_,
        }
    }

    fn intent_tx(
        segment: u16,
        guaranteed: Option<UnshieldedOffer<Signature, InMemoryDB>>,
        fallible: Option<UnshieldedOffer<Signature, InMemoryDB>>,
    ) -> UnprovenTransaction {
        let intent: Intent<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB> =
            Intent::new(
                &mut StdRng::seed_from_u64(u64::from(segment)),
                guaranteed,
                fallible,
                vec![],
                vec![],
                vec![],
                None,
                Timestamp::from_secs(3_600),
            );
        Transaction::from_intents(NETWORK, StorageHashMap::new().insert(segment, intent))
    }

    /// A transaction whose guaranteed zswap offer pays `value` of the
    /// shielded token to a contract with no input: what Compact's
    /// `receiveShielded` leaves for the wallet to fund.
    fn shielded_deposit(rng: &mut StdRng, value: u128, segment: u16) -> UnprovenTransaction {
        let coin = CoinInfo {
            nonce: Nonce(HashOutput([0x77; 32])),
            type_: shielded_token(),
            value,
        };
        let contract = ContractAddress(moonproof_ledger::base_crypto::hash::HashOutput([0xCC; 32]));
        let out =
            ZswapOutput::<_, InMemoryDB>::new_contract_owned(rng, &coin, Some(segment), contract)
                .unwrap();
        let offer = ZswapOffer::<_, InMemoryDB>::new(Vec::new(), vec![out], Vec::new()).unwrap();
        if segment == 0 {
            Transaction::new(
                NETWORK,
                StorageHashMap::new(),
                Some(offer),
                StorageHashMap::new(),
            )
        } else {
            Transaction::new(
                NETWORK,
                StorageHashMap::new(),
                None,
                StorageHashMap::new().insert(segment, offer),
            )
        }
    }

    fn standard<S, P, B>(
        tx: &Transaction<S, P, B, InMemoryDB>,
    ) -> &StandardTransaction<S, P, B, InMemoryDB>
    where
        S: moonproof_ledger::ledger::structure::SignatureKind<InMemoryDB>,
        P: ProofKind<InMemoryDB>,
        B: Storable<InMemoryDB>,
    {
        match tx {
            Transaction::Standard(stx) => stx,
            Transaction::ClaimRewards(_) => panic!("standard transaction expected"),
        }
    }

    fn assert_balanced<P, B>(tx: &Transaction<Signature, P, B, InMemoryDB>)
    where
        P: ProofKind<InMemoryDB>,
        B: Storable<InMemoryDB>,
        Transaction<Signature, P, B, InMemoryDB>: Serializable,
    {
        let left: Vec<_> = imbalances_of(tx)
            .unwrap()
            .into_iter()
            .filter(|((token, _), value)| *value != 0 && *token != LedgerTokenType::Dust)
            .collect();
        assert!(left.is_empty(), "imbalances left: {left:?}");
    }

    /// Every unshielded input of the intent at `segment` carries a
    /// signature that verifies over the intent as it now stands.
    fn assert_signed<P, B>(tx: &Transaction<Signature, P, B, InMemoryDB>, segment: u16)
    where
        P: ProofKind<InMemoryDB>,
        B: Storable<InMemoryDB>
            + moonproof_ledger::ledger::structure::PedersenDowngradeable<InMemoryDB>
            + Serializable,
    {
        let intent = standard(tx).intents.get(&segment).expect("intent");
        let data = intent
            .erase_proofs()
            .erase_signatures()
            .data_to_sign(segment);
        for offer in [
            &intent.guaranteed_unshielded_offer,
            &intent.fallible_unshielded_offer,
        ]
        .into_iter()
        .flatten()
        {
            assert_eq!(offer.inputs.len(), offer.signatures.len());
            for (input, signature) in offer.inputs.iter().zip(offer.signatures.iter()) {
                assert!(
                    <Signature as SignatureKind<InMemoryDB>>::signature_verify::<()>(
                        &data,
                        input.owner.clone(),
                        &signature,
                    ),
                    "a signature does not verify"
                );
            }
            let inputs = Vec::from(&offer.inputs);
            let outputs = Vec::from(&offer.outputs);
            assert!(
                inputs.is_sorted() && outputs.is_sorted(),
                "offer out of order"
            );
        }
    }

    #[test]
    fn a_shielded_deficit_is_paid_from_the_wallet_in_the_guaranteed_offer() {
        let mut rng = StdRng::seed_from_u64(1);
        let keys = Keys::new(0x21);
        let tx = shielded_deposit(&mut rng, 1_000, 0);

        let (recipe, booked) = balance_unproven_transaction(
            &mut rng,
            facade(&keys, 1_500, &[]),
            tx,
            &keys.transfer(),
            &options(false),
        )
        .unwrap();

        assert_balanced(&recipe.transaction);
        let offer = standard(&recipe.transaction)
            .guaranteed_coins
            .as_ref()
            .expect("guaranteed offer");
        assert_eq!(offer.inputs.len(), 1, "the wallet's coin");
        assert_eq!(
            offer.outputs.len(),
            2,
            "the contract's output and the change"
        );
        assert_eq!(booked.shielded.local().pending_spends.size(), 1);
    }

    #[test]
    fn a_fallible_shielded_deficit_is_paid_in_its_own_segment() {
        let mut rng = StdRng::seed_from_u64(2);
        let keys = Keys::new(0x22);
        let tx = shielded_deposit(&mut rng, 400, 3);

        let (recipe, _) = balance_unproven_transaction(
            &mut rng,
            facade(&keys, 400, &[]),
            tx,
            &keys.transfer(),
            &options(false),
        )
        .unwrap();

        assert_balanced(&recipe.transaction);
        let stx = standard(&recipe.transaction);
        assert!(stx.guaranteed_coins.is_none());
        let fallible = stx.fallible_coins.get(&3).expect("segment 3 offer");
        assert_eq!(fallible.inputs.len(), 1);
    }

    #[test]
    fn an_unshielded_deficit_is_paid_inside_the_intent_that_carries_it() {
        let mut rng = StdRng::seed_from_u64(3);
        let keys = Keys::new(0x23);
        let tx = intent_tx(
            1,
            Some(offer(vec![], vec![output(NIGHT, 300, [0xBB; 32])])),
            None,
        );

        let (recipe, booked) = balance_unproven_transaction(
            &mut rng,
            facade(&keys, 0, &[("native", 1_000)]),
            tx,
            &keys.transfer(),
            &options(false),
        )
        .unwrap();

        assert_balanced(&recipe.transaction);
        let stx = standard(&recipe.transaction);
        assert_eq!(stx.intents.size(), 1, "no intent added");
        let intent = stx.intents.get(&1).unwrap();
        let guaranteed = intent.guaranteed_unshielded_offer.as_ref().unwrap();
        assert_eq!(guaranteed.inputs.len(), 1);
        assert_eq!(guaranteed.outputs.len(), 2, "the payment and the change");
        assert!(intent.dust_actions.is_none(), "payFees false pays no fee");
        assert_signed(&recipe.transaction, 1);
        assert_eq!(booked.unshielded.pending().len(), 1);
    }

    #[test]
    fn a_fallible_unshielded_deficit_is_paid_in_its_fallible_offer() {
        let mut rng = StdRng::seed_from_u64(4);
        let keys = Keys::new(0x24);
        let tx = intent_tx(
            2,
            None,
            Some(offer(vec![], vec![output(NIGHT, 300, [0xBB; 32])])),
        );

        let (recipe, _) = balance_unproven_transaction(
            &mut rng,
            facade(&keys, 0, &[("native", 300)]),
            tx,
            &keys.transfer(),
            &options(false),
        )
        .unwrap();

        assert_balanced(&recipe.transaction);
        let intent = standard(&recipe.transaction).intents.get(&2).unwrap();
        assert!(intent.guaranteed_unshielded_offer.is_none());
        let fallible = intent.fallible_unshielded_offer.as_ref().unwrap();
        assert_eq!(fallible.inputs.len(), 1);
        assert_eq!(fallible.outputs.len(), 1, "an exact coin leaves no change");
        assert_signed(&recipe.transaction, 2);
    }

    #[test]
    fn an_unshielded_surplus_is_collected_to_the_wallet() {
        let mut rng = StdRng::seed_from_u64(5);
        let keys = Keys::new(0x25);
        let spend = UtxoSpend {
            value: 500,
            owner: keys.verifying.clone(),
            type_: NIGHT,
            intent_hash: crate::unshielded::ledger_adapter::to_ledger_intent_hash([0x99; 32]),
            output_no: 0,
        };
        let tx = intent_tx(1, Some(offer(vec![spend], vec![])), None);

        let (recipe, _) = balance_unproven_transaction(
            &mut rng,
            facade(&keys, 0, &[]),
            tx,
            &keys.transfer(),
            &options(false),
        )
        .unwrap();

        assert_balanced(&recipe.transaction);
        let intent = standard(&recipe.transaction).intents.get(&1).unwrap();
        let outputs = Vec::from(&intent.guaranteed_unshielded_offer.as_ref().unwrap().outputs);
        assert_eq!(outputs, vec![output(NIGHT, 500, keys.owner)]);
        assert_signed(&recipe.transaction, 1);
    }

    #[test]
    fn paying_fees_without_dust_fails_rather_than_skipping_the_fee() {
        let mut rng = StdRng::seed_from_u64(6);
        let keys = Keys::new(0x26);
        let tx = intent_tx(
            1,
            Some(offer(vec![], vec![output(NIGHT, 300, [0xBB; 32])])),
            None,
        );

        let err = balance_unproven_transaction(
            &mut rng,
            facade(&keys, 0, &[("native", 1_000)]),
            tx,
            &keys.transfer(),
            &options(true),
        )
        .unwrap_err();
        assert!(
            matches!(err, WalletError::InsufficientFunds { .. }),
            "{err:?}"
        );
    }

    #[test]
    fn an_unbound_transaction_is_balanced_in_place_and_sealed() {
        let mut rng = StdRng::seed_from_u64(7);
        let keys = Keys::new(0x27);
        let unproven = intent_tx(
            1,
            Some(offer(vec![], vec![output(NIGHT, 300, [0xBB; 32])])),
            None,
        );
        let base: ProvenTransaction =
            futures::executor::block_on(unproven.prove(NoopProvingProvider, &INITIAL_COST_MODEL))
                .unwrap();

        let (recipe, _) = balance_unbound_recipe(
            &mut rng,
            facade(&keys, 0, &[("native", 1_000)]),
            base,
            &keys.transfer(),
            &options(false),
        )
        .unwrap();
        assert!(recipe.balancing.is_none(), "unshielded value needs no leg");
        assert_signed(&recipe.base, 1);

        let sealed = recipe.complete(None).unwrap();
        assert_balanced(&sealed);
        assert_signed(&sealed, 1);
    }

    /// The maker's sealed half of a swap: 100 NIGHT offered, 50 of
    /// token T wanted, signed by the maker at segment 1.
    fn sealed_swap_half(maker: &Keys) -> FinalizedTransaction {
        let spend = UtxoSpend {
            value: 100,
            owner: maker.verifying.clone(),
            type_: NIGHT,
            intent_hash: crate::unshielded::ledger_adapter::to_ledger_intent_hash([0x42; 32]),
            output_no: 0,
        };
        let unsigned = intent_tx(
            1,
            Some(offer(vec![spend], vec![output(token_t(), 50, maker.owner)])),
            None,
        );
        let signed =
            sign_unshielded_inputs(unsigned, &maker.signing, &mut StdRng::seed_from_u64(8))
                .unwrap();
        let proven: Transaction<Signature, ProofMarker, PedersenRandomness, InMemoryDB> =
            futures::executor::block_on(signed.prove(NoopProvingProvider, &INITIAL_COST_MODEL))
                .unwrap();
        proven.seal(StdRng::seed_from_u64(9))
    }

    #[test]
    fn a_sealed_swap_half_is_completed_by_a_new_intent() {
        let mut rng = StdRng::seed_from_u64(10);
        let maker = Keys::new(0x31);
        let taker = Keys::new(0x32);
        let original = sealed_swap_half(&maker);
        let t = hex::encode(TOKEN_T);

        let (recipe, booked) = balance_sealed_recipe(
            &mut rng,
            facade(&taker, 0, &[(t.as_str(), 80)]),
            original,
            &taker.transfer(),
            &options(false),
        )
        .unwrap();

        let leg = recipe.balancing.as_ref().expect("a balancing leg");
        let intent = standard(leg)
            .intents
            .get(&2)
            .expect("the first free segment");
        let guaranteed = intent.guaranteed_unshielded_offer.as_ref().unwrap();
        assert_eq!(guaranteed.inputs.len(), 1, "the taker's token T");
        let mut outputs = vec![
            output(NIGHT, 100, taker.owner),
            output(token_t(), 30, taker.owner),
        ];
        outputs.sort();
        assert_eq!(Vec::from(&guaranteed.outputs), outputs);
        assert_signed(leg, 2);
        assert_eq!(booked.unshielded.pending().len(), 1);

        let completed =
            futures::executor::block_on(finalize_sealed_recipe(recipe, NoopProvingProvider))
                .unwrap();
        assert_balanced(&completed);
        assert_signed(&completed, 1);
        assert_signed(&completed, 2);
    }

    #[test]
    fn a_sealed_fallible_unshielded_deficit_is_refused() {
        let maker = Keys::new(0x33);
        let unsigned = intent_tx(
            1,
            None,
            Some(offer(vec![], vec![output(NIGHT, 10, maker.owner)])),
        );
        let proven: Transaction<Signature, ProofMarker, PedersenRandomness, InMemoryDB> =
            futures::executor::block_on(unsigned.prove(NoopProvingProvider, &INITIAL_COST_MODEL))
                .unwrap();
        let original = proven.seal(StdRng::seed_from_u64(11));
        let taker = Keys::new(0x34);

        let err = balance_sealed_recipe(
            &mut StdRng::seed_from_u64(12),
            facade(&taker, 0, &[("native", 100)]),
            original,
            &taker.transfer(),
            &options(false),
        )
        .unwrap_err();
        assert!(matches!(err, WalletError::SigningFailed(_)), "{err:?}");
    }

    #[test]
    fn a_balanced_sealed_transaction_without_fees_is_left_alone() {
        let maker = Keys::new(0x35);
        let unsigned = intent_tx(1, None, None);
        let proven: Transaction<Signature, ProofMarker, PedersenRandomness, InMemoryDB> =
            futures::executor::block_on(unsigned.prove(NoopProvingProvider, &INITIAL_COST_MODEL))
                .unwrap();
        let original = proven.seal(StdRng::seed_from_u64(13));

        let (recipe, _) = balance_sealed_recipe(
            &mut StdRng::seed_from_u64(14),
            facade(&maker, 0, &[]),
            original.clone(),
            &maker.transfer(),
            &options(false),
        )
        .unwrap();
        assert!(recipe.balancing.is_none());
        let bytes = |tx: &FinalizedTransaction| {
            let mut out = Vec::new();
            moonproof_ledger::serialize::tagged_serialize(tx, &mut out).unwrap();
            out
        };
        assert_eq!(bytes(&recipe.complete(None).unwrap()), bytes(&original));
    }
}