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
//! Pure-logic recipe builders for dust transactions.
//!
//! Port of `wallet-sdk-dust-wallet/Transacting.ts`. Two distinct operations
//! land here:
//!
//! 1. **Dust generation**: register or deregister a NIGHT UTXO for dust
//!    auto-generation. Produces a [`DustGenerationRecipe`] whose night
//!    UTXOs are split into the guaranteed (1 max) and fallible sections,
//!    and one [`DustRegistrationSpec`] per registration in the action.
//! 2. **Fee balancing**: pick dust UTXOs whose generated value covers a
//!    transaction's fees. Produces a [`DustBalancingRecipe`] containing the
//!    selected dust coins (each annotated with the per-input fee draw) and
//!    the converged total fee. The recipe also tells the ledger adapter
//!    which `segment_id` the balancing intent should use to avoid
//!    colliding with intents already in the merged transaction set.
//!
//! Both surfaces are pure — no I/O, no clocks, no tx-shape construction.
//! That happens in [`crate::dust::ledger_adapter`].
//!
//! ## Why two layers
//!
//! The TS reference computes the balance recipe iteratively: it picks dust
//! coins to cover the *current* fee estimate, then re-estimates the fee
//! with those coins added, then picks again until the recipe covers the
//! latest estimate. Convergence is monotone (more inputs only ever
//! increases the fee, never decreases below covered) and bounded by the
//! number of available dust coins.
//!
//! In Rust we keep that loop here as a pure function and let the caller
//! supply a `fee_estimator: impl FnMut(&[CoinWithFee]) -> u128` closure
//! that wraps the actual ledger `fees_with_margin` call. That keeps this
//! module unit-testable without a live chain.

use std::collections::BTreeSet;

use indexmap::IndexSet;
use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::ledger::dust::QualifiedDustOutput;

use crate::dust::balances::{
    available_coins_with_generated_dust, estimate_dust_generation, split_night_utxos,
    NightUtxoForDust, UtxoWithDustEstimate,
};
use crate::dust::state::{CoinWithFee, DustState};
use crate::error::{Result, WalletError};
use crate::unshielded::UtxoWithMeta;

// --- Generation (register / deregister) -------------------------------

/// Per-registration spec for one NIGHT key. Mirrors the runtime shape of
/// a [`DustRegistration`](moonproof_ledger::ledger::dust::DustRegistration) before
/// signatures are filled in.
///
/// `dust_address` is `Some` for *register* (the wallet wants dust to
/// accrue against this NIGHT key, paid out to that dust address) and
/// `None` for *deregister*. `allow_fee_payment` is the maximum amount
/// of dust the registration is willing to advance to cover the
/// containing transaction's fee — typically the sum of `generated_now`
/// across the guaranteed-section UTXOs that aren't already registered.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DustRegistrationSpec {
    pub dust_address: Option<moonproof_ledger::ledger::dust::DustPublicKey>,
    pub allow_fee_payment: u128,
}

/// Output of [`build_dust_generation_recipe`].
///
/// - `guaranteed_inputs` / `fallible_inputs`: the NIGHT UTXOs split into
///   the unshielded offer's two sections. The guaranteed section gets
///   the single highest-yielding UTXO so the registration's own fee is
///   covered even if some fallible inputs are dropped. We hold the full
///   [`UtxoWithMeta`] (not just the dust projection) so the ledger
///   adapter can reconstruct each input's `UtxoSpend` (`intent_hash`,
///   `output_no`, owner) without going back to the wallet state.
/// - `*_change_value`: total NIGHT to send back to the spender as a
///   single output per non-empty section (a transfer-to-self of the
///   total input value).
/// - `registration`: the single dust registration / deregistration spec.
/// - `ctime`: timestamp to stamp on the produced [`DustActions`].
#[derive(Debug, Clone)]
pub struct DustGenerationRecipe {
    pub guaranteed_inputs: Vec<UtxoWithMeta>,
    pub fallible_inputs: Vec<UtxoWithMeta>,
    pub guaranteed_change_value: u128,
    pub fallible_change_value: u128,
    pub registration: DustRegistrationSpec,
    pub ctime: Timestamp,
}

