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
//! Balance and coin-info read-only views over a [`DustState`].
//!
//! Port of `wallet-sdk-dust-wallet/CoinsAndBalances.ts`. All functions
//! here are pure projections — they do not mutate the state. Time enters
//! the API explicitly so callers can ask "what would the balance be at
//! time T?" without rolling the underlying [`DustLocalState::sync_time`].

use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::ledger::dust::{
    DustGenerationInfo, DustOutput, DustParameters, DustPublicKey, QualifiedDustOutput,
};

use crate::dust::state::DustState;

/// Snapshot of a dust UTXO's generation curve at a given moment.
///
/// `dtime` is `None` if the backing NIGHT UTXO has not been spent yet —
/// the dust is still actively generating (phase 1 or 2 of the curve).
/// Once `dtime` is set, decay has begun.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DustGenerationDetails {
    /// When the backing NIGHT UTXO was spent — `Some` iff decay has begun.
    pub dtime: Option<Timestamp>,
    /// Maximum value this UTXO can ever hold, in Specks: `gen.value * night_dust_ratio`.
    pub max_cap: u128,
    /// `ctime + time_to_cap`. Decay begins after this point if `dtime` hits first.
    pub max_cap_reached_at: Timestamp,
    /// Generated value at the queried time.
    pub generated_now: u128,
    /// Per-second generation/decay slope: `gen.value * generation_decay_rate`.
    pub rate: u128,
}

/// A dust UTXO together with its generation snapshot.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DustFullInfo {
    pub token: QualifiedDustOutput,
    pub details: DustGenerationDetails,
}

/// A NIGHT UTXO's "expected dust" projection — what dust generation would
/// look like if the UTXO were registered at its ctime. Used by callers
/// that want to pre-compute fee headroom for a registration transaction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UtxoWithDustEstimate<U> {
    pub utxo: U,
    pub dust: DustGenerationDetails,
}

/// A NIGHT UTXO carrying the wallet-side metadata required for dust
/// estimation: when it was created on chain (`ctime`) and whether the
/// wallet has already registered it for dust generation.
///
/// Mirrors TS `UtxoWithMeta` from the dust-wallet types module.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NightUtxoForDust {
    pub value: u128,
    pub ctime: Timestamp,
    pub registered_for_dust_generation: bool,
}

impl NightUtxoForDust {
    #[inline]
    #[must_use]
    pub const fn new(value: u128, ctime: Timestamp, registered_for_dust_generation: bool) -> Self {
        Self {
            value,
            ctime,
            registered_for_dust_generation,
        }
    }
}

/// Sum the wallet's dust balance evaluated at `time`. Available coins
/// only — pending spends are excluded. Mirrors TS `getWalletBalance`.
#[must_use]
pub fn wallet_balance(state: &DustState, time: Timestamp) -> u128 {
    state.local().wallet_balance(time)
}

/// Snapshot of every available dust coin (non-pending) at the given time
/// (or the local sync time if `time` is `None`). Order is the underlying
/// `dust_utxos` map's iteration order — deterministic across runs.
#[must_use]
pub fn available_coins(state: &DustState, time: Option<Timestamp>) -> Vec<DustFullInfo> {
    let now = resolve_time(state, time);
    available_dust_coins(state)
        .filter_map(|coin| build_full_info(state, coin, now))
        .collect()
}

/// Snapshot of every pending dust coin at the given time (or local sync
/// time if `time` is `None`). Pending coins are tracked locally between
/// submission and chain confirmation.
#[must_use]
pub fn pending_coins(state: &DustState, time: Option<Timestamp>) -> Vec<DustFullInfo> {
    let now = resolve_time(state, time);
    state
        .pending()
        .filter_map(|p| build_full_info(state, p.utxo, now))
        .collect()
}

/// Concatenation of [`available_coins`] then [`pending_coins`].
#[must_use]
pub fn total_coins(state: &DustState, time: Option<Timestamp>) -> Vec<DustFullInfo> {
    let now = resolve_time(state, time);
    let mut out = available_coins(state, Some(now));
    out.extend(pending_coins(state, Some(now)));
    out
}

