zingolib 0.0.1

Zingo backend library.
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
#![allow(dead_code)]

//! Tools to facilitate mocks for structs of external crates and general mocking utilities for testing

pub use sapling_crypto_note::SaplingCryptoNoteBuilder;

fn zaddr_from_seed(
    seed: [u8; 32],
) -> (
    ExtendedSpendingKey,
    PreparedIncomingViewingKey,
    PaymentAddress,
) {
    let extsk = ExtendedSpendingKey::master(&seed);
    let dfvk = extsk.to_diversifiable_full_viewing_key();
    let fvk = dfvk;
    let (_, addr) = fvk.default_address();

    (
        extsk,
        PreparedIncomingViewingKey::new(&fvk.fvk().vk.ivk()),
        addr,
    )
}

/// This is the "all-0" base case!
pub fn default_txid() -> zcash_primitives::transaction::TxId {
    zcash_primitives::transaction::TxId::from_bytes([0u8; 32])
}
/// This is the "all-0" base case!
pub fn default_zaddr() -> (
    ExtendedSpendingKey,
    PreparedIncomingViewingKey,
    PaymentAddress,
) {
    zaddr_from_seed([0u8; 32])
}

use rand::{Rng, rngs::OsRng};
use sapling_crypto::{
    PaymentAddress, note_encryption::PreparedIncomingViewingKey, zip32::ExtendedSpendingKey,
};

/// Any old OS randomness
pub fn random_txid() -> zcash_primitives::transaction::TxId {
    let mut rng = OsRng;
    let mut seed = [0u8; 32];
    rng.fill(&mut seed);
    zcash_primitives::transaction::TxId::from_bytes(seed)
}
/// Any old OS randomness
pub fn random_zaddr() -> (
    ExtendedSpendingKey,
    PreparedIncomingViewingKey,
    PaymentAddress,
) {
    let mut rng = OsRng;
    let mut seed = [0u8; 32];
    rng.fill(&mut seed);

    zaddr_from_seed(seed)
}

pub mod nullifier {
    //! Module for mocking nullifiers from [`sapling_crypto::Nullifier`] and [`orchard::note::Nullifier`]

    use crate::utils::build_method;

    macro_rules! build_assign_unique_nullifier {
        () => {
            /// Assign unique deterministic nullifier
            /// May not be unique if another nullifier is manually set to a value generated by this method
            pub(crate) fn assign_unique_nullifier(&mut self) -> &mut Self {
                if let Some(last) = self.unique_nullifier.last_mut() {
                    if *last == u8::MAX {
                        panic!("maximum unique nullifiers reached!");
                    }
                    *last += 1;
                }
                self.nullifier = Some(self.unique_nullifier);
                self
            }
        };
    }

    #[derive(Clone)]
    pub(crate) struct SaplingNullifierBuilder {
        unique_nullifier: [u8; 32],
        nullifier: Option<[u8; 32]>,
    }

    impl SaplingNullifierBuilder {
        /// Instantiate an empty builder.
        pub(crate) fn new() -> Self {
            SaplingNullifierBuilder {
                unique_nullifier: [0u8; 32],
                nullifier: None,
            }
        }

        // Set nullifier value
        build_method!(nullifier, [u8; 32]);
        build_assign_unique_nullifier!();

        /// Build the nullifier
        pub fn build(&self) -> sapling_crypto::Nullifier {
            sapling_crypto::Nullifier::from_slice(&self.nullifier.unwrap()).unwrap()
        }
    }

    impl Default for SaplingNullifierBuilder {
        fn default() -> Self {
            let mut builder = Self::new();
            builder.nullifier([0u8; 32]);
            builder
        }
    }

    #[derive(Clone)]
    pub(crate) struct OrchardNullifierBuilder {
        unique_nullifier: [u8; 32],
        nullifier: Option<[u8; 32]>,
    }

    impl OrchardNullifierBuilder {
        /// Instantiate an empty builder.
        pub(crate) fn new() -> Self {
            OrchardNullifierBuilder {
                unique_nullifier: [0u8; 32],
                nullifier: None,
            }
        }

        // Set nullifier value
        build_method!(nullifier, [u8; 32]);
        build_assign_unique_nullifier!();

        /// Build the nullifier
        pub fn build(&self) -> orchard::note::Nullifier {
            orchard::note::Nullifier::from_bytes(&self.nullifier.unwrap()).unwrap()
        }
    }

    impl Default for OrchardNullifierBuilder {
        fn default() -> Self {
            let mut builder = Self::new();
            builder.nullifier([0u8; 32]);
            builder
        }
    }
}

mod sapling_crypto_note {
    //! Sapling Note Mocker

    use sapling_crypto::Note;
    use sapling_crypto::PaymentAddress;
    use sapling_crypto::Rseed;
    use sapling_crypto::value::NoteValue;

