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
//! Convert dust [`DustGenerationRecipe`] / [`DustBalancingRecipe`] values
//! into `moonproof_ledger::ledger` `Intent` / `DustActions` shapes.
//!
//! Two shapes are produced here:
//!
//! 1. [`build_dust_generation_intent`] — registers (or deregisters) a set
//!    of NIGHT UTXOs for dust generation. Mirrors TS
//!    `createDustGenerationTransaction`. Produces an Intent with:
//!    - `guaranteed_unshielded_offer` = a self-transfer of the guaranteed
//!      NIGHT inputs back to the spender.
//!    - `fallible_unshielded_offer` = same, for the fallible section.
//!    - `dust_actions` = `Some(DustActions { spends: [], registrations: [reg], ctime })`.
//! 2. [`build_dust_balancing_intent`] — pays a transaction's dust fee from
//!    accrued dust UTXOs. Mirrors TS `balanceTransactions`. Produces an
//!    Intent with only `dust_actions = Some(DustActions { spends, registrations: [], ctime })`.
//!
//! Both intents are produced in the **unsigned** form — the caller signs
//! them via [`sign_dust_intent`], which guards against the
//! `Intent::sign` length-truncation footgun (mirrors the unshielded
//! `sign_intent` pattern).
//!
//! ## Why no `NoopProvingProvider`
//!
//! Dust **registration** intents have no spends, so `DustActions::prove`
//! is a no-op (its `spends.iter().map(|s| s.prove(...))` collapses to an
//! empty list). [`finalize_dust_only_transaction`] therefore reuses the
//! unshielded `NoopProvingProvider` safely for registration-only flows.
//!
//! Dust **spends** require the real `midnight/dust/spend` ZK proof. We
//! expose [`finalize_with_proving_provider`] that takes a real
//! [`ProvingProvider`] (e.g. a proof-server client) for those cases. The
//! noop variant on a tx that contains spends will surface a clear error
//! at prove time.

use std::collections::BTreeSet;

use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::coin_structure::coin::{UserAddress, NIGHT};
use moonproof_ledger::ledger::dust::{DustActions, DustRegistration, DustSpend};
use moonproof_ledger::ledger::error::TransactionProvingError;
use moonproof_ledger::ledger::structure::{
    Intent, ProofMarker, ProofPreimageMarker, Transaction, UnshieldedOffer, UtxoOutput, UtxoSpend,
};
use moonproof_ledger::onchain_runtime::cost_model::INITIAL_COST_MODEL;
use moonproof_ledger::serialize::tagged_serialize;
use moonproof_ledger::signatures::{Signature, SigningKey, VerifyingKey};
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, PureGeneratorPedersen};
use rand::rngs::OsRng;
use rand::{CryptoRng, RngCore};

use crate::dust::transacting::{DustBalancingRecipe, DustGenerationRecipe};
use crate::error::{Result, WalletError};
use crate::unshielded::ledger_adapter::{to_ledger_intent_hash, NoopProvingProvider};

/// Concrete DB type used throughout the dust path. Same `InMemoryDB` the
/// rest of the moonproof wallet uses — no need for a per-call DB.
pub type Db = InMemoryDB;

/// Intent shape used throughout the dust path: signature-ready (`S = Signature`),
/// pre-prove (`P = ProofPreimageMarker`), pre-bind (`B = PedersenRandomness`).
pub type DustIntent = Intent<Signature, ProofPreimageMarker, PedersenRandomness, Db>;

/// Signed `Transaction` shape — output of [`build_dust_transaction`].
/// Pre-proof, pre-bind: signatures populated, proofs are still
/// preimages, binding is still randomness. Suitable as input to a
/// proof server but NOT directly to the node.
pub type SignedDustTransaction =
    Transaction<Signature, ProofPreimageMarker, PedersenRandomness, Db>;

/// Wire-format `Transaction` shape — what `pallet_midnight.send_mn_transaction`
/// accepts. Output of [`finalize_dust_only_transaction`] (or
/// [`finalize_with_proving_provider`] when spends are present).
pub type FinalizedDustTransaction = Transaction<Signature, ProofMarker, PureGeneratorPedersen, Db>;

// --- Intent: dust generation -----------------------------------------