impl DustGenerationRecipe {
    #[must_use]
    pub fn has_guaranteed(&self) -> bool {
        !self.guaranteed_inputs.is_empty()
    }
    #[must_use]
    pub fn has_fallible(&self) -> bool {
        !self.fallible_inputs.is_empty()
    }
    #[must_use]
    pub fn total_inputs(&self) -> usize {
        self.guaranteed_inputs.len() + self.fallible_inputs.len()
    }
}

/// Build a [`DustGenerationRecipe`] for registering or deregistering the
/// supplied NIGHT UTXOs against the wallet's dust public key.
///
/// `dust_receiver` is `Some(dust_pk)` to register and `None` to
/// deregister. The reference distinguishes these two modes only by:
///
/// 1. Whether `dust_address` is set on the registration.
/// 2. Whether `allow_fee_payment` is non-zero (only meaningful for
///    register — deregister passes 0 because the wallet must pay fees
///    from already-accrued dust separately).
///
/// `night_utxos` are the wallet's available NIGHT UTXOs the caller wants
/// to register. Internally we split them by *dust yield* (the highest
/// goes into the guaranteed section) and stash the *full* `UtxoWithMeta`
/// in each section so the ledger adapter has the intent-hash / output-no
/// fields needed to construct each `UtxoSpend`.
///
/// Empty `night_utxos` produces an "address-only" registration recipe —
/// no NIGHT inputs at all, just a `DustActions::registrations` entry.
/// The TS reference uses this for pure deregistration.
///
/// # Errors
///
/// Currently always returns `Ok`. The signature returns `Result` so the
/// surface stays open for future validation (e.g. enforcing that all
/// inputs share the same owner).
pub fn build_dust_generation_recipe(
    state: &DustState,
    night_utxos: &[UtxoWithMeta],
    dust_receiver: Option<moonproof_ledger::ledger::dust::DustPublicKey>,
    current_time: Timestamp,
) -> Result<DustGenerationRecipe> {
    if night_utxos.is_empty() {
        // A pure deregister-the-address-only call: produces a registration
        // with `dust_address = None` and no inputs. The TS reference
        // notes this in its docstring on `deregisterNightTokens`.
        return Ok(DustGenerationRecipe {
            guaranteed_inputs: Vec::new(),
            fallible_inputs: Vec::new(),
            guaranteed_change_value: 0,
            fallible_change_value: 0,
            registration: DustRegistrationSpec {
                dust_address: dust_receiver,
                allow_fee_payment: 0,
            },
            ctime: current_time,
        });
    }

    // Pair each full UtxoWithMeta with its dust projection so we can sort
    // by yield while keeping the original UTXO available for the recipe.
    let projections: Vec<NightUtxoForDust> = night_utxos.iter().map(utxo_to_dust_view).collect();
    let estimates: Vec<UtxoWithDustEstimate<usize>> =
        estimate_dust_generation(state, &projections, current_time)
            .into_iter()
            .enumerate()
            .map(|(i, e)| UtxoWithDustEstimate {
                utxo: i,
                dust: e.dust,
            })
            .collect();
    let (guaranteed_estimates, fallible_estimates) = split_night_utxos(&estimates);

    let guaranteed_inputs: Vec<UtxoWithMeta> = guaranteed_estimates
        .iter()
        .map(|e| night_utxos[e.utxo].clone())
        .collect();
    let fallible_inputs: Vec<UtxoWithMeta> = fallible_estimates
        .iter()
        .map(|e| night_utxos[e.utxo].clone())
        .collect();

    let guaranteed_change_value: u128 = guaranteed_inputs.iter().map(|u| u.utxo.value).sum();
    let fallible_change_value: u128 = fallible_inputs.iter().map(|u| u.utxo.value).sum();

    // `allow_fee_payment` is only meaningful for register (Some). For
    // deregister we pass 0 because the wallet must already have spendable
    // dust to cover the deregistration tx's fees.
    let allow_fee_payment = if dust_receiver.is_some() {
        sum_unregistered_generated_dust(&guaranteed_estimates, night_utxos)
    } else {
        0
    };

    Ok(DustGenerationRecipe {
        guaranteed_inputs,
        fallible_inputs,
        guaranteed_change_value,
        fallible_change_value,
        registration: DustRegistrationSpec {
            dust_address: dust_receiver,
            allow_fee_payment,
        },
        ctime: current_time,
    })
}

