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
//! Dust generation registration / deregistration recipe builders.
//!
//! Port of `WalletFacade.registerNightUtxosForDustGeneration` and
//! `WalletFacade.deregisterFromDustGeneration` from
//! `@midnight-ntwrk/wallet-sdk-facade/src/index.ts`.
//!
//! # What a registration does
//!
//! Registering a NIGHT UTXO for dust generation tells the chain to start
//! accruing DUST against that UTXO, credited to the wallet's dust
//! public key. The transaction wraps:
//!
//! - An unshielded "self-transfer" offer spending each NIGHT UTXO and
//!   re-emitting its value to the same owner (so the chain can re-stamp
//!   each UTXO at the registration's `intent_hash` — the registered
//!   identity).
//! - A [`DustActions`] intent carrying one
//!   [`DustRegistration`](moonproof_ledger::ledger::dust::DustRegistration) with
//!   `dust_address = Some(dust_pk)` and an `allow_fee_payment`
//!   authorization summed from the freshly-generated dust on the
//!   guaranteed-section UTXOs.
//!
//! # Deregistration
//!
//! The TS `deregisterFromDustGeneration` produces the same shape with
//! `dust_address = None`. Moonproof mirrors the shape. Deregister flows
//! typically still need dust to pay their own fee (the
//! `allow_fee_payment = 0` path), so the caller must have spendable
//! dust in the facade state when submitting a deregister tx.
//!
//! # HSM / external signing
//!
//! The TS facade accepts a `signDustRegistration(payload)` callback so
//! hardware wallets can sign the registration without exposing the
//! NIGHT signing key. This builder accepts the signing key directly — matching the existing pattern in
//! [`crate::dust::sign_dust_intent`]. HSM integration is a future
//! extension: split [`build_registration_recipe`] into a
//! "build-unsigned" + "attach-signatures" pair, with the unsigned form
//! exposing per-section signature payloads.

use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::ledger::dust::{DustPublicKey, DustSecretKey};
use moonproof_ledger::signatures::{SigningKey, VerifyingKey};
use rand::{CryptoRng, Rng};

use crate::dust::{
    build_dust_generation_intent, build_dust_generation_recipe, build_dust_transaction,
    fee_coverage_estimate, sign_dust_intent,
};
use crate::error::{Result, WalletError};
use crate::facade::state::FacadeState;
use crate::facade::transfer::{
    balance_dust_fee, estimate_unproven_fee, FeeContext, UnprovenTransactionRecipe,
    PRIMARY_SEGMENT_ID,
};
use crate::unshielded::UtxoWithMeta;

/// Unsigned registration recipe — the intent and segment are shaped but
/// the unshielded offer signatures haven't been attached yet. Analogous
/// to the TS facade's intermediate shape after
/// `createDustGenerationTransaction` but before
/// `addDustGenerationSignature`.
///
/// Kept as a separate type so a future HSM-friendly builder can expose
/// the signature payloads without exposing a raw `DustIntent`.
#[derive(Debug, Clone)]
pub struct UnsignedRegistrationRecipe {
    pub intent: crate::dust::DustIntent,
    pub segment_id: u16,
    pub ttl: Timestamp,
}

/// Signed registration recipe — ready to flow into
/// [`crate::facade::submission::finalize_recipe`]. Identical shape to
/// [`UnprovenTransactionRecipe`]; exposed as its own type so callers
/// can pattern-match on the origin of a recipe.
#[derive(Debug, Clone)]
pub struct SignedRegistrationRecipe {
    pub recipe: UnprovenTransactionRecipe,
}

/// Inputs to [`build_registration_recipe`] /
/// [`build_deregistration_recipe`]. Bundled so the function signatures
/// stay under clippy's `too_many_arguments` threshold.
///
/// All references live as long as the single synchronous call; the
/// builder doesn't retain them.
#[derive(Debug)]
pub struct RegistrationParams<'a> {
    pub night_signing_key: &'a SigningKey,
    pub night_verifying_key: &'a VerifyingKey,
    /// Dust spending key — required for deregistration (which carries
    /// `allow_fee_payment = 0`, so its fee must be paid from
    /// already-generated dust by balancing in a dust spend). `None` is
    /// allowed for registration, whose `allow_fee_payment` lets the
    /// newly-generated dust cover the fee. Building a deregistration with
    /// `None` is rejected rather than emitting a fee-less (overspending) tx.
    pub dust_secret_key: Option<&'a DustSecretKey>,
    pub ttl: Timestamp,
    pub current_time: Timestamp,
}

