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
//! `UnshieldedState` — the available-vs-pending UTXO state machine.
//!
//! Ported 1:1 from `@midnight-ntwrk/wallet-sdk-unshielded-wallet`:
//! - `apply_update` (`SUCCESS` / `PARTIAL_SUCCESS`)
//! - `apply_failed_update` (`FAILURE`)
//! - `spend` / `spend_by_id` / `rollback_spend` / `rollback_spend_by_id`
//! - `restore` / `to_arrays`
//!
//! Uses an `IndexMap` so iteration order is deterministic — matters for
//! reproducible tx building and snapshot tests.

use indexmap::IndexMap;
use serde::{Deserialize, Serialize};

use crate::error::{Result, WalletError};
use crate::types::{Amount, CoinRecipe, TokenType};

/// Unique identifier for a UTXO on the Midnight unshielded ledger.
///
/// The TS reference uses the string form `${intentHash}#${outputNo}` as its
/// hash-map key. We use a structural tuple — same uniqueness, no hashing of
/// hex strings on the hot path.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct UtxoId {
    pub intent_hash: [u8; 32],
    pub output_no: u32,
}

impl UtxoId {
    #[inline]
    #[must_use]
    pub const fn new(intent_hash: [u8; 32], output_no: u32) -> Self {
        Self {
            intent_hash,
            output_no,
        }
    }
}

/// An unshielded UTXO as it appears on chain.
///
/// The ledger crate's own `Utxo` type additionally carries crypto-specific
/// reprs (`UserAddress`, `UnshieldedTokenType`, `IntentHash` newtypes); we use
/// byte-level shapes here so the wallet state machine is decoupled from the
/// exact ledger version, and conversions at the ledger boundary happen in the
/// transacting layer.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct UnshieldedUtxo {
    pub id: UtxoId,
    /// Token amount in its smallest on-chain unit (e.g. STAR for NIGHT).
    pub value: u128,
    pub token_type: TokenType,
    /// 32-byte user address (owner's public key).
    pub owner: [u8; 32],
}

impl UnshieldedUtxo {
    #[inline]
    #[must_use]
    pub fn new(id: UtxoId, value: u128, token_type: TokenType, owner: [u8; 32]) -> Self {
        Self {
            id,
            value,
            token_type,
            owner,
        }
    }
}

impl CoinRecipe for UnshieldedUtxo {
    #[inline]
    fn token_type(&self) -> &TokenType {
        &self.token_type
    }

    #[inline]
    fn value(&self) -> Amount {
        Amount::from(self.value)
    }
}

/// Wallet-level metadata attached to each tracked UTXO.
///
/// `ctime` is the chain time at which the UTXO was created. `registered_for_dust_generation`
/// flags NIGHT UTXOs that the wallet has registered with the Cardano side
/// to earn DUST (matches the TS reference's `registeredForDustGeneration`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct UtxoMeta {
    /// Chain timestamp (seconds since UNIX epoch) when this UTXO was created.
    pub ctime: i64,
    pub registered_for_dust_generation: bool,
}

impl UtxoMeta {
    #[inline]
    #[must_use]
    pub const fn new(ctime: i64, registered_for_dust_generation: bool) -> Self {
        Self {
            ctime,
            registered_for_dust_generation,
        }
    }
}

/// A UTXO paired with the wallet's local metadata.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UtxoWithMeta {
    pub utxo: UnshieldedUtxo,
    pub meta: UtxoMeta,
}

impl UtxoWithMeta {
    #[inline]
    #[must_use]
    pub fn new(utxo: UnshieldedUtxo, meta: UtxoMeta) -> Self {
        Self { utxo, meta }
    }

    #[inline]
    #[must_use]
    pub fn id(&self) -> UtxoId {
        self.utxo.id
    }
}

impl CoinRecipe for UtxoWithMeta {
    #[inline]
    fn token_type(&self) -> &TokenType {
        self.utxo.token_type()
    }
    #[inline]
    fn value(&self) -> Amount {
        self.utxo.value()
    }
}

/// Final status of a submitted transaction as reported by the chain.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum UpdateStatus {
    Success,
    Failure,
    PartialSuccess,
}

