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
//! Releasing what a transaction booked when the chain will not apply it.
//!
//! Building a transaction moves the coins, `UTxOs` and Dust it spends to
//! pending in each sub-wallet, so a second build cannot spend them
//! again. Sync settles them once the chain includes the transaction;
//! when it is rejected, dropped, or abandoned before submission they
//! stay pending until released here.

use moonproof_ledger::ledger::structure::{BindingKind, ProofKind, SignatureKind, Transaction};
use moonproof_ledger::serialize::tagged_deserialize;
use moonproof_ledger::storage::Storable;

use crate::dust::ledger_adapter::Db;
use crate::error::{Result, WalletError};
use crate::facade::state::FacadeState;
use crate::facade::submission::{FinalizedTransaction, ProvenTransaction};
use crate::facade::transfer::UnprovenTransaction;
use crate::pending_tx::{PendingTransactionResult, PendingTransactionStatus};
use crate::unshielded::UtxoId;

impl FacadeState {
    /// Release every shielded coin, NIGHT `UTxO` and Dust spend `tx`
    /// booked. Idempotent, and a no-op for anything another party
    /// booked, so it is safe to call on any transaction this wallet
    /// balanced. Only for a transaction the chain did not include:
    /// releasing an included one would offer spent coins again.
    #[must_use]
    pub fn revert_transaction<S, P, B>(mut self, tx: &Transaction<S, P, B, Db>) -> Self
    where
        S: SignatureKind<Db>,
        P: ProofKind<Db>,
        B: BindingKind<S, P, Db> + Storable<Db>,
    {
        if let Transaction::Standard(stx) = tx {
            if let Some(offer) = stx.guaranteed_coins.as_deref() {
                self.shielded = self.shielded.apply_failed(offer);
            }
            for entry in stx.fallible_coins.iter() {
                self.shielded = self.shielded.apply_failed(&entry.1);
            }
            for entry in stx.intents.iter() {
                let intent = &*entry.1;
                for offer in [
                    intent.guaranteed_unshielded_offer.as_deref(),
                    intent.fallible_unshielded_offer.as_deref(),
                ]
                .into_iter()
                .flatten()
                {
                    for spend in offer.inputs.iter() {
                        self.unshielded = self.unshielded.rollback_spend_by_id(UtxoId::new(
                            spend.intent_hash.0 .0,
                            spend.output_no,
                        ));
                    }
                }
            }
        }
        self.dust = self.dust.revert_transaction(tx);
        self
    }

    /// Release what `tx` booked in the fallible segments the chain did
    /// not apply when it included `tx` as a partial success: the
    /// shielded coins of those segments' fallible offers and the NIGHT
    /// UTXOs of their intents' fallible unshielded offers.
    ///
    /// The guaranteed segment and every segment that succeeded spent
    /// their coins on chain, and sync settles those; releasing them
    /// would offer spent coins again. Every Dust spend sits in the
    /// guaranteed segment, so no Dust is released. A segment `tx` has
    /// nothing at is ignored, and one listed twice is released once.
    #[must_use]
    pub fn revert_failed_segments<S, P, B>(
        mut self,
        tx: &Transaction<S, P, B, Db>,
        failed_segments: &[u16],
    ) -> Self
    where
        S: SignatureKind<Db>,
        P: ProofKind<Db>,
        B: BindingKind<S, P, Db> + Storable<Db>,
    {
        let Transaction::Standard(stx) = tx else {
            return self;
        };
        for entry in stx.fallible_coins.iter() {
            if failed_segments.contains(&*entry.0) {
                self.shielded = self.shielded.apply_failed(&entry.1);
            }
        }
        for entry in stx.intents.iter() {
            if !failed_segments.contains(&*entry.0) {
                continue;
            }
            if let Some(offer) = entry.1.fallible_unshielded_offer.as_deref() {
                for spend in offer.inputs.iter() {
                    self.unshielded = self
                        .unshielded
                        .rollback_spend_by_id(UtxoId::new(spend.intent_hash.0 .0, spend.output_no));
                }
            }
        }
        self
    }

    /// Release what `tx` booked according to what became of it: nothing
    /// for a success, the failed segments' bookings for a partial
    /// success, and everything for a failure.
    #[must_use]
    pub fn release_ended<S, P, B>(
        self,
        tx: &Transaction<S, P, B, Db>,
        result: &PendingTransactionResult,
    ) -> Self
    where
        S: SignatureKind<Db>,
        P: ProofKind<Db>,
        B: BindingKind<S, P, Db> + Storable<Db>,
    {
        match result.status {
            PendingTransactionStatus::Success => self,
            PendingTransactionStatus::PartialSuccess => {
                let failed: Vec<u16> = result
                    .segments
                    .iter()
                    .filter(|segment| !segment.success)
                    .map(|segment| segment.id)
                    .collect();
                self.revert_failed_segments(tx, &failed)
            }
            PendingTransactionStatus::Failure => self.revert_transaction(tx),
        }
    }
}