    use crate::utils::build_method;

    use super::default_zaddr;

    /// A struct to build a mock [`sapling_crypto::Note`].
    #[derive(Clone)]
    pub struct SaplingCryptoNoteBuilder {
        recipient: Option<PaymentAddress>,
        value: Option<NoteValue>,
        rseed: Option<Rseed>,
    }

    impl SaplingCryptoNoteBuilder {
        /// Instantiate an empty builder.
        pub fn new() -> Self {
            SaplingCryptoNoteBuilder {
                recipient: None,
                value: None,
                rseed: None,
            }
        }

        // Methods to set each field
        build_method!(recipient, PaymentAddress);
        build_method!(value, NoteValue);
        build_method!(rseed, Rseed);

        /// For any old zcaddr!
        pub fn randomize_recipient(&mut self) -> &mut Self {
            let (_, _, address) = super::random_zaddr();
            self.recipient(address)
        }

        /// Build the note.
        pub fn build(self) -> Note {
            Note::from_parts(
                self.recipient.unwrap(),
                self.value.unwrap(),
                self.rseed.unwrap(),
            )
        }
    }
    impl Default for SaplingCryptoNoteBuilder {
        fn default() -> Self {
            let (_, _, address) = default_zaddr();
            let mut builder = Self::new();
            builder
                .recipient(address)
                .value(NoteValue::from_raw(200_000))
                .rseed(Rseed::AfterZip212([7; 32]));
            builder
        }
    }
}

pub mod orchard_note {
    //! Orchard Note Mocker

    use orchard::{
        Address, Note,
        keys::{FullViewingKey, SpendingKey},
        note::{RandomSeed, Rho},
        value::NoteValue,
    };
    use rand::{Rng, rngs::OsRng};
    use zip32::Scope;

    use crate::utils::build_method;

    /// A struct to build a mock [`orchard::Note`].
    #[derive(Clone)]
    pub struct OrchardCryptoNoteBuilder {
        recipient: Option<Address>,
        value: Option<NoteValue>,
        rho: Option<Rho>,
        random_seed: Option<RandomSeed>,
    }

    impl OrchardCryptoNoteBuilder {
        /// Instantiate an empty builder.
        pub fn new() -> Self {
            OrchardCryptoNoteBuilder {
                recipient: None,
                value: None,
                rho: None,
                random_seed: None,
            }
        }

        // Methods to set each field
        build_method!(recipient, Address);
        build_method!(value, NoteValue);
        build_method!(rho, Rho);
        build_method!(random_seed, RandomSeed);

        /// selects a default recipient address for the orchard note
        pub fn default_recipient(&mut self) -> &mut Self {
            let bytes = [0; 32];
            let sk = SpendingKey::from_bytes(bytes).unwrap();
            let fvk: FullViewingKey = (&sk).into();
            let recipient = fvk.address_at(0u32, Scope::External);

            self.recipient(recipient)
        }

        /// selects a random recipient address for the orchard note
        pub fn randomize_recipient(&mut self) -> &mut Self {
            let mut rng = OsRng;

            let sk = {
                loop {
                    let mut bytes = [0; 32];
                    rng.fill(&mut bytes);
                    let sk = SpendingKey::from_bytes(bytes);
                    if sk.is_some().into() {
                        break sk.unwrap();
                    }
                }
            };
            let fvk: FullViewingKey = (&sk).into();
            let recipient = fvk.address_at(0u32, Scope::External);

            self.recipient(recipient)
        }

        /// selects a random nullifier for the orchard note
        pub fn randomize_rho_and_rseed(&mut self) -> &mut Self {
            let mut rng = OsRng;

            let rho = {
                loop {
                    let mut bytes = [0u8; 32];
                    rng.fill(&mut bytes);
                    let rho = Rho::from_bytes(&bytes);
                    if rho.is_some().into() {
                        break rho.unwrap();
                    }
                }
            };

            let random_seed = {
                loop {
                    let mut bytes = [0; 32];
                    rng.fill(&mut bytes);
                    let random_seed = RandomSeed::from_bytes(bytes, &rho);
                    if random_seed.is_some().into() {
                        break random_seed.unwrap();
                    }
                }
            };

            self.rho(rho).random_seed(random_seed)
        }