impl UpdateStatus {
    #[inline]
    #[must_use]
    pub fn is_success_or_partial(self) -> bool {
        matches!(self, Self::Success | Self::PartialSuccess)
    }

    #[inline]
    #[must_use]
    pub fn is_failure(self) -> bool {
        matches!(self, Self::Failure)
    }

    #[must_use]
    pub fn as_label(self) -> &'static str {
        match self {
            Self::Success => "SUCCESS",
            Self::Failure => "FAILURE",
            Self::PartialSuccess => "PARTIAL_SUCCESS",
        }
    }
}

/// One unshielded state transition reported by the chain.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UnshieldedUpdate {
    pub created_utxos: Vec<UtxoWithMeta>,
    pub spent_utxos: Vec<UtxoWithMeta>,
    pub status: UpdateStatus,
}

impl UnshieldedUpdate {
    #[must_use]
    pub fn success(created: Vec<UtxoWithMeta>, spent: Vec<UtxoWithMeta>) -> Self {
        Self {
            created_utxos: created,
            spent_utxos: spent,
            status: UpdateStatus::Success,
        }
    }

    #[must_use]
    pub fn failure(created: Vec<UtxoWithMeta>, spent: Vec<UtxoWithMeta>) -> Self {
        Self {
            created_utxos: created,
            spent_utxos: spent,
            status: UpdateStatus::Failure,
        }
    }

    #[must_use]
    pub fn partial_success(created: Vec<UtxoWithMeta>, spent: Vec<UtxoWithMeta>) -> Self {
        Self {
            created_utxos: created,
            spent_utxos: spent,
            status: UpdateStatus::PartialSuccess,
        }
    }
}

/// Available + pending UTXO bookkeeping for an unshielded wallet.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct UnshieldedState {
    available: IndexMap<UtxoId, UtxoWithMeta>,
    pending: IndexMap<UtxoId, UtxoWithMeta>,
}

impl UnshieldedState {
    /// Empty state — no tracked UTXOs.
    #[inline]
    #[must_use]
    pub fn empty() -> Self {
        Self::default()
    }

    /// Rebuild a state from externally-persisted available + pending arrays.
    #[must_use]
    pub fn restore(
        available: impl IntoIterator<Item = UtxoWithMeta>,
        pending: impl IntoIterator<Item = UtxoWithMeta>,
    ) -> Self {
        let mut s = Self::empty();
        for u in available {
            s.available.insert(u.id(), u);
        }
        for u in pending {
            s.pending.insert(u.id(), u);
        }
        s
    }

    /// Iterate over available UTXOs in insertion order.
    #[inline]
    pub fn available(&self) -> impl ExactSizeIterator<Item = &UtxoWithMeta> {
        self.available.values()
    }

    /// Iterate over pending UTXOs in insertion order.
    #[inline]
    pub fn pending(&self) -> impl ExactSizeIterator<Item = &UtxoWithMeta> {
        self.pending.values()
    }

    #[inline]
    #[must_use]
    pub fn has_available(&self, id: &UtxoId) -> bool {
        self.available.contains_key(id)
    }

    #[inline]
    #[must_use]
    pub fn has_pending(&self, id: &UtxoId) -> bool {
        self.pending.contains_key(id)
    }

    #[inline]
    #[must_use]
    pub fn available_len(&self) -> usize {
        self.available.len()
    }

    #[inline]
    #[must_use]
    pub fn pending_len(&self) -> usize {
        self.pending.len()
    }

    /// Collect available + pending into owned `Vec`s (mirrors the TS
    /// `toArrays` helper).
    #[must_use]
    pub fn to_arrays(&self) -> (Vec<UtxoWithMeta>, Vec<UtxoWithMeta>) {
        (
            self.available.values().cloned().collect(),
            self.pending.values().cloned().collect(),
        )
    }

    /// Move a UTXO from `available` to `pending`. Errors if the UTXO isn't
    /// available.
    pub fn spend(mut self, utxo: &UtxoWithMeta) -> Result<Self> {
        let id = utxo.id();
        if self.available.shift_remove(&id).is_none() {
            return Err(WalletError::UtxoNotFound { id });
        }
        self.pending.insert(id, utxo.clone());
        Ok(self)
    }