/// Available coins paired with the *generated* dust value at `time` (the
/// figure callers care about for fee balancing). Mirrors TS
/// `getAvailableCoinsWithGeneratedDust`.
#[must_use]
pub fn available_coins_with_generated_dust(
    state: &DustState,
    time: Timestamp,
) -> Vec<(QualifiedDustOutput, u128)> {
    available_coins(state, Some(time))
        .into_iter()
        .map(|info| (info.token, info.details.generated_now))
        .collect()
}

/// Look up the [`DustGenerationInfo`] (the backing NIGHT's generation
/// curve) for a given dust coin. `None` if the backing NIGHT isn't
/// tracked locally — typically because the wallet hasn't synced past the
/// registration that produced it.
#[must_use]
pub fn generation_info(
    state: &DustState,
    coin: &QualifiedDustOutput,
) -> Option<DustGenerationInfo> {
    state.local().generation_info(coin)
}

/// "What if I registered these NIGHT UTXOs for dust generation?" —
/// projected dust details for each, as if they had backed dust generation
/// from their ctime. Used by the registration transaction builder to
/// figure out how much dust will be available to cover its own fees.
///
/// Mirrors TS `estimateDustGeneration`.
#[must_use]
pub fn estimate_dust_generation(
    state: &DustState,
    night_utxos: &[NightUtxoForDust],
    current_time: Timestamp,
) -> Vec<UtxoWithDustEstimate<NightUtxoForDust>> {
    let dust_pk = state.public_key();
    let params = state.parameters();
    night_utxos
        .iter()
        .map(|utxo| {
            let gen_info = fake_generation_info(*utxo, dust_pk);
            let fake_dust = fake_dust_token(dust_pk, *utxo);
            let details = build_details(&params, &gen_info, &fake_dust, current_time);
            UtxoWithDustEstimate {
                utxo: *utxo,
                dust: details,
            }
        })
        .collect()
}

/// Split NIGHT UTXOs (with their pre-computed dust estimates) into the
/// *guaranteed* and *fallible* sections of an unshielded offer. The
/// guaranteed section gets exactly one UTXO — the one with the highest
/// generated-dust value — so the registration's own fee can be paid
/// from it; everything else lands in the fallible section.
///
/// Mirrors TS `splitNightUtxos`.
#[must_use]
pub fn split_night_utxos<U: Clone>(
    utxos: &[UtxoWithDustEstimate<U>],
) -> (Vec<UtxoWithDustEstimate<U>>, Vec<UtxoWithDustEstimate<U>>) {
    let mut sorted: Vec<UtxoWithDustEstimate<U>> = utxos.to_vec();
    // Descending by generated_now: the highest-yielding UTXO goes first.
    sorted.sort_by_key(|u| std::cmp::Reverse(u.dust.generated_now));
    if sorted.is_empty() {
        return (Vec::new(), Vec::new());
    }
    let fallible = sorted.split_off(1);
    (sorted, fallible)
}

// --- Internal helpers --------------------------------------------------

/// Build the [`DustFullInfo`] for one coin at a given time, returning
/// `None` if its backing NIGHT generation info isn't tracked. Bridges
/// [`DustOutput::updated_value`] to the moonproof view.
fn build_full_info(
    state: &DustState,
    coin: QualifiedDustOutput,
    now: Timestamp,
) -> Option<DustFullInfo> {
    let gen_info = state.local().generation_info(&coin)?;
    let details = build_details(&state.local().params, &gen_info, &coin, now);
    Some(DustFullInfo {
        token: coin,
        details,
    })
}

/// Walk the available dust UTXOs (those without `pending_until` set in
/// the underlying [`DustLocalState`]). Coins our own `pending_dust` knows
/// about are filtered out — they've been submitted but not yet confirmed.
fn available_dust_coins(state: &DustState) -> impl Iterator<Item = QualifiedDustOutput> + '_ {
    let pending_nonces: indexmap::IndexSet<_> = state.pending().map(|p| p.utxo.nonce).collect();
    state
        .local()
        .utxos()
        .filter(move |coin| !pending_nonces.contains(&coin.nonce))
}