impl FacadeState {
    /// [`Self::revert_transaction`] over a tagged-serialized
    /// transaction at any stage a wallet hands out: an unproven
    /// recipe, a proven unbound transaction, or a finalized one.
    ///
    /// # Errors
    ///
    /// [`WalletError::Serialization`] when the bytes are none of them.
    pub fn revert_serialized_transaction(self, bytes: &[u8]) -> Result<Self> {
        Ok(match AnyTransaction::decode(bytes)? {
            AnyTransaction::Finalized(tx) => self.revert_transaction(&tx),
            AnyTransaction::Proven(tx) => self.revert_transaction(&tx),
            AnyTransaction::Unproven(tx) => self.revert_transaction(&tx),
        })
    }

    /// [`Self::revert_failed_segments`] over a tagged-serialized
    /// transaction at any stage a wallet hands out.
    ///
    /// # Errors
    ///
    /// [`WalletError::Serialization`] when the bytes are none of them.
    pub fn revert_serialized_failed_segments(
        self,
        bytes: &[u8],
        failed_segments: &[u16],
    ) -> Result<Self> {
        Ok(match AnyTransaction::decode(bytes)? {
            AnyTransaction::Finalized(tx) => self.revert_failed_segments(&tx, failed_segments),
            AnyTransaction::Proven(tx) => self.revert_failed_segments(&tx, failed_segments),
            AnyTransaction::Unproven(tx) => self.revert_failed_segments(&tx, failed_segments),
        })
    }
}

enum AnyTransaction {
    Finalized(FinalizedTransaction),
    Proven(ProvenTransaction),
    Unproven(UnprovenTransaction),
}

impl AnyTransaction {
    fn decode(bytes: &[u8]) -> Result<Self> {
        if let Ok(tx) = tagged_deserialize::<FinalizedTransaction>(bytes) {
            return Ok(Self::Finalized(tx));
        }
        if let Ok(tx) = tagged_deserialize::<ProvenTransaction>(bytes) {
            return Ok(Self::Proven(tx));
        }
        tagged_deserialize::<UnprovenTransaction>(bytes)
            .map(Self::Unproven)
            .map_err(|e| {
                WalletError::Serialization(format!(
                    "not a finalized, proven or unproven transaction: {e}"
                ))
            })
    }
}

#[cfg(test)]
mod tests {
    use moonproof_ledger::base_crypto::hash::HashOutput;
    use moonproof_ledger::base_crypto::time::{Duration, Timestamp};
    use moonproof_ledger::coin_structure::coin::{Info as CoinInfo, Nonce, ShieldedTokenType};
    use moonproof_ledger::coin_structure::coin::{QualifiedInfo, NIGHT};
    use moonproof_ledger::ledger::dust::{DustParameters, DustSecretKey};
    use moonproof_ledger::ledger::structure::{Intent, UnshieldedOffer, UtxoSpend};
    use moonproof_ledger::signatures::Signature;
    use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
    use moonproof_ledger::zswap::keys::{SecretKeys as ZswapSecretKeys, Seed as ZswapSeed};
    use rand::rngs::StdRng;
    use rand::SeedableRng;

    use super::*;
    use crate::abstractions::NetworkId;
    use crate::dust::DustState;
    use crate::facade::transfer::UnprovenTransaction;
    use crate::pending_tx::SegmentResult;
    use crate::shielded::ledger_adapter::build_shielded_offer;
    use crate::shielded::transacting::ShieldedTransferRecipe;
    use crate::shielded::ShieldedState;
    use crate::types::TokenType;
    use crate::unshielded::ledger_adapter::{signing_key_from_bytes, to_ledger_intent_hash};
    use crate::unshielded::{
        UnshieldedState, UnshieldedUpdate, UnshieldedUtxo, UtxoMeta, UtxoWithMeta,
    };

    /// A transaction this wallet booked, laid out across three segments:
    /// shielded coin `s0` and UTXO `u0` in the guaranteed segment, `s1`
    /// and `u1` in fallible segment 1, `s2` and `u2` in fallible
    /// segment 2. Returns it with the wallet that booked all six.
    struct Booked {
        tx: UnprovenTransaction,
        state: FacadeState,
        shielded: [QualifiedInfo; 3],
    }

    type ShieldedOffer = moonproof_ledger::zswap::Offer<
        moonproof_ledger::transient_crypto::proofs::ProofPreimage,
        Db,
    >;