/// Lift a wallet [`UtxoWithMeta`] into the dust-only projection used for
/// generation estimates.
fn utxo_to_dust_view(utxo: &UtxoWithMeta) -> NightUtxoForDust {
    // `meta.ctime` is i64 (seconds since epoch); the dust ledger uses
    // u64 seconds. Negative values would mean "before genesis" which is
    // impossible — clamp at 0 defensively rather than panicking.
    let ctime = u64::try_from(utxo.meta.ctime).unwrap_or(0);
    NightUtxoForDust::new(
        utxo.utxo.value,
        Timestamp::from_secs(ctime),
        utxo.meta.registered_for_dust_generation,
    )
}

/// Sum `generated_now` across guaranteed-section estimates whose backing
/// UTXO is *not* yet registered. The TS reference uses this to decide
/// how much fee advancement the registration can authorize — if the UTXO
/// is already registered, its dust accrues normally and shouldn't be
/// double-counted toward fees.
fn sum_unregistered_generated_dust(
    estimates: &[UtxoWithDustEstimate<usize>],
    night_utxos: &[UtxoWithMeta],
) -> u128 {
    estimates
        .iter()
        .filter(|e| !night_utxos[e.utxo].meta.registered_for_dust_generation)
        .map(|e| e.dust.generated_now)
        .sum()
}

/// When the dust a first-time registration may pay its fee from will
/// cover that fee. Mirrors midnight-wallet's `FeeCoverageEstimate`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FeeCoverageEstimate {
    /// Some unregistered `UTxO`'s generated dust covers the fee `seconds`
    /// after the estimate was made, at `at`; `0` when it already does.
    Reachable { seconds: u64, at: Timestamp },
    /// No unregistered `UTxO` generates dust, so waiting will not help.
    NoGeneration,
    /// Every generating `UTxO`'s cap is below the fee.
    ExceedsCap,
}

/// Estimate when one unregistered `UTxO`'s generated dust reaches `fee`,
/// counting a `UTxO` whose creation time is still ahead of `now` from
/// then.
#[must_use]
pub fn fee_coverage_estimate(
    state: &DustState,
    night_utxos: &[UtxoWithMeta],
    fee: u128,
    now: Timestamp,
) -> FeeCoverageEstimate {
    let views: Vec<NightUtxoForDust> = night_utxos.iter().map(utxo_to_dust_view).collect();
    let claimable: Vec<_> = estimate_dust_generation(state, &views, now)
        .into_iter()
        .filter(|e| !e.utxo.registered_for_dust_generation)
        .collect();
    if fee == 0 || claimable.iter().any(|e| e.dust.generated_now >= fee) {
        return FeeCoverageEstimate::Reachable {
            seconds: 0,
            at: now,
        };
    }
    let generating: Vec<_> = claimable.iter().filter(|e| e.dust.rate > 0).collect();
    if generating.is_empty() {
        return FeeCoverageEstimate::NoGeneration;
    }
    let seconds = generating
        .iter()
        .filter(|e| e.dust.max_cap >= fee)
        .map(|e| {
            let until_created = e.utxo.ctime.to_secs().saturating_sub(now.to_secs());
            let to_generate = (fee - e.dust.generated_now).div_ceil(e.dust.rate);
            u128::from(until_created).saturating_add(to_generate)
        })
        .min();
    match seconds {
        Some(s) => {
            let seconds = u64::try_from(s).unwrap_or(u64::MAX);
            FeeCoverageEstimate::Reachable {
                seconds,
                at: Timestamp::from_secs(now.to_secs().saturating_add(seconds)),
            }
        }
        None => FeeCoverageEstimate::ExceedsCap,
    }
}

// --- Fee balancing -----------------------------------------------------