fn build_details<C: Into<DustOutput> + Copy>(
    params: &DustParameters,
    gen_info: &DustGenerationInfo,
    coin: &C,
    now: Timestamp,
) -> DustGenerationDetails {
    let coin_output: DustOutput = (*coin).into();
    let generated = coin_output.updated_value(gen_info, now, params);
    let rate = gen_info
        .value
        .saturating_mul(u128::from(params.generation_decay_rate));
    let max_cap = gen_info
        .value
        .saturating_mul(u128::from(params.night_dust_ratio));
    let max_cap_reached_at = coin_output.ctime + params.time_to_cap();
    DustGenerationDetails {
        dtime: option_dtime(gen_info),
        max_cap,
        max_cap_reached_at,
        generated_now: generated,
        rate,
    }
}

#[inline]
fn option_dtime(gen_info: &DustGenerationInfo) -> Option<Timestamp> {
    // "No dtime yet" is encoded two ways in our world:
    //
    // 1. `Timestamp::default()` (0) — a real on-chain generation info
    //    that hasn't observed a backing-NIGHT spend yet. Chain time is
    //    always > 0 at any usable point so this is unambiguous.
    // 2. `Timestamp::MAX` — the sentinel we use in `fake_generation_info`
    //    so the synthetic estimate stays in the generation phase.
    //
    // The TS reference uses `info.dtime` truthiness for case 1 only.
    if gen_info.dtime == Timestamp::default() || gen_info.dtime == Timestamp::MAX {
        None
    } else {
        Some(gen_info.dtime)
    }
}

#[inline]
fn resolve_time(state: &DustState, time: Option<Timestamp>) -> Timestamp {
    time.unwrap_or_else(|| state.sync_time())
}

/// Synthetic generation info used when projecting dust for an unregistered
/// NIGHT UTXO. The nonce is irrelevant for `DustOutput::updated_value`
/// (it only reads `value` and `dtime`), so we use the all-zero
/// `InitialNonce` as a sentinel — same trick the TS reference uses.
///
/// `dtime` MUST be set to a value far in the future (we use
/// [`Timestamp::MAX`]). The TS reference encodes "backing NIGHT not yet
/// spent" with `undefined` and the WASM `updatedValue` handles that as
/// "no decay phase". The Rust ledger uses `Timestamp::min(dtime, now)`
/// to compute the end of the generation phase — passing `Timestamp::MAX`
/// keeps the decay branch clamped out.
fn fake_generation_info(utxo: NightUtxoForDust, dust_pk: DustPublicKey) -> DustGenerationInfo {
    DustGenerationInfo {
        value: utxo.value,
        owner: dust_pk,
        nonce: moonproof_ledger::ledger::dust::InitialNonce(
            moonproof_ledger::base_crypto::hash::HashOutput([0; 32]),
        ),
        dtime: Timestamp::MAX,
    }
}