/// Wrap a [`DustGenerationRecipe`] in an unsigned [`DustIntent`]. The
/// caller signs via [`sign_dust_intent`]; both the unshielded inputs
/// AND the dust registration get signed by the **NIGHT** signing key
/// (one key per input + one per registration), since the ledger's
/// `Intent::sign` requires `night_key == sk.verifying_key()` for both.
///
/// Returns `Ok(None)` if the recipe is empty (no inputs and no
/// registration `dust_address`) — there's nothing for the chain to do.
pub fn build_dust_generation_intent<R: RngCore + CryptoRng>(
    recipe: &DustGenerationRecipe,
    spender_verifying_key: &VerifyingKey,
    ttl: Timestamp,
    rng: &mut R,
) -> Result<Option<DustIntent>> {
    if recipe.guaranteed_inputs.is_empty()
        && recipe.fallible_inputs.is_empty()
        && recipe.registration.dust_address.is_none()
    {
        // Empty recipe = no chain effect. The TS reference returns the
        // recipe unchanged in this case; we return None so callers know
        // not to submit anything.
        return Ok(None);
    }

    let guaranteed_offer = build_self_transfer_offer(
        &recipe.guaranteed_inputs,
        recipe.guaranteed_change_value,
        spender_verifying_key,
    );
    let fallible_offer = build_self_transfer_offer(
        &recipe.fallible_inputs,
        recipe.fallible_change_value,
        spender_verifying_key,
    );

    let registration: DustRegistration<Signature, Db> = DustRegistration {
        night_key: spender_verifying_key.clone(),
        dust_address: recipe.registration.dust_address.map(Sp::new),
        allow_fee_payment: recipe.registration.allow_fee_payment,
        signature: None,
    };

    let dust_actions: DustActions<Signature, ProofPreimageMarker, Db> = DustActions {
        spends: Vec::<DustSpend<ProofPreimageMarker, Db>>::new().into(),
        registrations: vec![registration].into(),
        ctime: recipe.ctime,
    };

    let intent: DustIntent = Intent::new(
        rng,
        guaranteed_offer,
        fallible_offer,
        Vec::new(), // no contract calls
        Vec::new(), // no maintenance updates
        Vec::new(), // no contract deploys
        Some(dust_actions),
        ttl,
    );

    Ok(Some(intent))
}

/// Wrap a [`DustBalancingRecipe`] in an unsigned [`DustIntent`].
///
/// The intent contains *only* `dust_actions = Some(DustActions { spends,
/// registrations: [], ctime })`. No unshielded offer; no contract calls.
/// Designed to be merged into an existing transaction via
/// [`Transaction::merge`].
///
/// Returns `Ok(None)` if the recipe has no spends — nothing to balance.
pub fn build_dust_balancing_intent<R: RngCore + CryptoRng>(
    recipe: &DustBalancingRecipe,
    spends: Vec<DustSpend<ProofPreimageMarker, Db>>,
    ctime: Timestamp,
    ttl: Timestamp,
    rng: &mut R,
) -> Result<Option<DustIntent>> {
    if spends.is_empty() {
        let _ = recipe; // explicit empty-recipe path: nothing to do.
        return Ok(None);
    }
    let dust_actions: DustActions<Signature, ProofPreimageMarker, Db> = DustActions {
        spends: spends.into(),
        registrations: Vec::<DustRegistration<Signature, Db>>::new().into(),
        ctime,
    };
    let intent: DustIntent = Intent::new(
        rng,
        None, // no guaranteed offer
        None, // no fallible offer
        Vec::new(),
        Vec::new(),
        Vec::new(),
        Some(dust_actions),
        ttl,
    );
    Ok(Some(intent))
}

/// Sign an unsigned [`DustIntent`] in place, signing both the unshielded
/// offer inputs (if any) and the dust registrations (if any) with the
/// supplied NIGHT signing key.
///
/// This is the single-key shorthand that mirrors what the TS reference
/// does (`addDustGenerationSignature`) for the typical case where one
/// wallet owns both the inputs and the registration. If multiple keys
/// are needed (multi-owner sets), use [`sign_dust_intent_multi`].
///
/// # Footgun protection
///
/// `Intent::sign` internally `zip`s inputs and keys, silently truncating
/// to the shorter side. We pre-validate every section's input/registration
/// count against the keys count and error out before any chain interaction.
pub fn sign_dust_intent<R: RngCore + CryptoRng>(
    intent: DustIntent,
    segment_id: u16,
    night_signing_key: &SigningKey,
    rng: &mut R,
) -> Result<DustIntent> {
    let guaranteed_count = intent
        .guaranteed_unshielded_offer
        .as_ref()
        .map_or(0, |offer| offer.inputs.len());
    let fallible_count = intent
        .fallible_unshielded_offer
        .as_ref()
        .map_or(0, |offer| offer.inputs.len());
    let registration_count = intent
        .dust_actions
        .as_ref()
        .map_or(0, |da| da.registrations.len());

    let key = night_signing_key.clone();
    let guaranteed_keys = vec![key.clone(); guaranteed_count];
    let fallible_keys = vec![key.clone(); fallible_count];
    let registration_keys = vec![key; registration_count];

    sign_dust_intent_multi(
        intent,
        segment_id,
        &guaranteed_keys,
        &fallible_keys,
        &registration_keys,
        rng,
    )
}