// --- Register --------------------------------------------------------

/// Build a signed registration recipe for `night_utxos`. Returns the
/// recipe plus the updated [`FacadeState`] (currently no state change —
/// the dust sub-wallet updates on chain-confirmed registration, not at
/// recipe-build time).
///
/// ## Errors
///
/// - [`WalletError::Dust`] if `night_utxos` is empty — registering zero
///   UTXOs under the caller's dust address is a no-op. TS matches via
///   `At least one Night UTXO is required`.
/// - Any error from
///   [`build_dust_generation_intent`] / [`sign_dust_intent`].
pub fn build_registration_recipe<R>(
    rng: &mut R,
    state: FacadeState,
    night_utxos: &[UtxoWithMeta],
    dust_receiver: DustPublicKey,
    params: &RegistrationParams<'_>,
) -> Result<(SignedRegistrationRecipe, FacadeState)>
where
    R: Rng + CryptoRng,
{
    if night_utxos.is_empty() {
        return Err(WalletError::Dust(
            "registration recipe requires at least one Night UTXO".to_owned(),
        ));
    }
    build_registration_recipe_inner(rng, state, night_utxos, Some(dust_receiver), params)
}

/// Build a signed deregistration recipe for `night_utxos`. Empty
/// `night_utxos` is allowed here — matches the TS reference's
/// "address-only deregistration" flow where the caller's goal is just
/// to clear the wallet's dust address from the chain's records.
///
/// ## Errors
///
/// Any error from [`build_dust_generation_intent`] /
/// [`sign_dust_intent`].
pub fn build_deregistration_recipe<R>(
    rng: &mut R,
    state: FacadeState,
    night_utxos: &[UtxoWithMeta],
    params: &RegistrationParams<'_>,
) -> Result<(SignedRegistrationRecipe, FacadeState)>
where
    R: Rng + CryptoRng,
{
    build_registration_recipe_inner(rng, state, night_utxos, None, params)
}