/// Synthetic dust output for the same purpose. `initial_value: 0` means
/// `updated_value` reports the "from-genesis" growth; `nonce` and `seq`
/// are placeholders.
fn fake_dust_token(dust_pk: DustPublicKey, utxo: NightUtxoForDust) -> DustOutput {
    use moonproof_ledger::transient_crypto::curve::Fr;
    DustOutput {
        initial_value: 0,
        owner: dust_pk,
        nonce: Fr::default(),
        seq: 0,
        ctime: utxo.ctime,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use moonproof_ledger::base_crypto::time::Duration;
    use moonproof_ledger::ledger::dust::{DustParameters, DustSecretKey};

    use crate::abstractions::NetworkId;
    use crate::dust::state::DustState;

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

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

    #[test]
    fn empty_state_has_zero_balance_and_no_coins() {
        let s = empty_state();
        assert_eq!(wallet_balance(&s, Timestamp::from_secs(100)), 0);
        assert_eq!(available_coins(&s, None), [] as [DustFullInfo; 0]);
        assert_eq!(pending_coins(&s, None), [] as [DustFullInfo; 0]);
        assert_eq!(total_coins(&s, None), [] as [DustFullInfo; 0]);
    }

    #[test]
    fn estimate_dust_generation_yields_one_entry_per_input() {
        let s = empty_state();
        let utxos = vec![
            NightUtxoForDust::new(50_000, Timestamp::from_secs(0), false),
            NightUtxoForDust::new(150_000, Timestamp::from_secs(0), false),
        ];
        let estimates = estimate_dust_generation(&s, &utxos, Timestamp::from_secs(60));
        assert_eq!(estimates.len(), 2);
        // Higher value => higher rate.
        assert!(estimates[1].dust.rate > estimates[0].dust.rate);
        // Higher value => higher max cap.
        assert!(estimates[1].dust.max_cap > estimates[0].dust.max_cap);
    }

    #[test]
    fn estimate_dust_generation_respects_time_to_cap() {
        let s = empty_state();
        let utxos = vec![NightUtxoForDust::new(1_000, Timestamp::from_secs(0), false)];
        // night_dust_ratio = 1000, generation_decay_rate = 1 → time_to_cap = 1000s
        // so generated_now after 1000s should equal max_cap.
        let est = estimate_dust_generation(&s, &utxos, Timestamp::from_secs(1_000));
        let expected_cap = 1_000u128 * 1_000u128;
        assert_eq!(est[0].dust.max_cap, expected_cap);
        assert_eq!(est[0].dust.generated_now, expected_cap);
    }

    #[test]
    fn split_night_utxos_puts_highest_in_guaranteed() {
        let utxos: Vec<UtxoWithDustEstimate<NightUtxoForDust>> = vec![
            UtxoWithDustEstimate {
                utxo: NightUtxoForDust::new(100, Timestamp::from_secs(0), false),
                dust: DustGenerationDetails {
                    dtime: None,
                    max_cap: 1_000,
                    max_cap_reached_at: Timestamp::from_secs(1_000),
                    generated_now: 100,
                    rate: 1,
                },
            },
            UtxoWithDustEstimate {
                utxo: NightUtxoForDust::new(500, Timestamp::from_secs(0), false),
                dust: DustGenerationDetails {
                    dtime: None,
                    max_cap: 5_000,
                    max_cap_reached_at: Timestamp::from_secs(5_000),
                    generated_now: 500,
                    rate: 5,
                },
            },
            UtxoWithDustEstimate {
                utxo: NightUtxoForDust::new(200, Timestamp::from_secs(0), false),
                dust: DustGenerationDetails {
                    dtime: None,
                    max_cap: 2_000,
                    max_cap_reached_at: Timestamp::from_secs(2_000),
                    generated_now: 200,
                    rate: 2,
                },
            },
        ];
        let (guaranteed, fallible) = split_night_utxos(&utxos);
        assert_eq!(guaranteed.len(), 1);
        assert_eq!(fallible.len(), 2);
        assert_eq!(guaranteed[0].utxo.value, 500); // highest generated_now
        assert_eq!(fallible[0].utxo.value, 200);
        assert_eq!(fallible[1].utxo.value, 100);
    }

    #[test]
    fn split_night_utxos_handles_empty_input() {
        let utxos: Vec<UtxoWithDustEstimate<NightUtxoForDust>> = Vec::new();
        let (guaranteed, fallible) = split_night_utxos(&utxos);
        assert_eq!(
            guaranteed,
            [] as [UtxoWithDustEstimate<NightUtxoForDust>; 0]
        );
        assert_eq!(fallible, [] as [UtxoWithDustEstimate<NightUtxoForDust>; 0]);
    }

    #[test]
    fn split_night_utxos_with_single_input_returns_only_guaranteed() {
        let one = UtxoWithDustEstimate {
            utxo: NightUtxoForDust::new(123, Timestamp::from_secs(0), false),
            dust: DustGenerationDetails {
                dtime: None,
                max_cap: 1_230,
                max_cap_reached_at: Timestamp::from_secs(1_230),
                generated_now: 7,
                rate: 1,
            },
        };
        let (guaranteed, fallible) = split_night_utxos(std::slice::from_ref(&one));
        assert_eq!(guaranteed.len(), 1);
        assert_eq!(fallible, [] as [UtxoWithDustEstimate<NightUtxoForDust>; 0]);
        assert_eq!(guaranteed[0].utxo.value, 123);
    }

    #[test]
    fn resolve_time_falls_back_to_sync_time_when_none() {
        let s = empty_state();
        // sync_time of an empty state defaults to Timestamp(0).
        assert_eq!(resolve_time(&s, None), Timestamp::default());
        let explicit = Timestamp::from_secs(99);
        assert_eq!(resolve_time(&s, Some(explicit)), explicit);
    }
}