/// Output of [`compute_fee_balancing_recipe`].
///
/// - `inputs`: dust coins (with per-input fee draw) to spend in the
///   balancing intent. Empty iff the existing transactions already
///   balance dust (rare).
/// - `total_fee`: the converged fee in dust specks.
#[derive(Debug, Clone)]
pub struct DustBalancingRecipe {
    pub inputs: Vec<CoinWithFee>,
    pub total_fee: u128,
}

/// Find the minimum-set of dust coins whose accrued value covers the fee
/// of the existing-tx-set + a new balancing intent that spends them.
/// Iterative: pick a candidate set, ask the supplied `fee_estimator` for
/// the resulting fee, repeat until the picked set covers it.
///
/// This is a pure-logic port of TS `computeBalancingRecipe`. The fee
/// estimator is injected so callers can plug in either the real
/// `Transaction::fees_with_margin` (production) or a stub (unit tests).
///
/// `initial_fee` is the fee of the un-balanced transaction set (the TS
/// reference computes this with `feeImbalance` per existing tx). Pass
/// `0` if the existing set is already perfectly balanced apart from the
/// dust deficit.
///
/// # Errors
///
/// - [`WalletError::InsufficientFunds`] if available dust never covers
///   the fee.
/// - [`WalletError::Dust`] for any other error from the estimator.
pub fn compute_fee_balancing_recipe(
    state: &DustState,
    initial_fee: u128,
    current_time: Timestamp,
    mut fee_estimator: impl FnMut(&[CoinWithFee]) -> Result<u128>,
) -> Result<DustBalancingRecipe> {
    let available = available_coins_with_generated_dust(state, current_time);
    if available.is_empty() && initial_fee > 0 {
        return Err(WalletError::InsufficientFunds {
            token: "dust".to_owned(),
        });
    }

    let mut current_fee = initial_fee;

    // Convergence loop: pick coins covering current_fee, estimate the new
    // fee with those coins, repeat until the new fee ≤ what we cover.
    // A monotonic pessimistic upper bound — `available.len()` extra
    // iterations max — keeps this from running away.
    for _ in 0..=(available.len() + 1) {
        let picked = pick_dust_coins(&available, current_fee)?;
        let new_fee = fee_estimator(&picked)?;
        let coverage: u128 = picked.iter().map(|c| c.fee).sum();
        if new_fee <= coverage {
            let converged_inputs = distribute_fee_across_inputs(picked, new_fee);
            return Ok(DustBalancingRecipe {
                inputs: converged_inputs,
                total_fee: new_fee,
            });
        }
        current_fee = new_fee;
    }

    // We escaped the loop without converging — the fee oscillated, which
    // shouldn't happen given the monotonic property. Surface as a clear
    // error rather than spinning forever.
    Err(WalletError::Dust(format!(
        "fee balancing did not converge after {} iterations (current fee {})",
        available.len() + 2,
        current_fee
    )))
}

/// Pick the fewest dust coins whose summed `generated_now` covers
/// `target`. Each picked coin contributes its full generated value;
/// the per-coin draw distribution happens later in
/// [`distribute_fee_across_inputs`].
///
/// Strategy (Ledger 9 `OutsideTimeToDismiss`-safe):
/// 1. Skip zero-`generated_now` coins (mirrors midnight-wallet PR #383).
/// 2. If any single coin covers `target`, pick the **smallest** such
///    coin (1 `DustSpend` proof, minimal locked change).
/// 3. Otherwise sort **largest-first** so we minimize the number of
///    `DustSpend` proofs in `cost_to_dismiss`.
///
/// Pure function — no `DustState` required.
fn pick_dust_coins(
    available: &[(QualifiedDustOutput, u128)],
    target: u128,
) -> Result<Vec<CoinWithFee>> {
    if target == 0 {
        return Ok(Vec::new());
    }
    let mut non_zero: Vec<(QualifiedDustOutput, u128)> = available
        .iter()
        .filter(|(_, value)| *value > 0)
        .copied()
        .collect();

    // Best case: a single coin covers the whole fee — pick the smallest
    // covering coin so we pay with 1 DustSpend proof and keep larger
    // coins intact.
    if let Some((utxo, generated_value)) = non_zero
        .iter()
        .copied()
        .filter(|(_, value)| *value >= target)
        .min_by_key(|(_, value)| *value)
    {
        return Ok(vec![CoinWithFee::new(utxo, generated_value)]);
    }

    // No single coin covers `target`: sort largest-first to minimize
    // the count of DustSpend proofs (Ledger 9 enforces a tight
    // `time_to_dismiss` budget per transaction byte).
    non_zero.sort_by_key(|a| std::cmp::Reverse(a.1));

    let mut covered: u128 = 0;
    let mut picked = Vec::new();
    for (utxo, generated_value) in &non_zero {
        if covered >= target {
            break;
        }
        // We provisionally take the full generated value of each picked
        // coin; the actual per-input fee draw is reset by
        // distribute_fee_across_inputs once the converged fee is known.
        picked.push(CoinWithFee::new(*utxo, *generated_value));
        covered = covered.saturating_add(*generated_value);
    }

    if covered < target {
        return Err(WalletError::InsufficientFunds {
            token: "dust".to_owned(),
        });
    }
    Ok(picked)
}