    /// Shielded coins `s0`, `s1`, `s2`, each spent by its own offer at
    /// the segment of the same number.
    fn shielded_spends(
        rng: &mut StdRng,
        network: &NetworkId,
    ) -> (ShieldedState, [QualifiedInfo; 3], Vec<ShieldedOffer>) {
        let keys = ZswapSecretKeys::from(ZswapSeed::from([0x05; 32]));
        let mut local = moonproof_ledger::zswap::local::State::<Db>::new();
        for nonce in 1..=3u8 {
            let coin = CoinInfo {
                nonce: Nonce(HashOutput([nonce; 32])),
                type_: ShieldedTokenType(HashOutput([0xCD; 32])),
                value: 1_000,
            };
            local = local.insert_coin(&keys, coin).unwrap();
        }
        let mut shielded = ShieldedState::init(local, &keys, network.clone());
        let mut coins: Vec<QualifiedInfo> = shielded
            .local()
            .coins
            .iter()
            .map(|entry| *entry.1)
            .collect();
        coins.sort_by_key(|coin| coin.nonce.0 .0);
        let coins: [QualifiedInfo; 3] = coins.try_into().expect("three coins");

        let mut offers = Vec::new();
        for (segment, coin) in (0u16..).zip(coins.iter()) {
            let recipe = ShieldedTransferRecipe {
                inputs: vec![*coin],
                recipient_outputs: Vec::new(),
                change_outputs: Vec::new(),
            };
            let (offer, next) = build_shielded_offer(rng, shielded, &keys, &recipe, segment)
                .unwrap()
                .expect("an offer spending the coin");
            shielded = next;
            offers.push(offer);
        }
        (shielded, coins, offers)
    }

    /// UTXOs `u0`, `u1`, `u2`, all booked, and an offer spending each.
    fn unshielded_spends() -> (UnshieldedState, Vec<UnshieldedOffer<Signature, Db>>) {
        let night_key = signing_key_from_bytes(&[0x77; 32]).unwrap();
        let owner = {
            use moonproof_ledger::coin_structure::coin::UserAddress;
            UserAddress::from(night_key.verifying_key()).0 .0
        };
        let utxos: Vec<UtxoWithMeta> = (0..3u8)
            .map(|i| {
                UtxoWithMeta::new(
                    UnshieldedUtxo::new(
                        UtxoId::new([0x10 + i; 32], 0),
                        500,
                        TokenType::new("native"),
                        owner,
                    ),
                    UtxoMeta::new(0, false),
                )
            })
            .collect();
        let mut unshielded = UnshieldedState::empty()
            .apply_update(&UnshieldedUpdate::success(utxos.clone(), vec![]))
            .unwrap();
        for utxo in &utxos {
            unshielded = unshielded.spend(utxo).unwrap();
        }
        let offers = utxos
            .iter()
            .map(|utxo| UnshieldedOffer::<Signature, Db> {
                inputs: vec![UtxoSpend {
                    value: utxo.utxo.value,
                    owner: night_key.verifying_key(),
                    type_: NIGHT,
                    intent_hash: to_ledger_intent_hash(utxo.utxo.id.intent_hash),
                    output_no: utxo.utxo.id.output_no,
                }]
                .into(),
                outputs: Vec::new().into(),
                signatures: Vec::<Signature>::new().into(),
            })
            .collect();
        (unshielded, offers)
    }

    fn booked() -> Booked {
        let mut rng = StdRng::seed_from_u64(7);
        let network = NetworkId::Undeployed;
        let (shielded, coins, shielded_offers) = shielded_spends(&mut rng, &network);
        let (unshielded, unshielded_offers) = unshielded_spends();

        let mut unshielded_offers = unshielded_offers.into_iter();
        let ttl = Timestamp::from_secs(3600);
        let intent_one = Intent::new(
            &mut rng,
            unshielded_offers.next(),
            unshielded_offers.next(),
            vec![],
            vec![],
            vec![],
            None,
            ttl,
        );
        let intent_two = Intent::new(
            &mut rng,
            None,
            unshielded_offers.next(),
            vec![],
            vec![],
            vec![],
            None,
            ttl,
        );

        let mut shielded_offers = shielded_offers.into_iter();
        let guaranteed = shielded_offers.next();
        let mut fallible = StorageHashMap::new();
        fallible = fallible.insert(1u16, shielded_offers.next().unwrap());
        fallible = fallible.insert(2u16, shielded_offers.next().unwrap());
        let mut intents = StorageHashMap::new();
        intents = intents.insert(1u16, intent_one);
        intents = intents.insert(2u16, intent_two);
        let tx: UnprovenTransaction =
            Transaction::new(network.as_str(), intents, guaranteed, fallible);

        let dust = DustState::init_empty(
            DustParameters {
                night_dust_ratio: 1_000,
                generation_decay_rate: 1,
                dust_grace_period: Duration::from_secs(60),
            },
            &DustSecretKey::derive_secret_key(&[0x02; 32]),
            network.clone(),
        );
        let state = FacadeState::new(shielded, unshielded, dust, network);
        assert_eq!(state.shielded.pending_spend_count(), 3);
        assert_eq!(state.unshielded.pending_len(), 3);
        Booked {
            tx,
            state,
            shielded: coins,
        }
    }