        /// Build the note.
        pub fn build(&self) -> Note {
            Note::from_parts(
                self.recipient.unwrap(),
                self.value.unwrap(),
                self.rho.unwrap(),
                self.random_seed.unwrap(),
            )
            .unwrap()
        }
        /// generates a note from a provided
        /// 'random' value, to allow for
        // deterministic generation of notes
        pub fn non_random(nonce: [u8; 32]) -> Self {
            fn next_valid_thing<T>(mut nonce: [u8; 32], f: impl Fn([u8; 32]) -> Option<T>) -> T {
                let mut i = 0;
                loop {
                    if let Some(output) = f(nonce) {
                        return output;
                    } else {
                        nonce[i % 32] = nonce[i % 32].wrapping_add(1);
                        i += 1;
                    }
                }
            }

            let rho = next_valid_thing(nonce, |bytes| Option::from(Rho::from_bytes(&bytes)));
            let rseed = next_valid_thing(nonce, |bytes| {
                Option::from(RandomSeed::from_bytes(bytes, &rho))
            });

            Self::new()
                .default_recipient()
                .value(NoteValue::from_raw(800_000))
                .rho(rho)
                .random_seed(rseed)
                .clone()
        }
    }
    /// mocks a random orchard note
    impl Default for OrchardCryptoNoteBuilder {
        fn default() -> Self {
            Self::new()
                .default_recipient()
                .randomize_rho_and_rseed()
                .value(NoteValue::from_raw(800_000))
                .clone()
        }
    }
}

pub mod proposal {
    //! Module for mocking structs from [`zcash_client_backend::proposal`]

    use std::collections::BTreeMap;

    use nonempty::NonEmpty;

    use incrementalmerkletree::Position;
    use pepper_sync::wallet::OutputId;
    use sapling_crypto::Rseed;
    use sapling_crypto::value::NoteValue;
    use zcash_address::ZcashAddress;
    use zcash_client_backend::fees::TransactionBalance;
    use zcash_client_backend::proposal::{Proposal, ShieldedInputs, Step, StepOutput};
    use zcash_client_backend::wallet::{ReceivedNote, WalletTransparentOutput};
    use zcash_client_backend::zip321::{Payment, TransactionRequest};
    use zcash_primitives::consensus::BlockHeight;
    use zcash_primitives::transaction::fees::zip317::FeeRule;
    use zcash_protocol::value::Zatoshis;
    use zcash_protocol::{PoolType, ShieldedProtocol};

    use super::{default_txid, default_zaddr};
    use crate::utils::conversion::address_from_str;
    use crate::utils::{build_method, build_method_push};
    use crate::wallet::output::OutputRef;

    /// Provides a builder for constructing a mock [`zcash_client_backend::proposal::Proposal`].
    ///
    /// # Examples
    ///
    /// ```
    /// use zingolib::mocks::proposal::ProposalBuilder;
    ///
    /// let proposal = ProposalBuilder::default().build();
    /// ````
    pub struct ProposalBuilder {
        fee_rule: Option<FeeRule>,
        min_target_height: Option<BlockHeight>,
        steps: Option<NonEmpty<Step<OutputRef>>>,
    }

    #[allow(dead_code)]
    impl ProposalBuilder {
        /// Constructs an empty builder.
        pub fn new() -> Self {
            ProposalBuilder {
                fee_rule: None,
                min_target_height: None,
                steps: None,
            }
        }

        build_method!(fee_rule, FeeRule);
        build_method!(min_target_height, BlockHeight);
        build_method!(steps, NonEmpty<Step<OutputRef>>);

        /// Builds after all fields have been set.
        pub fn build(self) -> Proposal<FeeRule, OutputRef> {
            let step = self.steps.unwrap().first().clone();
            Proposal::single_step(
                step.transaction_request().clone(),
                step.payment_pools().clone(),
                step.transparent_inputs().to_vec(),
                step.shielded_inputs().cloned(),
                step.balance().clone(),
                self.fee_rule.unwrap(),
                self.min_target_height.unwrap(),
                step.is_shielding(),
            )
            .unwrap()
        }
    }

    impl Default for ProposalBuilder {
        /// Constructs a default builder.
        fn default() -> Self {
            let mut builder = ProposalBuilder::new();
            builder
                .fee_rule(FeeRule::standard())
                .min_target_height(BlockHeight::from_u32(1))
                .steps(NonEmpty::singleton(StepBuilder::default().build()));
            builder
        }
    }

    /// Provides a builder for constructing a mock [`zcash_client_backend::proposal::Step`].
    ///
    /// # Examples
    ///
    /// ```
    /// use zingolib::mocks::proposal::StepBuilder;
    ///
    /// let step = StepBuilder::default().build();
    /// ````
    pub struct StepBuilder {
        transaction_request: Option<TransactionRequest>,
        payment_pools: Option<BTreeMap<usize, PoolType>>,
        transparent_inputs: Option<Vec<WalletTransparentOutput>>,
        shielded_inputs: Option<Option<ShieldedInputs<OutputRef>>>,
        prior_step_inputs: Option<Vec<StepOutput>>,
        balance: Option<TransactionBalance>,
        is_shielding: Option<bool>,
    }