    /// Convenience: spend by raw ledger UTXO identity. Resolves the full
    /// `UtxoWithMeta` from `available` before moving to `pending`.
    pub fn spend_by_id(self, id: UtxoId) -> Result<Self> {
        let Some(found) = self.available.get(&id).cloned() else {
            return Err(WalletError::UtxoNotFound { id });
        };
        self.spend(&found)
    }

    /// Restore a pending UTXO back to `available`. No-op if the UTXO isn't
    /// pending (matches the TS reference: rollbacks race with sync and must
    /// be idempotent).
    #[must_use]
    pub fn rollback_spend(mut self, utxo: &UtxoWithMeta) -> Self {
        let id = utxo.id();
        if self.pending.shift_remove(&id).is_none() {
            return self;
        }
        self.available.insert(id, utxo.clone());
        self
    }

    /// Rollback by id. No-op if not pending.
    #[must_use]
    pub fn rollback_spend_by_id(mut self, id: UtxoId) -> Self {
        if let Some(found) = self.pending.shift_remove(&id) {
            self.available.insert(id, found);
        }
        self
    }

    /// Apply a confirmed chain update. Accepts only `SUCCESS` or
    /// `PARTIAL_SUCCESS`. Created UTXOs go to `available`; spent UTXOs are
    /// removed from both `available` and `pending`.
    pub fn apply_update(mut self, update: &UnshieldedUpdate) -> Result<Self> {
        if !update.status.is_success_or_partial() {
            return Err(WalletError::InvalidUpdateStatus {
                expected: "SUCCESS or PARTIAL_SUCCESS",
                got: update.status.as_label(),
            });
        }

        for spent in &update.spent_utxos {
            let id = spent.id();
            self.available.shift_remove(&id);
            self.pending.shift_remove(&id);
        }

        for created in &update.created_utxos {
            self.available.insert(created.id(), created.clone());
        }

        Ok(self)
    }