/// Multi-key variant: caller supplies one key per guaranteed input, one
/// per fallible input, and one per registration. Same length-mismatch
/// guards as [`sign_dust_intent`].
pub fn sign_dust_intent_multi<R: RngCore + CryptoRng>(
    intent: DustIntent,
    segment_id: u16,
    guaranteed_signing_keys: &[SigningKey],
    fallible_signing_keys: &[SigningKey],
    dust_registration_signing_keys: &[SigningKey],
    rng: &mut R,
) -> Result<DustIntent> {
    let guaranteed_count = intent
        .guaranteed_unshielded_offer
        .as_ref()
        .map_or(0, |offer| offer.inputs.len());
    let fallible_count = intent
        .fallible_unshielded_offer
        .as_ref()
        .map_or(0, |offer| offer.inputs.len());
    let registration_count = intent
        .dust_actions
        .as_ref()
        .map_or(0, |da| da.registrations.len());

    if guaranteed_signing_keys.len() != guaranteed_count {
        return Err(WalletError::SigningFailed(format!(
            "guaranteed signing keys count ({}) does not match guaranteed input count ({})",
            guaranteed_signing_keys.len(),
            guaranteed_count
        )));
    }
    if fallible_signing_keys.len() != fallible_count {
        return Err(WalletError::SigningFailed(format!(
            "fallible signing keys count ({}) does not match fallible input count ({})",
            fallible_signing_keys.len(),
            fallible_count
        )));
    }
    if dust_registration_signing_keys.len() != registration_count {
        return Err(WalletError::SigningFailed(format!(
            "dust registration signing keys count ({}) does not match registration count ({})",
            dust_registration_signing_keys.len(),
            registration_count
        )));
    }

    intent
        .sign(
            rng,
            segment_id,
            guaranteed_signing_keys,
            fallible_signing_keys,
            dust_registration_signing_keys,
        )
        .map_err(|e| WalletError::SigningFailed(format!("Intent::sign: {e:?}")))
}

// --- Transaction assembly --------------------------------------------

/// Wrap a signed dust intent into a [`SignedDustTransaction`] under one
/// segment id. For multi-intent merging (e.g. balancing intent merged
/// with a transfer tx), use [`Transaction::merge`] after calling this.
#[must_use]
pub fn build_dust_transaction(
    intent: DustIntent,
    segment_id: u16,
    network_id: impl Into<String>,
) -> SignedDustTransaction {
    let mut intents: StorageHashMap<u16, DustIntent, Db> = StorageHashMap::new();
    intents = intents.insert(segment_id, intent);
    Transaction::from_intents(network_id, intents)
}

/// Serialize a [`SignedDustTransaction`] in the tagged form expected by a
/// proof server. NOT the form the node accepts — finalize first, then
/// serialize via [`serialize_finalized_dust_transaction`].
pub fn serialize_signed_dust_transaction(tx: &SignedDustTransaction) -> Result<Vec<u8>> {
    let mut bytes = Vec::with_capacity(2048);
    tagged_serialize(tx, &mut bytes)
        .map_err(|e| WalletError::Serialization(format!("tagged_serialize(signed): {e}")))?;
    Ok(bytes)
}

/// Upgrade a [`SignedDustTransaction`] that contains **no dust spends**
/// (registration-only, possibly with unshielded offers) into a
/// [`FinalizedDustTransaction`] using [`NoopProvingProvider`]. Dust
/// registrations don't carry proofs, only signatures, so no real prover
/// is needed — provided `spends.is_empty()` for every dust action.
///
/// # Errors
///
/// Returns [`WalletError::Serialization`] wrapping the underlying
/// proving error if the transaction contains anything that requires a
/// real prover (dust spends, contract calls, Zswap offers).
pub fn finalize_dust_only_transaction(
    tx: &SignedDustTransaction,
) -> Result<FinalizedDustTransaction> {
    let post_prove = futures::executor::block_on(
        tx.prove(NoopProvingProvider, &INITIAL_COST_MODEL),
    )
    .map_err(|e: TransactionProvingError<Db>| {
        WalletError::Serialization(format!(
            "finalize_dust_only_transaction: prove step failed — \
                 transaction must be registration-only (no spends, no contract \
                 calls, no Zswap offers); use finalize_with_proving_provider \
                 for spend-bearing transactions: {e:?}"
        ))
    })?;
    Ok(post_prove.seal(OsRng))
}