fn build_registration_recipe_inner<R>(
    rng: &mut R,
    state: FacadeState,
    night_utxos: &[UtxoWithMeta],
    dust_receiver: Option<DustPublicKey>,
    params: &RegistrationParams<'_>,
) -> Result<(SignedRegistrationRecipe, FacadeState)>
where
    R: Rng + CryptoRng,
{
    let network_label = state.network_id().as_str().to_owned();
    let dust_state = state.dust.clone();

    let recipe =
        build_dust_generation_recipe(&dust_state, night_utxos, dust_receiver, params.current_time)?;

    let intent_opt =
        build_dust_generation_intent(&recipe, params.night_verifying_key, params.ttl, rng)?;
    let Some(unsigned_intent) = intent_opt else {
        // The recipe-builder returns `None` only when inputs are empty
        // AND dust_receiver is None (pure address-only deregister with
        // no registration change needed). The TS reference handles this
        // silently by short-circuiting; we surface an error to keep the
        // flow explicit.
        return Err(WalletError::Dust(
            "registration recipe would produce no on-chain effect; refusing to build an empty tx"
                .to_owned(),
        ));
    };

    let signed_intent = sign_dust_intent(
        unsigned_intent,
        PRIMARY_SEGMENT_ID,
        params.night_signing_key,
        rng,
    )?;
    let tx = build_dust_transaction(signed_intent, PRIMARY_SEGMENT_ID, network_label.clone());

    // A first-time registration pays its fee from the dust its NIGHT has
    // generated so far (`allow_fee_payment`). Below the fee the node
    // rejects it as BalanceCheckOverspend, so refuse it here, before
    // anything is booked, with an estimate of when it will be covered.
    // A re-registration carries no fee payment and is balanced
    // externally. NIGHT carried across the ledger 8 -> 9 fork arrives
    // unregistered, since the fork reset dust generation, so it counts
    // as first-time.
    if dust_receiver.is_some()
        && recipe
            .guaranteed_inputs
            .iter()
            .any(|u| !u.meta.registered_for_dust_generation)
    {
        let fee = estimate_unproven_fee(&tx, state.ledger_parameters());
        let fee_payment = recipe.registration.allow_fee_payment;
        if fee_payment < fee {
            return Err(WalletError::InsufficientDustForFee {
                fee,
                fee_payment,
                estimate: fee_coverage_estimate(
                    &dust_state,
                    &recipe.guaranteed_inputs,
                    fee,
                    params.current_time,
                ),
            });
        }
    }

    // Deregistration carries `allow_fee_payment = 0` (the UTxOs are
    // leaving generation, so they can't fund the fee). It must pay from
    // already-generated dust — balance a fee-paying dust spend into the
    // tx, exactly as the transfer path does. Without this the node
    // rejects the tx with BalanceCheckOverspend (custom error 138).
    // Registration is left untouched: its `allow_fee_payment` lets the
    // newly-generated dust cover the fee (matching the TS facade, which
    // only runs `dust.balanceTransactions` on the deregistration path).
    let (tx, balanced_dust) = if dust_receiver.is_none() {
        let dust_sk = params.dust_secret_key.ok_or_else(|| {
            WalletError::Dust(
                "deregistration requires a dust secret key to balance the transaction fee \
                 (allow_fee_payment is 0); pass it via RegistrationParams.dust_secret_key"
                    .to_owned(),
            )
        })?;
        let (dust_after, balanced_tx) = balance_dust_fee(
            rng,
            state.dust.clone(),
            dust_sk,
            &tx,
            &FeeContext {
                current_time: params.current_time,
                ttl: params.ttl,
                network_id: &network_label,
                ledger_parameters: state.ledger_parameters(),
            },
        )?;
        (balanced_tx, Some(dust_after))
    } else {
        (tx, None)
    };

    // Book the chosen Night UTxOs (available -> pending) so a concurrent
    // build that touches any of these UTxOs fails fast with UtxoNotFound
    // instead of only at submission. Mirrors midnight-wallet PR #416
    // (`unshielded.rotateUtxos`). Booking is the last step: any earlier
    // failure leaves `state` untouched.
    let mut unshielded = state.unshielded.clone();
    for utxo in recipe
        .guaranteed_inputs
        .iter()
        .chain(recipe.fallible_inputs.iter())
    {
        unshielded = unshielded.spend(utxo)?;
    }
    let mut state = state.with_unshielded(unshielded);
    if let Some(dust_after) = balanced_dust {
        state = state.with_dust(dust_after);
    }

    Ok((
        SignedRegistrationRecipe {
            recipe: UnprovenTransactionRecipe { transaction: tx },
        },
        state,
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::abstractions::NetworkId;
    use crate::dust::DustState;
    use crate::shielded::ShieldedState;
    use crate::unshielded::{ledger_adapter::signing_key_from_bytes, UnshieldedState};
    use moonproof_ledger::base_crypto::time::Duration;
    use moonproof_ledger::ledger::dust::{DustParameters, DustSecretKey};
    use moonproof_ledger::ledger::structure::Transaction;
    use moonproof_ledger::zswap::keys::{SecretKeys as ZswapSecretKeys, Seed as ZswapSeed};
    use rand::rngs::StdRng;
    use rand::SeedableRng;

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

    /// Generous enough that a minute of generation covers a
    /// registration's fee (~1e15 Specks under the initial parameters),
    /// which a first-time registration must pay from that dust.
    fn dust_params() -> DustParameters {
        DustParameters {
            night_dust_ratio: 10_000_000_000,
            generation_decay_rate: 4_000_000_000,
            dust_grace_period: Duration::from_secs(60),
        }
    }

    fn empty_facade(network: NetworkId) -> (FacadeState, DustSecretKey) {
        let dsk = DustSecretKey::derive_secret_key(&[0x02u8; 32]);
        let sh = ShieldedState::init_empty(&zswap_keys(0x01), network.clone());
        let du = DustState::init_empty(dust_params(), &dsk, network.clone());
        (
            FacadeState::new(sh, UnshieldedState::empty(), du, network),
            dsk,
        )
    }

    /// Build a facade seeded with `utxos` in the unshielded `available`
    /// pool. Needed because `build_registration_recipe` now books
    /// (available -> pending) at build time per midnight-wallet PR #416.
    fn facade_with_night_utxos(
        network: NetworkId,
        utxos: &[UtxoWithMeta],
    ) -> (FacadeState, DustSecretKey) {
        let (f, dsk) = empty_facade(network);
        let seeded = UnshieldedState::restore(utxos.iter().cloned(), Vec::<UtxoWithMeta>::new());
        (f.with_unshielded(seeded), dsk)
    }

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

    fn params<'a>(
        sk: &'a SigningKey,
        vk: &'a VerifyingKey,
        dsk: Option<&'a DustSecretKey>,
    ) -> RegistrationParams<'a> {
        RegistrationParams {
            night_signing_key: sk,
            night_verifying_key: vk,
            dust_secret_key: dsk,
            ttl: Timestamp::from_secs(3600),
            current_time: Timestamp::from_secs(60),
        }
    }

    /// Nothing generated yet means no fee payment, which the node would
    /// reject as `BalanceCheckOverspend`; the build refuses and says when
    /// generation will cover the fee.
    #[test]
    fn a_first_registration_without_generated_dust_is_refused() {
        let mut rng = StdRng::seed_from_u64(9);
        let sk = signing_key_from_bytes(&[0x77u8; 32]).unwrap();
        let vk = sk.verifying_key();
        let owner = {
            use moonproof_ledger::coin_structure::coin::UserAddress;
            UserAddress::from(vk.clone()).0 .0
        };
        let utxos = vec![night_utxo(0x11, 500_000, owner)];
        let (f, dsk) = facade_with_night_utxos(NetworkId::Undeployed, &utxos);
        let unbooked = f.unshielded.available_len();
        let mut at_creation = params(&sk, &vk, None);
        at_creation.current_time = Timestamp::from_secs(0);
        let err =
            build_registration_recipe(&mut rng, f, &utxos, DustPublicKey::from(dsk), &at_creation)
                .unwrap_err();
        match err {
            WalletError::InsufficientDustForFee {
                fee,
                fee_payment,
                estimate,
            } => {
                assert_eq!(fee_payment, 0);
                assert!(fee > 0);
                assert!(matches!(
                    estimate,
                    crate::dust::FeeCoverageEstimate::Reachable { seconds, .. } if seconds > 0
                ));
            }
            other => panic!("expected InsufficientDustForFee, got {other:?}"),
        }
        assert_eq!(
            unbooked, 1,
            "the UTxO was available before the refused build"
        );
    }

    #[test]
    fn register_with_empty_utxos_errors() {
        let mut rng = StdRng::seed_from_u64(1);
        let (f, dsk) = empty_facade(NetworkId::Undeployed);
        let sk = signing_key_from_bytes(&[0x77u8; 32]).unwrap();
        let vk = sk.verifying_key();
        let dust_pk = DustPublicKey::from(dsk);
        let err = build_registration_recipe(&mut rng, f, &[], dust_pk, &params(&sk, &vk, None))
            .unwrap_err();
        assert!(matches!(err, WalletError::Dust(_)));
    }

    #[test]
    fn register_single_utxo_produces_signed_recipe() {
        let mut rng = StdRng::seed_from_u64(2);
        let sk = signing_key_from_bytes(&[0x77u8; 32]).unwrap();
        let vk = sk.verifying_key();
        let owner = {
            use moonproof_ledger::coin_structure::coin::UserAddress;
            UserAddress::from(vk.clone()).0 .0
        };
        let utxos = vec![night_utxo(0x11, 500_000, owner)];
        let (f, dsk) = facade_with_night_utxos(NetworkId::Undeployed, &utxos);
        let dust_pk = DustPublicKey::from(dsk);
        let (signed, _) =
            build_registration_recipe(&mut rng, f, &utxos, dust_pk, &params(&sk, &vk, None))
                .unwrap();

        match &signed.recipe.transaction {
            Transaction::Standard(stx) => {
                assert_eq!(stx.intents.size(), 1);
                // Registration intent contains dust_actions with one
                // registration and no spends.
                let entry = stx.intents.iter().next().unwrap();
                let pair = &*entry;
                let intent = &*pair.1;
                let actions = intent.dust_actions.as_ref().unwrap();
                assert_eq!(actions.registrations.len(), 1);
                assert_eq!(actions.spends.len(), 0);
                let reg_entry = actions.registrations.iter().next().unwrap();
                let reg = &*reg_entry;
                assert!(reg.dust_address.is_some());
            }
            Transaction::ClaimRewards(_) => panic!("expected Standard"),
        }
    }

    #[test]
    fn deregister_requires_dust_to_cover_fee() {
        // Deregistration carries `allow_fee_payment = 0`, so the builder
        // must balance a fee-paying dust spend. A facade with night UTxOs
        // but no spendable dust can't cover the fee, so the build fails
        // fast — proving fee balancing is wired. Before the fix the
        // builder emitted a fee-less tx the node rejected with
        // BalanceCheckOverspend (custom error 138).
        let mut rng = StdRng::seed_from_u64(3);
        let sk = signing_key_from_bytes(&[0x77u8; 32]).unwrap();
        let vk = sk.verifying_key();
        let owner = {
            use moonproof_ledger::coin_structure::coin::UserAddress;
            UserAddress::from(vk.clone()).0 .0
        };
        let utxos = vec![night_utxo(0x22, 500_000, owner)];
        let (f, dsk) = facade_with_night_utxos(NetworkId::Undeployed, &utxos);
        let err = build_deregistration_recipe(&mut rng, f, &utxos, &params(&sk, &vk, Some(&dsk)))
            .unwrap_err();
        assert!(
            matches!(err, WalletError::InsufficientFunds { .. }),
            "expected InsufficientFunds (no dust to cover fee), got {err:?}"
        );
    }

    #[test]
    fn deregister_without_dust_secret_key_errors() {
        // Passing `dust_secret_key: None` to a deregistration is refused
        // rather than emitting an unbalanced (overspending) tx.
        let mut rng = StdRng::seed_from_u64(7);
        let sk = signing_key_from_bytes(&[0x77u8; 32]).unwrap();
        let vk = sk.verifying_key();
        let owner = {
            use moonproof_ledger::coin_structure::coin::UserAddress;
            UserAddress::from(vk.clone()).0 .0
        };
        let utxos = vec![night_utxo(0x33, 500_000, owner)];
        let (f, _dsk) = facade_with_night_utxos(NetworkId::Undeployed, &utxos);
        let err =
            build_deregistration_recipe(&mut rng, f, &utxos, &params(&sk, &vk, None)).unwrap_err();
        assert!(matches!(err, WalletError::Dust(_)), "got {err:?}");
    }

    #[test]
    fn deregister_with_no_utxos_and_no_address_errors_no_effect() {
        // Deregister with no UTXOs AND None dust_receiver produces an
        // empty intent — the builder returns Ok(None), which we convert
        // to a Dust error since there's no on-chain effect.
        let mut rng = StdRng::seed_from_u64(4);
        let (f, _dsk) = empty_facade(NetworkId::Undeployed);
        let sk = signing_key_from_bytes(&[0x77u8; 32]).unwrap();
        let vk = sk.verifying_key();
        let err =
            build_deregistration_recipe(&mut rng, f, &[], &params(&sk, &vk, None)).unwrap_err();
        assert!(matches!(err, WalletError::Dust(_)));
    }

    #[test]
    fn register_multiple_utxos_splits_into_guaranteed_plus_fallible() {
        let mut rng = StdRng::seed_from_u64(5);
        let sk = signing_key_from_bytes(&[0x77u8; 32]).unwrap();
        let vk = sk.verifying_key();
        let owner = {
            use moonproof_ledger::coin_structure::coin::UserAddress;
            UserAddress::from(vk.clone()).0 .0
        };
        let utxos = vec![
            night_utxo(0x11, 100_000, owner),
            night_utxo(0x22, 500_000, owner),
            night_utxo(0x33, 300_000, owner),
        ];
        let (f, dsk) = facade_with_night_utxos(NetworkId::Undeployed, &utxos);
        let dust_pk = DustPublicKey::from(dsk);
        let (signed, _) =
            build_registration_recipe(&mut rng, f, &utxos, dust_pk, &params(&sk, &vk, None))
                .unwrap();
        match &signed.recipe.transaction {
            Transaction::Standard(stx) => {
                let entry = stx.intents.iter().next().unwrap();
                let pair = &*entry;
                let intent = &*pair.1;
                let g_inputs = intent
                    .guaranteed_unshielded_offer
                    .as_ref()
                    .map_or(0, |o| o.inputs.len());
                let f_inputs = intent
                    .fallible_unshielded_offer
                    .as_ref()
                    .map_or(0, |o| o.inputs.len());
                assert_eq!(g_inputs, 1, "highest-yield UTXO lands in guaranteed");
                assert_eq!(f_inputs, 2, "other two land in fallible");
            }
            Transaction::ClaimRewards(_) => panic!("expected Standard"),
        }
    }

    #[test]
    fn register_populates_unshielded_offer_signatures() {
        let mut rng = StdRng::seed_from_u64(6);
        let sk = signing_key_from_bytes(&[0x77u8; 32]).unwrap();
        let vk = sk.verifying_key();
        let owner = {
            use moonproof_ledger::coin_structure::coin::UserAddress;
            UserAddress::from(vk.clone()).0 .0
        };
        let utxos = vec![night_utxo(0x11, 500_000, owner)];
        let (f, dsk) = facade_with_night_utxos(NetworkId::Undeployed, &utxos);
        let dust_pk = DustPublicKey::from(dsk);
        let (signed, _) =
            build_registration_recipe(&mut rng, f, &utxos, dust_pk, &params(&sk, &vk, None))
                .unwrap();
        match &signed.recipe.transaction {
            Transaction::Standard(stx) => {
                let entry = stx.intents.iter().next().unwrap();
                let pair = &*entry;
                let intent = &*pair.1;
                let offer = intent.guaranteed_unshielded_offer.as_ref().unwrap();
                assert_eq!(
                    offer.inputs.len(),
                    offer.signatures.len(),
                    "sign_dust_intent attaches one signature per input"
                );
                let reg_entry = intent
                    .dust_actions
                    .as_ref()
                    .unwrap()
                    .registrations
                    .iter()
                    .next()
                    .unwrap();
                let reg = &*reg_entry;
                assert!(reg.signature.is_some(), "registration is signed");
            }
            Transaction::ClaimRewards(_) => panic!("expected Standard"),
        }
    }

    #[test]
    fn register_books_night_utxos_into_pending() {
        // Mirrors midnight-wallet PR #416: build-time booking moves
        // chosen Night UTxOs from available to pending so a concurrent
        // build that wants the same UTxO fails fast.
        let mut rng = StdRng::seed_from_u64(7);
        let sk = signing_key_from_bytes(&[0x77u8; 32]).unwrap();
        let vk = sk.verifying_key();
        let owner = {
            use moonproof_ledger::coin_structure::coin::UserAddress;
            UserAddress::from(vk.clone()).0 .0
        };
        let utxos = vec![
            night_utxo(0x11, 100_000, owner),
            night_utxo(0x22, 500_000, owner),
        ];
        let (f, dsk) = facade_with_night_utxos(NetworkId::Undeployed, &utxos);
        let dust_pk = DustPublicKey::from(dsk);

        assert_eq!(f.unshielded.available_len(), 2);
        assert_eq!(f.unshielded.pending_len(), 0);

        let (_signed, after) =
            build_registration_recipe(&mut rng, f, &utxos, dust_pk, &params(&sk, &vk, None))
                .unwrap();

        assert_eq!(after.unshielded.available_len(), 0);
        assert_eq!(after.unshielded.pending_len(), 2);
    }

    #[test]
    fn register_second_build_for_same_utxos_fails_fast() {
        // After a first build books the UTxOs, a concurrent second
        // build against the *same* state must fail at build time, not
        // submission. We model this by re-using the freshly-booked
        // state as input to a second build call.
        let mut rng = StdRng::seed_from_u64(8);
        let sk = signing_key_from_bytes(&[0x77u8; 32]).unwrap();
        let vk = sk.verifying_key();
        let owner = {
            use moonproof_ledger::coin_structure::coin::UserAddress;
            UserAddress::from(vk.clone()).0 .0
        };
        let utxos = vec![night_utxo(0x11, 500_000, owner)];
        let (f, dsk) = facade_with_night_utxos(NetworkId::Undeployed, &utxos);
        let dust_pk = DustPublicKey::from(dsk);

        let (_first, after) =
            build_registration_recipe(&mut rng, f, &utxos, dust_pk, &params(&sk, &vk, None))
                .unwrap();
        let err =
            build_registration_recipe(&mut rng, after, &utxos, dust_pk, &params(&sk, &vk, None))
                .unwrap_err();
        assert!(
            matches!(err, WalletError::UtxoNotFound { .. }),
            "expected UtxoNotFound, got {err:?}"
        );
    }
}