    fn is_pending(state: &FacadeState, coin: &QualifiedInfo) -> bool {
        let keys = ZswapSecretKeys::from(ZswapSeed::from([0x05; 32]));
        let info = CoinInfo::from(coin);
        state
            .shielded
            .is_pending_spend(&ShieldedState::nullifier_for(&info, &keys))
    }

    fn utxo_pending(state: &FacadeState, i: u8) -> bool {
        state
            .unshielded
            .pending()
            .any(|u| u.id() == UtxoId::new([0x10 + i; 32], 0))
    }

    #[test]
    fn a_failed_segment_releases_only_its_own_bookings() {
        let Booked {
            tx,
            state,
            shielded,
        } = booked();

        let released = state.revert_failed_segments(&tx, &[2]);

        assert!(is_pending(&released, &shielded[0]), "guaranteed coin stays");
        assert!(is_pending(&released, &shielded[1]), "segment 1 succeeded");
        assert!(!is_pending(&released, &shielded[2]), "segment 2 failed");
        assert!(utxo_pending(&released, 0), "guaranteed UTXO stays");
        assert!(utxo_pending(&released, 1), "segment 1 succeeded");
        assert!(!utxo_pending(&released, 2), "segment 2 failed");
        assert_eq!(released.unshielded.available_len(), 1);
    }

    #[test]
    fn a_failed_segment_keeps_its_intents_guaranteed_offer() {
        let Booked {
            tx,
            state,
            shielded,
        } = booked();

        let released = state.revert_failed_segments(&tx, &[1]);

        assert!(
            utxo_pending(&released, 0),
            "intent 1's guaranteed offer ran"
        );
        assert!(!utxo_pending(&released, 1));
        assert!(utxo_pending(&released, 2));
        assert!(is_pending(&released, &shielded[0]));
        assert!(!is_pending(&released, &shielded[1]));
        assert!(is_pending(&released, &shielded[2]));
    }

    #[test]
    fn unknown_and_repeated_segments_release_nothing_more() {
        let Booked { tx, state, .. } = booked();

        let released = state.revert_failed_segments(&tx, &[0, 2, 2, 9]);

        assert_eq!(released.shielded.pending_spend_count(), 2);
        assert_eq!(released.unshielded.pending_len(), 2);
        assert_eq!(released.unshielded.available_len(), 1);
    }

    #[test]
    fn release_ended_follows_the_chain_result() {
        let Booked {
            tx,
            state,
            shielded,
        } = booked();
        let result = |status, segments| PendingTransactionResult { status, segments };

        let success = state
            .clone()
            .release_ended(&tx, &result(PendingTransactionStatus::Success, vec![]));
        assert_eq!(success.shielded.pending_spend_count(), 3);
        assert_eq!(success.unshielded.pending_len(), 3);

        let partial = state.clone().release_ended(
            &tx,
            &result(
                PendingTransactionStatus::PartialSuccess,
                vec![
                    SegmentResult {
                        id: 0,
                        success: true,
                    },
                    SegmentResult {
                        id: 1,
                        success: false,
                    },
                    SegmentResult {
                        id: 2,
                        success: true,
                    },
                ],
            ),
        );
        assert!(!is_pending(&partial, &shielded[1]));
        assert!(!utxo_pending(&partial, 1));
        assert_eq!(partial.shielded.pending_spend_count(), 2);
        assert_eq!(partial.unshielded.pending_len(), 2);

        let failure = state.release_ended(&tx, &result(PendingTransactionStatus::Failure, vec![]));
        assert_eq!(failure.shielded.pending_spend_count(), 0);
        assert_eq!(failure.unshielded.pending_len(), 0);
        assert_eq!(failure.unshielded.available_len(), 3);
    }

    #[test]
    fn serialized_failed_segments_release_like_the_typed_transaction() {
        let Booked { tx, state, .. } = booked();
        let mut bytes = Vec::new();
        moonproof_ledger::serialize::tagged_serialize(&tx, &mut bytes).unwrap();

        let released = state
            .revert_serialized_failed_segments(&bytes, &[1, 2])
            .unwrap();

        assert_eq!(released.shielded.pending_spend_count(), 1);
        assert_eq!(released.unshielded.pending_len(), 1);
        assert!(utxo_pending(&released, 0));
    }
}