/// Upgrade a spend-bearing [`SignedDustTransaction`] into a
/// [`FinalizedDustTransaction`] using a caller-supplied real
/// [`ProvingProvider`]. The provider is invoked once per `DustSpend`.
///
/// Use this when the recipe contains [`DustBalancingRecipe::inputs`] —
/// real spends require the `midnight/dust/spend` ZK proof.
pub fn finalize_with_proving_provider<P>(
    tx: &SignedDustTransaction,
    prover: P,
) -> Result<FinalizedDustTransaction>
where
    P: moonproof_ledger::transient_crypto::proofs::ProvingProvider,
{
    let post_prove = futures::executor::block_on(tx.prove(prover, &INITIAL_COST_MODEL)).map_err(
        |e: TransactionProvingError<Db>| {
            WalletError::Serialization(format!(
                "finalize_with_proving_provider: prove step failed: {e:?}"
            ))
        },
    )?;
    Ok(post_prove.seal(OsRng))
}

/// Serialize a [`FinalizedDustTransaction`] in the byte form
/// `pallet_midnight.send_mn_transaction` accepts.
pub fn serialize_finalized_dust_transaction(tx: &FinalizedDustTransaction) -> Result<Vec<u8>> {
    let mut bytes = Vec::with_capacity(2048);
    tagged_serialize(tx, &mut bytes).map_err(|e| {
        WalletError::Serialization(format!("tagged_serialize(finalized dust): {e}"))
    })?;
    Ok(bytes)
}

// --- Helpers ---------------------------------------------------------

/// Build the unshielded "self-transfer" offer used by a registration:
/// take the input UTXOs, send them all back to the spender as a single
/// output. The chain re-creates them as fresh UTXOs at the segment's
/// `intent_hash`, which is what `apply_registration` inspects to walk the
/// (now-tracked) NIGHT for dust generation.
///
/// Returns `None` if `inputs` is empty — no offer needed.
fn build_self_transfer_offer(
    inputs: &[crate::unshielded::UtxoWithMeta],
    total_value: u128,
    spender_verifying_key: &VerifyingKey,
) -> Option<UnshieldedOffer<Signature, Db>> {
    if inputs.is_empty() {
        return None;
    }
    let utxo_spends: Vec<UtxoSpend> = inputs
        .iter()
        .map(|u| UtxoSpend {
            value: u.utxo.value,
            owner: spender_verifying_key.clone(),
            type_: NIGHT,
            intent_hash: to_ledger_intent_hash(u.utxo.id.intent_hash),
            output_no: u.utxo.id.output_no,
        })
        .collect();
    let output = UtxoOutput {
        value: total_value,
        owner: UserAddress::from(spender_verifying_key.clone()),
        type_: NIGHT,
    };
    Some(UnshieldedOffer {
        inputs: utxo_spends.into(),
        outputs: vec![output].into(),
        signatures: Vec::<Signature>::new().into(),
    })
}