/// Re-distribute a fixed total fee across the picked inputs by draining
/// each input's value in order until the fee is satisfied. Mirrors TS
/// `distributeFeeAcrossInputs`. Order matters — the iteration order of
/// `inputs` is preserved so the per-input draw is deterministic.
fn distribute_fee_across_inputs(inputs: Vec<CoinWithFee>, fee: u128) -> Vec<CoinWithFee> {
    let mut remaining = fee;
    let mut out = Vec::with_capacity(inputs.len());
    for c in inputs {
        let deduction = remaining.min(c.fee);
        out.push(CoinWithFee::new(c.utxo, deduction));
        remaining = remaining.saturating_sub(deduction);
    }
    out
}

// --- Segment-id selection ---------------------------------------------

/// Find the lowest unused segment id in `[1, 65_535]` for a dust-balancing
/// intent that's about to be merged into the supplied set of existing
/// segment ids. Segment 0 is reserved for the guaranteed section and is
/// never returned.
///
/// Mirrors TS `findAvailableSegmentId`.
#[must_use]
pub fn find_available_segment_id(used: &BTreeSet<u16>) -> Option<u16> {
    (1u16..=u16::MAX).find(|s| !used.contains(s))
}

/// Convenience over [`find_available_segment_id`] for the common case
/// where the caller has the used segment ids as an iterator.
#[must_use]
pub fn next_segment_id_after(used_segments: impl IntoIterator<Item = u16>) -> Option<u16> {
    let used: IndexSet<u16> = used_segments.into_iter().collect();
    (1u16..=u16::MAX).find(|s| !used.contains(s))
}

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

    mod fee_coverage {
        use super::*;
        use crate::abstractions::NetworkId;
        use crate::unshielded::{UnshieldedUtxo, UtxoId, UtxoMeta};
        use moonproof_ledger::base_crypto::time::Duration;
        use moonproof_ledger::ledger::dust::{DustParameters, DustSecretKey};

        fn state(night_dust_ratio: u64, generation_decay_rate: u32) -> DustState {
            DustState::init_empty(
                DustParameters {
                    night_dust_ratio,
                    generation_decay_rate,
                    dust_grace_period: Duration::from_secs(60),
                },
                &DustSecretKey::derive_secret_key(&[0x02u8; 32]),
                NetworkId::Undeployed,
            )
        }

        fn utxo(value: u128, ctime: i64, registered: bool) -> UtxoWithMeta {
            UtxoWithMeta::new(
                UnshieldedUtxo::new(
                    UtxoId::new([1; 32], 0),
                    value,
                    crate::TokenType::new("native"),
                    [0; 32],
                ),
                UtxoMeta::new(ctime, registered),
            )
        }

        #[test]
        fn seconds_until_one_utxo_covers_the_fee() {
            // 10 NIGHT units at rate 3 generate 30 Specks a second.
            let est = fee_coverage_estimate(
                &state(1_000, 3),
                &[utxo(10, 0, false)],
                100,
                Timestamp::from_secs(0),
            );
            assert_eq!(
                est,
                FeeCoverageEstimate::Reachable {
                    seconds: 4,
                    at: Timestamp::from_secs(4)
                }
            );
        }

        #[test]
        fn already_covered_is_zero_seconds() {
            let est = fee_coverage_estimate(
                &state(1_000, 3),
                &[utxo(10, 0, false)],
                100,
                Timestamp::from_secs(10),
            );
            assert!(matches!(
                est,
                FeeCoverageEstimate::Reachable { seconds: 0, .. }
            ));
        }

        #[test]
        fn a_cap_below_the_fee_is_unreachable() {
            let est = fee_coverage_estimate(
                &state(5, 3),
                &[utxo(10, 0, false)],
                100,
                Timestamp::from_secs(0),
            );
            assert_eq!(est, FeeCoverageEstimate::ExceedsCap);
        }

        #[test]
        fn registered_utxos_do_not_count() {
            let est = fee_coverage_estimate(
                &state(1_000, 3),
                &[utxo(10, 0, true)],
                100,
                Timestamp::from_secs(0),
            );
            assert_eq!(est, FeeCoverageEstimate::NoGeneration);
        }
    }
    use moonproof_ledger::base_crypto::time::{Duration, Timestamp};
    use moonproof_ledger::ledger::dust::{DustParameters, DustSecretKey};

    use crate::abstractions::NetworkId;

    fn params() -> DustParameters {
        DustParameters {
            night_dust_ratio: 1_000,
            generation_decay_rate: 1,
            dust_grace_period: Duration::from_secs(60),
        }
    }

    fn state() -> DustState {
        let sk = DustSecretKey::derive_secret_key(&[0x42u8; 32]);
        DustState::init_empty(params(), &sk, NetworkId::Undeployed)
    }

    /// Build a synthetic [`UtxoWithMeta`] with the value, ctime, and
    /// registration flag the recipe-builder needs. Other fields
    /// (`intent_hash`, `output_no`, owner) are placeholders — recipe shape
    /// tests don't exercise the ledger adapter.
    fn night_utxo(value: u128, ctime_secs: i64, registered: bool) -> UtxoWithMeta {
        use crate::types::TokenType;
        use crate::unshielded::{UnshieldedUtxo, UtxoId, UtxoMeta};
        // Distinct intent_hash per call so identity-by-id doesn't collide.
        // We use a lightweight per-call seed seeded from value+ctime; tests
        // don't depend on specific hash values, only uniqueness.
        let mut intent_hash = [0u8; 32];
        intent_hash[0] = (value & 0xff) as u8;
        intent_hash[1] = ((value >> 8) & 0xff) as u8;
        intent_hash[2] = ctime_secs.to_le_bytes()[0];
        UtxoWithMeta::new(
            UnshieldedUtxo::new(
                UtxoId::new(intent_hash, 0),
                value,
                TokenType::new("native"),
                [0u8; 32],
            ),
            UtxoMeta::new(ctime_secs, registered),
        )
    }

    // --- Dust generation recipe ---------------------------------------

    #[test]
    fn build_recipe_for_zero_utxos_yields_address_only_registration() {
        let s = state();
        let pk = s.public_key();
        let r = build_dust_generation_recipe(&s, &[], Some(pk), Timestamp::from_secs(10)).unwrap();
        assert_eq!(r.total_inputs(), 0);
        assert_eq!(r.registration.dust_address, Some(pk));
        assert_eq!(r.registration.allow_fee_payment, 0);
        assert_eq!(r.ctime, Timestamp::from_secs(10));
    }

    #[test]
    fn build_recipe_for_zero_utxos_deregister_clears_address() {
        let s = state();
        let r = build_dust_generation_recipe(&s, &[], None, Timestamp::from_secs(10)).unwrap();
        assert!(r.registration.dust_address.is_none());
        assert_eq!(r.registration.allow_fee_payment, 0);
    }

    #[test]
    fn build_recipe_puts_one_utxo_in_guaranteed() {
        let s = state();
        let utxos = vec![night_utxo(150_000, 0, false)];
        let r = build_dust_generation_recipe(
            &s,
            &utxos,
            Some(s.public_key()),
            Timestamp::from_secs(10),
        )
        .unwrap();
        assert_eq!(r.guaranteed_inputs.len(), 1);
        assert_eq!(r.fallible_inputs, [] as [UtxoWithMeta; 0]);
        assert_eq!(r.guaranteed_inputs[0].utxo.value, 150_000);
        assert_eq!(r.guaranteed_change_value, 150_000);
        assert_eq!(r.fallible_change_value, 0);
    }

    #[test]
    fn build_recipe_with_multiple_utxos_splits_one_to_guaranteed() {
        let s = state();
        let utxos = vec![
            night_utxo(100_000, 0, false),
            night_utxo(500_000, 0, false),
            night_utxo(200_000, 0, false),
        ];
        let r = build_dust_generation_recipe(
            &s,
            &utxos,
            Some(s.public_key()),
            Timestamp::from_secs(10),
        )
        .unwrap();
        // Highest value yields highest dust → guaranteed
        assert_eq!(r.guaranteed_inputs.len(), 1);
        assert_eq!(r.guaranteed_inputs[0].utxo.value, 500_000);
        assert_eq!(r.fallible_inputs.len(), 2);
        // Fallible change is the sum of fallible inputs.
        assert_eq!(r.fallible_change_value, 300_000);
        assert_eq!(r.guaranteed_change_value, 500_000);
    }

    #[test]
    fn build_recipe_register_sums_unregistered_for_fee_payment() {
        let s = state();
        let utxos = vec![night_utxo(100_000, 0, true), night_utxo(500_000, 0, false)];
        let r = build_dust_generation_recipe(
            &s,
            &utxos,
            Some(s.public_key()),
            Timestamp::from_secs(10),
        )
        .unwrap();
        // Guaranteed = 500_000 (higher) which is unregistered → contributes
        // its generated_now to allow_fee_payment.
        assert!(r.registration.allow_fee_payment > 0);
    }

    #[test]
    fn build_recipe_deregister_never_authorizes_fee_payment() {
        let s = state();
        let utxos = vec![night_utxo(500_000, 0, false)];
        let r = build_dust_generation_recipe(&s, &utxos, None, Timestamp::from_secs(10)).unwrap();
        assert_eq!(r.registration.allow_fee_payment, 0);
        assert!(r.registration.dust_address.is_none());
    }

    // --- Fee-balancing recipe -----------------------------------------

    #[test]
    fn balancing_with_zero_initial_fee_picks_no_inputs() {
        let s = state();
        let r = compute_fee_balancing_recipe(
            &s,
            0,
            Timestamp::from_secs(10),
            // Estimator is never asked.
            |_| Ok(0),
        )
        .unwrap();
        assert_eq!(r.inputs, [] as [CoinWithFee; 0]);
        assert_eq!(r.total_fee, 0);
    }

    #[test]
    fn balancing_with_no_dust_and_nonzero_fee_errors_insufficient() {
        let s = state();
        let err = compute_fee_balancing_recipe(&s, 100, Timestamp::from_secs(10), |_| Ok(100))
            .unwrap_err();
        assert!(matches!(err, WalletError::InsufficientFunds { .. }));
    }

    // --- Segment-id selection -----------------------------------------

    #[test]
    fn find_available_segment_skips_used_starting_at_one() {
        let mut used = BTreeSet::new();
        used.insert(1);
        used.insert(2);
        used.insert(4);
        assert_eq!(find_available_segment_id(&used), Some(3));
    }

    #[test]
    fn find_available_segment_returns_one_when_empty() {
        let used = BTreeSet::new();
        assert_eq!(find_available_segment_id(&used), Some(1));
    }

    #[test]
    fn next_segment_id_after_iter_finds_first_gap() {
        assert_eq!(next_segment_id_after([1u16, 2, 3, 5]), Some(4));
        assert_eq!(next_segment_id_after([2u16, 3, 4]), Some(1));
        assert_eq!(next_segment_id_after(std::iter::empty::<u16>()), Some(1));
    }

    // --- Distribute fee --------------------------------------------------

    #[test]
    fn distribute_fee_drains_first_input_fully_then_partial() {
        let inputs = vec![
            CoinWithFee::new(dummy_utxo(), 100),
            CoinWithFee::new(dummy_utxo(), 100),
            CoinWithFee::new(dummy_utxo(), 100),
        ];
        let dist = distribute_fee_across_inputs(inputs, 250);
        assert_eq!(dist[0].fee, 100);
        assert_eq!(dist[1].fee, 100);
        assert_eq!(dist[2].fee, 50);
        let total: u128 = dist.iter().map(|c| c.fee).sum();
        assert_eq!(total, 250);
    }

    #[test]
    fn distribute_fee_zero_yields_zero_per_input() {
        let inputs = vec![
            CoinWithFee::new(dummy_utxo(), 100),
            CoinWithFee::new(dummy_utxo(), 50),
        ];
        let dist = distribute_fee_across_inputs(inputs, 0);
        assert!(dist.iter().all(|c| c.fee == 0));
    }

    #[test]
    fn distribute_fee_does_not_overdraw_total_capacity() {
        let inputs = vec![
            CoinWithFee::new(dummy_utxo(), 50),
            CoinWithFee::new(dummy_utxo(), 50),
        ];
        // Fee larger than capacity: still drains the full capacity, no more.
        let dist = distribute_fee_across_inputs(inputs, 200);
        let total: u128 = dist.iter().map(|c| c.fee).sum();
        assert_eq!(total, 100);
    }

    #[test]
    fn pick_dust_coins_skips_zero_generated_now_coins() {
        // Mirrors midnight-wallet PR #383: a freshly-registered dust UTXO
        // with `generated_now == 0` must not be picked — it can't reduce
        // the deficit and would burn a convergence iteration.
        let available = vec![
            (dummy_utxo(), 0), // freshly-registered, no accrual yet
            (dummy_utxo(), 100),
            (dummy_utxo(), 200),
        ];
        let picked = pick_dust_coins(&available, 150).unwrap();
        let total: u128 = picked.iter().map(|c| c.fee).sum();
        assert!(total >= 150, "covers target");
        assert!(
            picked.iter().all(|c| c.fee > 0),
            "no zero-value coin in picked set",
        );
    }

    #[test]
    fn pick_dust_coins_insufficient_when_only_zero_value_coins() {
        // All zero-accrual coins: target > 0 must report InsufficientFunds
        // rather than returning a useless picked set.
        let available = vec![(dummy_utxo(), 0), (dummy_utxo(), 0)];
        let err = pick_dust_coins(&available, 1).unwrap_err();
        assert!(matches!(err, WalletError::InsufficientFunds { .. }));
    }

    #[test]
    fn pick_dust_coins_prefers_single_covering_coin_for_time_to_dismiss() {
        // Ledger 9 enforces tight time-to-dismiss per byte: prefer 1 coin
        // covering the target over summing multiple smaller coins.
        let available = vec![
            (dummy_utxo(), 50),
            (dummy_utxo(), 120),
            (dummy_utxo(), 200),
            (dummy_utxo(), 500),
        ];
        let picked = pick_dust_coins(&available, 150).unwrap();
        assert_eq!(picked.len(), 1);
        assert_eq!(picked[0].fee, 200);

        // When no single coin covers target, pick largest-first (fewest spends).
        let picked_multi = pick_dust_coins(&available, 650).unwrap();
        assert_eq!(picked_multi.len(), 2);
        assert_eq!(picked_multi[0].fee, 500);
        assert_eq!(picked_multi[1].fee, 200);
    }

    fn dummy_utxo() -> QualifiedDustOutput {
        use moonproof_ledger::base_crypto::hash::HashOutput;
        use moonproof_ledger::ledger::dust::{DustPublicKey, InitialNonce};
        use moonproof_ledger::transient_crypto::curve::Fr;
        QualifiedDustOutput {
            initial_value: 0,
            owner: DustPublicKey(Fr::default()),
            nonce: Fr::default(),
            seq: 0,
            ctime: Timestamp::default(),
            backing_night: InitialNonce(HashOutput([0; 32])),
            mt_index: 0,
        }
    }
}