    impl StepBuilder {
        /// Constructs an empty builder.
        pub fn new() -> Self {
            StepBuilder {
                transaction_request: None,
                payment_pools: None,
                transparent_inputs: None,
                shielded_inputs: None,
                prior_step_inputs: None,
                balance: None,
                is_shielding: None,
            }
        }

        build_method!(transaction_request, TransactionRequest);
        build_method!(payment_pools, BTreeMap<usize, PoolType>
        );
        build_method!(transparent_inputs, Vec<WalletTransparentOutput>);
        build_method!(shielded_inputs, Option<ShieldedInputs<OutputRef>>);
        build_method!(prior_step_inputs, Vec<StepOutput>);
        build_method!(balance, TransactionBalance);
        build_method!(is_shielding, bool);

        /// Builds after all fields have been set.
        pub fn build(self) -> Step<OutputRef> {
            Step::from_parts(
                &[],
                self.transaction_request.unwrap(),
                self.payment_pools.unwrap(),
                self.transparent_inputs.unwrap(),
                self.shielded_inputs.unwrap(),
                self.prior_step_inputs.unwrap(),
                self.balance.unwrap(),
                self.is_shielding.unwrap(),
            )
            .unwrap()
        }
    }

    impl Default for StepBuilder {
        /// Constructs a default builder.
        fn default() -> Self {
            let txid = default_txid();
            let (_, _, address) = default_zaddr();
            let note = sapling_crypto::Note::from_parts(
                address,
                NoteValue::from_raw(120_000),
                Rseed::AfterZip212([7; 32]),
            );
            let mut payment_pools = BTreeMap::new();
            payment_pools.insert(0, PoolType::Shielded(ShieldedProtocol::Orchard));

            let mut builder = Self::new();
            builder
                .transaction_request(TransactionRequestBuilder::default().build())
                .payment_pools(payment_pools)
                .transparent_inputs(vec![])
                // .shielded_inputs(None)
                .shielded_inputs(Some(ShieldedInputs::from_parts(
                    BlockHeight::from_u32(1),
                    NonEmpty::singleton(ReceivedNote::from_parts(
                        OutputRef::new(OutputId::new(txid, 0), PoolType::SAPLING),
                        txid,
                        0,
                        zcash_client_backend::wallet::Note::Sapling(note),
                        zip32::Scope::External,
                        Position::from(1),
                    )),
                )))
                .prior_step_inputs(vec![])
                .balance(TransactionBalance::new(vec![], Zatoshis::const_from_u64(20_000)).unwrap())
                .is_shielding(false);
            builder
        }
    }

    /// Provides a builder for constructing a mock [`zcash_client_backend::zip321::TransactionRequest`].
    ///
    /// # Examples
    ///
    /// ```
    /// use zingolib::mocks::proposal::TransactionRequestBuilder;
    ///
    /// let transaction_request = TransactionRequestBuilder::default().build();
    /// ````
    pub struct TransactionRequestBuilder {
        payments: Vec<Payment>,
    }

    impl TransactionRequestBuilder {
        /// Constructs an empty builder.
        pub fn new() -> Self {
            TransactionRequestBuilder { payments: vec![] }
        }

        build_method_push!(payments, Payment);

        /// Builds after all fields have been set.
        pub fn build(self) -> TransactionRequest {
            TransactionRequest::new(self.payments).unwrap()
        }
    }

    impl Default for TransactionRequestBuilder {
        /// Constructs a default builder.
        fn default() -> Self {
            let mut builder = Self::new();
            builder.payments(PaymentBuilder::default().build());
            builder
        }
    }

    /// Provides a builder for constructing a mock [`zcash_client_backend::zip321::Payment`].
    ///
    /// # Examples
    ///
    /// ```
    /// use zingolib::mocks::proposal::PaymentBuilder;
    ///
    /// let payment = PaymentBuilder::default().build();
    /// ````
    pub struct PaymentBuilder {
        recipient_address: Option<ZcashAddress>,
        amount: Option<Zatoshis>,
    }

    impl PaymentBuilder {
        /// Constructs an empty builder.
        pub fn new() -> Self {
            PaymentBuilder {
                recipient_address: None,
                amount: None,
            }
        }

        build_method!(recipient_address, ZcashAddress);
        build_method!(amount, Zatoshis);

        /// Builds after all fields have been set.
        pub fn build(&self) -> Payment {
            Payment::without_memo(
                self.recipient_address.clone().unwrap(),
                self.amount.unwrap(),
            )
        }
    }

    impl Default for PaymentBuilder {
        /// Constructs a default builder.
        fn default() -> Self {
            let mut builder = Self::new();
            builder
                .recipient_address(
                    address_from_str(testvectors::REG_O_ADDR_FROM_ABANDONART).unwrap(),
                )
                .amount(Zatoshis::from_u64(100_000).unwrap());
            builder
        }
    }
}