/// Convenience: collect the segment ids in use across a transaction's
/// intent map. Use with [`crate::dust::transacting::find_available_segment_id`]
/// when picking a slot for a balancing intent.
#[must_use]
pub fn used_segment_ids<S, P, B>(tx: &Transaction<S, P, B, Db>) -> BTreeSet<u16>
where
    S: moonproof_ledger::ledger::structure::SignatureKind<Db>,
    P: moonproof_ledger::ledger::structure::ProofKind<Db>,
    B: moonproof_ledger::ledger::structure::BindingKind<S, P, Db> + Storable<Db>,
{
    match tx {
        Transaction::Standard(stx) => stx.intents.keys().collect(),
        Transaction::ClaimRewards(_) => BTreeSet::new(),
    }
}

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

    use crate::abstractions::NetworkId;
    use crate::dust::state::DustState;
    use crate::dust::transacting::{
        build_dust_generation_recipe, DustBalancingRecipe, DustRegistrationSpec,
    };
    use crate::types::TokenType;
    use crate::unshielded::ledger_adapter::signing_key_from_bytes;
    use crate::unshielded::{UnshieldedUtxo, UtxoId, UtxoMeta, UtxoWithMeta};

    fn dust_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(dust_params(), &sk, NetworkId::Undeployed)
    }

    fn signer() -> (SigningKey, VerifyingKey) {
        let sk = signing_key_from_bytes(&[0x77u8; 32]).expect("signing key");
        let vk = sk.verifying_key();
        (sk, vk)
    }

    fn night_utxo(intent_byte: u8, value: u128) -> UtxoWithMeta {
        UtxoWithMeta::new(
            UnshieldedUtxo::new(
                UtxoId::new([intent_byte; 32], 0),
                value,
                TokenType::new("native"),
                [0u8; 32],
            ),
            UtxoMeta::new(0, false),
        )
    }

    // --- build_dust_generation_intent ---------------------------------

    #[test]
    fn empty_recipe_yields_no_intent() {
        let mut rng = StdRng::seed_from_u64(42);
        let (_, vk) = signer();
        let r = crate::dust::transacting::DustGenerationRecipe {
            guaranteed_inputs: Vec::new(),
            fallible_inputs: Vec::new(),
            guaranteed_change_value: 0,
            fallible_change_value: 0,
            registration: DustRegistrationSpec {
                dust_address: None,
                allow_fee_payment: 0,
            },
            ctime: Timestamp::from_secs(10),
        };
        let intent =
            build_dust_generation_intent(&r, &vk, Timestamp::from_secs(20), &mut rng).unwrap();
        assert!(intent.is_none());
    }

    #[test]
    fn address_only_registration_yields_intent_without_offers() {
        let s = empty_state();
        let (_, vk) = signer();
        let mut rng = StdRng::seed_from_u64(42);
        let recipe =
            build_dust_generation_recipe(&s, &[], Some(s.public_key()), Timestamp::from_secs(10))
                .unwrap();
        let intent =
            build_dust_generation_intent(&recipe, &vk, Timestamp::from_secs(20), &mut rng).unwrap();
        let intent = intent.expect("address-only registration is a valid intent");
        assert!(intent.guaranteed_unshielded_offer.is_none());
        assert!(intent.fallible_unshielded_offer.is_none());
        let da = intent.dust_actions.expect("dust_actions populated");
        assert_eq!(da.registrations.len(), 1);
        assert_eq!(da.spends.len(), 0);
    }

    #[test]
    fn registration_with_one_utxo_puts_input_in_guaranteed() {
        let s = empty_state();
        let (_, vk) = signer();
        let mut rng = StdRng::seed_from_u64(42);
        let utxos = vec![night_utxo(0xAA, 150_000)];
        let recipe = build_dust_generation_recipe(
            &s,
            &utxos,
            Some(s.public_key()),
            Timestamp::from_secs(10),
        )
        .unwrap();
        let intent =
            build_dust_generation_intent(&recipe, &vk, Timestamp::from_secs(20), &mut rng).unwrap();
        let intent = intent.unwrap();
        let g = intent.guaranteed_unshielded_offer.unwrap();
        assert_eq!(g.inputs.len(), 1);
        assert_eq!(g.outputs.len(), 1);
        // Self-transfer: the single output sums all input values.
        let single_output = g.outputs.iter().next().unwrap().clone();
        assert_eq!(single_output.value, 150_000);
        assert!(intent.fallible_unshielded_offer.is_none());
    }

    #[test]
    fn registration_with_multiple_utxos_splits_into_guaranteed_and_fallible() {
        let s = empty_state();
        let (_, vk) = signer();
        let mut rng = StdRng::seed_from_u64(42);
        let utxos = vec![
            night_utxo(0xAA, 100_000),
            night_utxo(0xBB, 500_000),
            night_utxo(0xCC, 200_000),
        ];
        let recipe = build_dust_generation_recipe(
            &s,
            &utxos,
            Some(s.public_key()),
            Timestamp::from_secs(10),
        )
        .unwrap();
        let intent =
            build_dust_generation_intent(&recipe, &vk, Timestamp::from_secs(20), &mut rng).unwrap();
        let intent = intent.unwrap();
        let g = intent.guaranteed_unshielded_offer.unwrap();
        let f = intent.fallible_unshielded_offer.unwrap();
        assert_eq!(g.inputs.len(), 1, "guaranteed gets one (highest-yield)");
        assert_eq!(f.inputs.len(), 2, "fallible gets the rest");
        // Each section emits exactly one self-transfer output.
        assert_eq!(g.outputs.len(), 1);
        assert_eq!(f.outputs.len(), 1);
    }

    // --- sign_dust_intent guards --------------------------------------

    #[test]
    fn sign_dust_intent_signs_a_real_registration_intent() {
        let s = empty_state();
        let (sk, vk) = signer();
        let mut rng = StdRng::seed_from_u64(42);
        let utxos = vec![night_utxo(0xAA, 150_000)];
        let recipe = build_dust_generation_recipe(
            &s,
            &utxos,
            Some(s.public_key()),
            Timestamp::from_secs(10),
        )
        .unwrap();
        // For inputs to sign, the spender's verifying key MUST match the
        // owner field on the input UtxoSpend — we set it so above.
        let intent = build_dust_generation_intent(&recipe, &vk, Timestamp::from_secs(20), &mut rng)
            .unwrap()
            .unwrap();
        let signed = sign_dust_intent(intent, 1, &sk, &mut rng).expect("sign ok");
        assert!(
            signed
                .dust_actions
                .unwrap()
                .registrations
                .iter()
                .next()
                .unwrap()
                .signature
                .is_some(),
            "registration signature should be populated"
        );
    }

    #[test]
    fn sign_dust_intent_multi_rejects_mismatched_guaranteed_keys() {
        let s = empty_state();
        let (sk, vk) = signer();
        let mut rng = StdRng::seed_from_u64(42);
        let utxos = vec![night_utxo(0xAA, 150_000)];
        let recipe = build_dust_generation_recipe(
            &s,
            &utxos,
            Some(s.public_key()),
            Timestamp::from_secs(10),
        )
        .unwrap();
        let intent = build_dust_generation_intent(&recipe, &vk, Timestamp::from_secs(20), &mut rng)
            .unwrap()
            .unwrap();
        // 1 guaranteed input but we pass 0 keys.
        let err = sign_dust_intent_multi(intent, 1, &[], &[], std::slice::from_ref(&sk), &mut rng)
            .unwrap_err();
        assert!(matches!(err, WalletError::SigningFailed(_)));
    }

    #[test]
    fn sign_dust_intent_multi_rejects_mismatched_registration_keys() {
        let s = empty_state();
        let (_sk, vk) = signer();
        let mut rng = StdRng::seed_from_u64(42);
        let recipe =
            build_dust_generation_recipe(&s, &[], Some(s.public_key()), Timestamp::from_secs(10))
                .unwrap();
        let intent = build_dust_generation_intent(&recipe, &vk, Timestamp::from_secs(20), &mut rng)
            .unwrap()
            .unwrap();
        // 1 registration but 0 keys.
        let err = sign_dust_intent_multi(intent, 1, &[], &[], &[], &mut rng).unwrap_err();
        assert!(matches!(err, WalletError::SigningFailed(_)));
    }

    // --- balancing intent -------------------------------------------

    #[test]
    fn balancing_intent_with_no_spends_yields_none() {
        let mut rng = StdRng::seed_from_u64(42);
        let recipe = DustBalancingRecipe {
            inputs: Vec::new(),
            total_fee: 0,
        };
        let intent = build_dust_balancing_intent(
            &recipe,
            Vec::new(),
            Timestamp::from_secs(10),
            Timestamp::from_secs(20),
            &mut rng,
        )
        .unwrap();
        assert!(intent.is_none());
    }

    // --- finalize ---------------------------------------------------

    #[test]
    fn finalize_dust_only_address_registration_round_trips() {
        let s = empty_state();
        let (sk, vk) = signer();
        let mut rng = StdRng::seed_from_u64(42);
        let recipe =
            build_dust_generation_recipe(&s, &[], Some(s.public_key()), Timestamp::from_secs(10))
                .unwrap();
        let intent = build_dust_generation_intent(&recipe, &vk, Timestamp::from_secs(20), &mut rng)
            .unwrap()
            .unwrap();
        let signed = sign_dust_intent(intent, 1, &sk, &mut rng).unwrap();
        let tx = build_dust_transaction(signed, 1, "undeployed");
        // Address-only registration has no dust spends — Noop prover suffices.
        let finalized = finalize_dust_only_transaction(&tx).expect("finalize ok");
        let bytes = serialize_finalized_dust_transaction(&finalized).expect("serialize ok");
        assert!(
            !bytes.is_empty(),
            "finalized tx serializes to non-empty bytes"
        );
    }
}