    /// Apply a chain-reported FAILURE. Restores `spent_utxos` from `pending`
    /// back to `available`. Spent UTXOs not present in `pending` are
    /// silently inserted into `available` — matches the TS reference's
    /// behavior when the indexer observes a failed tx before the wallet
    /// saw its own `spend` (rare race), so state converges regardless.
    pub fn apply_failed_update(mut self, update: &UnshieldedUpdate) -> Result<Self> {
        if !update.status.is_failure() {
            return Err(WalletError::InvalidUpdateStatus {
                expected: "FAILURE",
                got: update.status.as_label(),
            });
        }

        for spent in &update.spent_utxos {
            let id = spent.id();
            self.pending.shift_remove(&id);
            self.available.insert(id, spent.clone());
        }

        Ok(self)
    }
}

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

    // --- Test helpers --------------------------------------------------

    fn token() -> TokenType {
        TokenType::new("native")
    }

    fn mock_utxo(intent_byte: u8, output_no: u32) -> UtxoWithMeta {
        UtxoWithMeta::new(
            UnshieldedUtxo::new(
                UtxoId::new([intent_byte; 32], output_no),
                1_000,
                token(),
                [intent_byte; 32],
            ),
            UtxoMeta::new(0, false),
        )
    }

    #[allow(clippy::cast_possible_truncation)] // test helper: small loop indices
    fn make_update(status: UpdateStatus, created: usize, spent: usize) -> UnshieldedUpdate {
        let created_utxos: Vec<_> = (0..created)
            .map(|i| mock_utxo(0xC0 | (i as u8), i as u32))
            .collect();
        let spent_utxos: Vec<_> = (0..spent)
            .map(|i| mock_utxo(0xD0 | (i as u8), i as u32))
            .collect();
        UnshieldedUpdate {
            created_utxos,
            spent_utxos,
            status,
        }
    }

    // --- applyUpdate ---------------------------------------------------

    #[test]
    fn apply_update_success_creates_utxo() {
        let s = UnshieldedState::empty()
            .apply_update(&make_update(UpdateStatus::Success, 1, 0))
            .unwrap();
        assert_eq!(s.available_len(), 1);
        assert_eq!(s.pending_len(), 0);
    }

    #[test]
    fn apply_update_success_creates_multiple_utxos() {
        let s = UnshieldedState::empty()
            .apply_update(&make_update(UpdateStatus::Success, 3, 0))
            .unwrap();
        assert_eq!(s.available_len(), 3);
        assert_eq!(s.pending_len(), 0);
    }

    #[test]
    fn apply_update_rejects_failure_status() {
        let err = UnshieldedState::empty()
            .apply_update(&make_update(UpdateStatus::Failure, 1, 0))
            .unwrap_err();
        assert!(matches!(err, WalletError::InvalidUpdateStatus { .. }));
    }

    #[test]
    fn apply_update_partial_success_behaves_like_success() {
        let created = mock_utxo(0xAA, 0);
        let upd = UnshieldedUpdate::partial_success(vec![created.clone()], vec![]);
        let s = UnshieldedState::empty().apply_update(&upd).unwrap();
        assert!(s.has_available(&created.id()));
        assert_eq!(s.available_len(), 1);
        assert_eq!(s.pending_len(), 0);
    }

    #[test]
    fn apply_update_creates_and_spends_in_one_step() {
        let existing = mock_utxo(0x10, 0);
        let created = mock_utxo(0x20, 0);

        let initial = UnshieldedState::empty()
            .apply_update(&UnshieldedUpdate::success(vec![existing.clone()], vec![]))
            .unwrap();

        let after = initial
            .apply_update(&UnshieldedUpdate::success(
                vec![created.clone()],
                vec![existing.clone()],
            ))
            .unwrap();

        assert!(after.has_available(&created.id()));
        assert!(!after.has_available(&existing.id()));
        assert_eq!(after.available_len(), 1);
        assert_eq!(after.pending_len(), 0);
    }

    #[test]
    fn apply_update_removes_confirmed_spent_from_pending() {
        let u = mock_utxo(0x33, 0);
        let s = UnshieldedState::empty()
            .apply_update(&UnshieldedUpdate::success(vec![u.clone()], vec![]))
            .unwrap()
            .spend(&u)
            .unwrap();
        assert!(s.has_pending(&u.id()));

        let after = s
            .apply_update(&UnshieldedUpdate::success(vec![], vec![u.clone()]))
            .unwrap();
        assert!(!after.has_pending(&u.id()));
        assert!(!after.has_available(&u.id()));
    }

    #[test]
    fn apply_update_empty_is_noop() {
        let seed = mock_utxo(0xAB, 0);
        let before = UnshieldedState::empty()
            .apply_update(&UnshieldedUpdate::success(vec![seed.clone()], vec![]))
            .unwrap();
        let after = before
            .apply_update(&UnshieldedUpdate::success(vec![], vec![]))
            .unwrap();
        assert!(after.has_available(&seed.id()));
        assert_eq!(after.available_len(), 1);
        assert_eq!(after.pending_len(), 0);
    }

    #[test]
    fn apply_update_silently_ignores_unknown_spent() {
        let present = mock_utxo(0x01, 0);
        let ghost = mock_utxo(0x02, 0);
        let state = UnshieldedState::empty()
            .apply_update(&UnshieldedUpdate::success(vec![present.clone()], vec![]))
            .unwrap()
            .apply_update(&UnshieldedUpdate::success(vec![], vec![ghost.clone()]))
            .unwrap();
        assert!(state.has_available(&present.id()));
        assert_eq!(state.available_len(), 1);
        assert_eq!(state.pending_len(), 0);
    }

    #[test]
    fn apply_update_places_each_created_by_its_id() {
        let a = mock_utxo(0xAA, 0);
        let b = mock_utxo(0xBB, 1);
        let state = UnshieldedState::empty()
            .apply_update(&UnshieldedUpdate::success(
                vec![a.clone(), b.clone()],
                vec![],
            ))
            .unwrap();
        assert_eq!(state.available().find(|u| u.id() == a.id()), Some(&a));
        assert_eq!(state.available().find(|u| u.id() == b.id()), Some(&b));
        assert_eq!(state.available_len(), 2);
    }

    // --- applyFailedUpdate --------------------------------------------

    #[test]
    fn apply_failed_update_restores_pending() {
        let update = make_update(UpdateStatus::Success, 1, 0);
        let utxo_to_spend = update.created_utxos[0].clone();
        let failed = UnshieldedUpdate::failure(vec![], vec![utxo_to_spend.clone()]);

        let state = UnshieldedState::empty()
            .apply_update(&update)
            .unwrap()
            .spend(&utxo_to_spend)
            .unwrap()
            .apply_failed_update(&failed)
            .unwrap();

        assert_eq!(state.available_len(), 1);
        assert_eq!(state.pending_len(), 0);
    }

    #[test]
    fn apply_failed_update_rejects_success_status() {
        let err = UnshieldedState::empty()
            .apply_failed_update(&make_update(UpdateStatus::Success, 0, 1))
            .unwrap_err();
        assert!(matches!(err, WalletError::InvalidUpdateStatus { .. }));
    }

    #[test]
    fn apply_failed_update_rejects_partial_success() {
        let err = UnshieldedState::empty()
            .apply_failed_update(&UnshieldedUpdate::partial_success(vec![], vec![]))
            .unwrap_err();
        assert!(matches!(err, WalletError::InvalidUpdateStatus { .. }));
    }

    #[test]
    fn apply_failed_update_restores_spent_and_clears_pending() {
        let a = mock_utxo(0xAA, 0);
        let b = mock_utxo(0xBB, 0);

        let after = UnshieldedState::empty()
            .apply_update(&UnshieldedUpdate::success(
                vec![a.clone(), b.clone()],
                vec![],
            ))
            .unwrap()
            .spend(&a)
            .unwrap();
        assert!(after.has_pending(&a.id()));
        assert!(!after.has_available(&a.id()));
        assert!(after.has_available(&b.id()));

        let recovered = after
            .apply_failed_update(&UnshieldedUpdate::failure(vec![], vec![a.clone()]))
            .unwrap();
        assert!(recovered.has_available(&a.id()));
        assert!(recovered.has_available(&b.id()));
        assert_eq!(recovered.available_len(), 2);
        assert!(!recovered.has_pending(&a.id()));
        assert_eq!(recovered.pending_len(), 0);
    }

    #[test]
    fn apply_failed_update_for_unknown_spent_inserts_into_available() {
        // Matches the TS behavior: if the indexer reports a failed tx that spent
        // a utxo we don't know about, we converge by surfacing it in `available`.
        let present = mock_utxo(0x01, 0);
        let ghost = mock_utxo(0x02, 0);
        let after = UnshieldedState::empty()
            .apply_update(&UnshieldedUpdate::success(vec![present.clone()], vec![]))
            .unwrap()
            .apply_failed_update(&UnshieldedUpdate::failure(vec![], vec![ghost.clone()]))
            .unwrap();
        assert!(after.has_available(&present.id()));
        assert!(after.has_available(&ghost.id()));
        assert_eq!(after.pending_len(), 0);
    }

    // --- spend / rollback --------------------------------------------

    #[test]
    fn spend_moves_utxo_to_pending() {
        let update = make_update(UpdateStatus::Success, 1, 0);
        let state = UnshieldedState::empty()
            .apply_update(&update)
            .unwrap()
            .spend(&update.created_utxos[0])
            .unwrap();
        assert_eq!(state.available_len(), 0);
        assert_eq!(state.pending_len(), 1);
    }

    #[test]
    fn spend_errors_when_utxo_not_available() {
        let update = make_update(UpdateStatus::Success, 1, 0);
        let ghost = mock_utxo(0xFF, 7);
        let err = UnshieldedState::empty()
            .apply_update(&update)
            .unwrap()
            .spend(&ghost)
            .unwrap_err();
        match err {
            WalletError::UtxoNotFound { id } => assert_eq!(id, ghost.id()),
            other => panic!("wrong error: {other:?}"),
        }
    }

    #[test]
    fn spend_by_id_succeeds_when_available() {
        let update = make_update(UpdateStatus::Success, 1, 0);
        let id = update.created_utxos[0].id();
        let state = UnshieldedState::empty()
            .apply_update(&update)
            .unwrap()
            .spend_by_id(id)
            .unwrap();
        assert_eq!(state.available_len(), 0);
        assert_eq!(state.pending_len(), 1);
    }

    #[test]
    fn spend_by_id_errors_when_not_available() {
        let ghost = mock_utxo(0x77, 0);
        let err = UnshieldedState::empty()
            .spend_by_id(ghost.id())
            .unwrap_err();
        match err {
            WalletError::UtxoNotFound { id } => assert_eq!(id, ghost.id()),
            other => panic!("wrong error: {other:?}"),
        }
    }

    #[test]
    fn rollback_spend_returns_pending_to_available() {
        let update = make_update(UpdateStatus::Success, 1, 0);
        let u = update.created_utxos[0].clone();
        let state = UnshieldedState::empty()
            .apply_update(&update)
            .unwrap()
            .spend(&u)
            .unwrap()
            .rollback_spend(&u);
        assert_eq!(state.available_len(), 1);
        assert_eq!(state.pending_len(), 0);
    }

    #[test]
    fn rollback_spend_by_id_is_idempotent() {
        let update = make_update(UpdateStatus::Success, 1, 0);
        let id = update.created_utxos[0].id();
        let state = UnshieldedState::empty()
            .apply_update(&update)
            .unwrap()
            .spend_by_id(id)
            .unwrap()
            .rollback_spend_by_id(id)
            .rollback_spend_by_id(id); // second call is a no-op
        assert_eq!(state.available_len(), 1);
        assert_eq!(state.pending_len(), 0);
    }

    // --- restore / to_arrays ------------------------------------------

    #[test]
    fn restore_and_to_arrays_round_trip() {
        let u1 = mock_utxo(0x01, 0);
        let u2 = mock_utxo(0x02, 0);
        let pending = mock_utxo(0x03, 0);
        let state = UnshieldedState::restore([u1.clone(), u2.clone()], [pending.clone()]);
        assert_eq!(state.available_len(), 2);
        assert_eq!(state.pending_len(), 1);

        let (av, pd) = state.to_arrays();
        assert_eq!(av.len(), 2);
        assert_eq!(pd.len(), 1);
    }

    // --- lifecycle ----------------------------------------------------

    #[test]
    fn lifecycle_create_spend_confirm_empties_both_collections() {
        let u = mock_utxo(0xA0, 0);
        let after = UnshieldedState::empty()
            .apply_update(&UnshieldedUpdate::success(vec![u.clone()], vec![]))
            .unwrap()
            .spend(&u)
            .unwrap()
            .apply_update(&UnshieldedUpdate::success(vec![], vec![u.clone()]))
            .unwrap();
        assert_eq!(after.available_len(), 0);
        assert_eq!(after.pending_len(), 0);
    }

    #[test]
    fn lifecycle_create_spend_fail_restores_available() {
        let u = mock_utxo(0xB0, 0);
        let after = UnshieldedState::empty()
            .apply_update(&UnshieldedUpdate::success(vec![u.clone()], vec![]))
            .unwrap()
            .spend(&u)
            .unwrap()
            .apply_failed_update(&UnshieldedUpdate::failure(vec![], vec![u.clone()]))
            .unwrap();
        assert!(after.has_available(&u.id()));
        assert_eq!(after.available_len(), 1);
        assert_eq!(after.pending_len(), 0);
    }

    // --- CoinRecipe conformance ---------------------------------------

    #[test]
    fn unshielded_utxo_implements_coin_recipe() {
        let u = UnshieldedUtxo::new(UtxoId::new([0; 32], 0), 42, token(), [0; 32]);
        assert_eq!(u.token_type(), &token());
        assert_eq!(u.value(), Amount::from(42_u32));
    }

    #[test]
    fn utxo_with_meta_implements_coin_recipe() {
        let u = mock_utxo(0xAA, 0);
        assert_eq!(u.token_type(), &token());
        assert_eq!(u.value(), Amount::from(1_000_u32));
    }
}