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
//! these functions are each meant to be 'test-in-a-box'
//! simply plug in a mock server as a chain conductor and provide some values

use pepper_sync::wallet::SaplingNote;
use zcash_primitives::transaction::fees::zip317::MARGINAL_FEE;
use zcash_protocol::{PoolType, ShieldedProtocol};

use crate::testutils::chain_generics::conduct_chain::ConductChain;
use crate::testutils::chain_generics::with_assertions;
use crate::testutils::fee_tables;
use crate::testutils::lightclient::from_inputs;
use crate::testutils::lightclient::get_base_address;
use crate::testutils::timestamped_test_log;
use crate::wallet::data::summaries::SelfSendValueTransfer;
use crate::wallet::data::summaries::SentValueTransfer;
use crate::wallet::data::summaries::ValueTransferKind;
use crate::wallet::output::query::OutputPoolQuery;
use crate::wallet::output::query::OutputQuery;
use crate::wallet::output::query::OutputSpendStatusQuery;

/// Fixture for testing various vt transactions
pub async fn create_various_value_transfers<CC>()
where
    CC: ConductChain,
{
    let mut environment = CC::setup().await;
    let mut sender = environment.fund_client_orchard(250_000).await;
    let sender_orchard_addr =
        get_base_address(&sender, PoolType::Shielded(ShieldedProtocol::Orchard)).await;
    let sender_sapling_addr =
        get_base_address(&sender, PoolType::Shielded(ShieldedProtocol::Sapling)).await;
    let sender_taddr = get_base_address(&sender, PoolType::Transparent).await;
    let send_value_for_recipient = 23_000;
    let send_value_self = 17_000;

    println!("client is ready to send");

    let mut recipient = environment.create_client();
    dbg!("TEST 1");
    with_assertions::propose_send_bump_sync_all_recipients(
        &mut environment,
        &mut sender,
        vec![
            (
                &get_base_address(&recipient, PoolType::Shielded(ShieldedProtocol::Orchard)).await,
                send_value_for_recipient,
                Some("Orchard sender to recipient"),
            ),
            (
                &sender_sapling_addr,
                send_value_self,
                Some("Orchard sender to self"),
            ),
            (&sender_taddr, send_value_self, None),
        ],
        vec![&mut recipient],
        false,
    )
    .await
    .unwrap();

    assert_eq!(sender.sorted_value_transfers(true).await.unwrap().len(), 3);

    assert!(
        sender
            .sorted_value_transfers(false)
            .await
            .unwrap()
            .iter()
            .any(|vt| { vt.kind() == ValueTransferKind::Received })
    );

    assert!(
        sender
            .sorted_value_transfers(false)
            .await
            .unwrap()
            .iter()
            .any(|vt| { vt.kind() == ValueTransferKind::Sent(SentValueTransfer::Send) })
    );

    assert!(
        sender
            .sorted_value_transfers(false)
            .await
            .unwrap()
            .iter()
            .any(|vt| {
                vt.kind()
                    == ValueTransferKind::Sent(SentValueTransfer::SendToSelf(
                        SelfSendValueTransfer::MemoToSelf,
                    ))
            })
    );

    assert_eq!(
        recipient.sorted_value_transfers(true).await.unwrap().len(),
        1
    );

    dbg!("TEST 2");
    with_assertions::propose_send_bump_sync_all_recipients(
        &mut environment,
        &mut sender,
        vec![(&sender_orchard_addr, send_value_self, None)],
        vec![],
        false,
    )
    .await
    .unwrap();

    assert_eq!(sender.sorted_value_transfers(true).await.unwrap().len(), 4);
    assert_eq!(
        sender.sorted_value_transfers(true).await.unwrap()[0].kind(),
        ValueTransferKind::Sent(SentValueTransfer::SendToSelf(SelfSendValueTransfer::Basic))
    );

    with_assertions::assure_propose_shield_bump_sync(&mut environment, &mut sender, false)
        .await
        .unwrap();
    assert_eq!(sender.sorted_value_transfers(true).await.unwrap().len(), 5);
    assert_eq!(
        sender.sorted_value_transfers(true).await.unwrap()[0].kind(),
        ValueTransferKind::Sent(SentValueTransfer::SendToSelf(SelfSendValueTransfer::Shield))
    );
}

/// sends back and forth several times, including sends to transparent
pub async fn send_shield_cycle<CC>(n: u64)
where
    CC: ConductChain,
{
    let mut environment = CC::setup().await;
    let primary_fund = 1_000_000;
    let mut primary = environment.fund_client_orchard(primary_fund).await;

    let mut secondary = environment.create_client();
    let secondary_taddr = get_base_address(&secondary, PoolType::Transparent).await;

    for _ in 0..n {
        let (recorded_fee, recorded_value, recorded_change) =
            with_assertions::propose_send_bump_sync_all_recipients(
                &mut environment,
                &mut primary,
                vec![
                    (&secondary_taddr, 100_000, None),
                    (&secondary_taddr, 4_000, None),
                ],
                vec![&mut secondary],
                false,
            )
            .await
            .unwrap();
        assert_eq!(
            (recorded_fee, recorded_value, recorded_change),
            (MARGINAL_FEE.into_u64() * 4, recorded_value, recorded_change)
        );

        let (recorded_fee, recorded_value) = with_assertions::assure_propose_shield_bump_sync(
            &mut environment,
            &mut secondary,
            false,
        )
        .await
        .unwrap();
        assert_eq!(
            (recorded_fee, recorded_value),
            (MARGINAL_FEE.into_u64() * 3, 100_000 - recorded_fee)
        );

        let (recorded_fee, recorded_value, recorded_change) =
            with_assertions::propose_send_bump_sync_all_recipients(
                &mut environment,
                &mut secondary,
                vec![(
                    &get_base_address(&primary, PoolType::Shielded(ShieldedProtocol::Orchard))
                        .await,
                    50_000,
                    None,
                )],
                vec![&mut primary],
                false,
            )
            .await
            .unwrap();
        assert_eq!(
            (recorded_fee, recorded_value, recorded_change),
            (MARGINAL_FEE.into_u64() * 2, 50_000, recorded_change)
        );
    }
}

/// overlooks a bunch of dust inputs to find a pair of inputs marginally big enough to send
pub async fn ignore_dust_inputs<CC>()
where
    CC: ConductChain,
{
    let mut environment = CC::setup().await;

    let mut primary = environment.fund_client_orchard(120_000).await;
    let mut secondary = environment.create_client();
    let secondary_sapling_addr =
        get_base_address(&secondary, PoolType::Shielded(ShieldedProtocol::Sapling)).await;
    let secondary_orchard_addr =
        get_base_address(&secondary, PoolType::Shielded(ShieldedProtocol::Orchard)).await;

    // send a bunch of dust
    let (recorded_fee, recorded_value, recorded_change) =
        with_assertions::propose_send_bump_sync_all_recipients(
            &mut environment,
            &mut primary,
            vec![
                (&secondary_orchard_addr, 1_000, None),
                (&secondary_orchard_addr, 1_000, None),
                (&secondary_orchard_addr, 1_000, None),
                (&secondary_orchard_addr, 1_000, None),
                (&secondary_orchard_addr, 15_000, None),
                (&secondary_sapling_addr, 1_000, None),
                (&secondary_sapling_addr, 1_000, None),
                (&secondary_sapling_addr, 1_000, None),
                (&secondary_sapling_addr, 1_000, None),
                (&secondary_sapling_addr, 15_000, None),
            ],
            vec![&mut secondary],
            false,
        )
        .await
        .unwrap();
    assert_eq!(
        (recorded_fee, recorded_value, recorded_change),
        (
            11 * MARGINAL_FEE.into_u64(),
            recorded_value,
            recorded_change
        )
    );

    // combine the only valid sapling note with the only valid orchard note to send
    let (recorded_fee, recorded_value, recorded_change) =
        with_assertions::propose_send_bump_sync_all_recipients(
            &mut environment,
            &mut secondary,
            vec![(
                &get_base_address(&primary, PoolType::Shielded(ShieldedProtocol::Orchard)).await,
                10_000,
                None,
            )],
            vec![&mut primary],
            false,
        )
        .await
        .unwrap();
    assert_eq!(
        (recorded_fee, recorded_value, recorded_change),
        (4 * MARGINAL_FEE.into_u64(), 10_000, recorded_change)
    );
}

/// In order to fund a transaction multiple notes may be selected and consumed.
/// The algorithm selects the smallest covering note(s).
pub async fn note_selection_order<CC>()
where
    CC: ConductChain,
{
    // toDo: proptest different values for these first two variables
    let number_of_notes = 4;
    let expected_value_from_transaction_2: u64 = 40_000;

    let transaction_1_values = (1..=number_of_notes).map(|n| n * 10_000);

    let expected_fee_for_transaction_1 = (number_of_notes + 2) * MARGINAL_FEE.into_u64();
    let expected_value_from_transaction_1: u64 = transaction_1_values.clone().sum();

    let mut environment = CC::setup().await;
    let mut primary = environment
        .fund_client_orchard(expected_fee_for_transaction_1 + expected_value_from_transaction_1)
        .await;
    let mut secondary = environment.create_client();

    // Send number_of_notes transfers in increasing 10_000 zat increments
    let secondary_sapling_addr =
        get_base_address(&secondary, PoolType::Shielded(ShieldedProtocol::Sapling)).await;
    let (recorded_fee, recorded_value, recorded_change) =
        with_assertions::propose_send_bump_sync_all_recipients(
            &mut environment,
            &mut primary,
            transaction_1_values
                .map(|value| (secondary_sapling_addr.as_str(), value, None))
                .collect(),
            vec![&mut secondary],
            false,
        )
        .await
        .unwrap();
    assert_eq!(
        (recorded_fee, recorded_value, recorded_change),
        (
            expected_fee_for_transaction_1,
            recorded_value,
            recorded_change
        )
    );

    let expected_orchard_contribution_for_transaction_2 = 2;

    // calculate what will be spent
    let mut expected_highest_unselected: i64 = 10_000 * number_of_notes as i64;
    let mut expected_inputs_for_transaction_2 = 0;
    let mut max_unselected_value_for_transaction_2: i64 = (expected_value_from_transaction_2
        + expected_orchard_contribution_for_transaction_2)
        as i64;
    loop {
        // add an input
        expected_inputs_for_transaction_2 += 1;
        max_unselected_value_for_transaction_2 += MARGINAL_FEE.into_u64() as i64;
        max_unselected_value_for_transaction_2 -= expected_highest_unselected;
        expected_highest_unselected -= 10_000;

        if max_unselected_value_for_transaction_2 <= 0 {
            // met target
            break;
        }
        if expected_highest_unselected <= 0 {
            // did not meet target. expect error on send
            break;
        }
    }
    let expected_fee_for_transaction_2 = (expected_inputs_for_transaction_2
        + expected_orchard_contribution_for_transaction_2)
        * MARGINAL_FEE.into_u64();

    // the second client selects notes to cover the transaction.
    let primary_orchard_addr =
        get_base_address(&primary, PoolType::Shielded(ShieldedProtocol::Orchard)).await;
    let (recorded_fee, recorded_value, recorded_change) =
        with_assertions::propose_send_bump_sync_all_recipients(
            &mut environment,
            &mut secondary,
            vec![(
                &primary_orchard_addr,
                expected_value_from_transaction_2,
                None,
            )],
            vec![&mut primary],
            false,
        )
        .await
        .unwrap();
    assert_eq!(
        (recorded_fee, recorded_value, recorded_change),
        (
            expected_fee_for_transaction_2,
            expected_value_from_transaction_2,
            0
        )
    );

    let received_change_from_transaction_2 = secondary
        .wallet
        .lock()
        .await
        .sum_queried_output_values(OutputQuery {
            spend_status: OutputSpendStatusQuery::only_unspent(),
            pools: OutputPoolQuery::one_pool(PoolType::Shielded(ShieldedProtocol::Orchard)),
        });
    // if 10_000 or more change, would have used a smaller note
    assert!(received_change_from_transaction_2 < 10_000);

    let secondary_wallet = secondary.wallet.lock().await;
    let spent_sapling_outputs = secondary_wallet
        .wallet_outputs::<SaplingNote>()
        .into_iter()
        .filter(|&output| {
            secondary_wallet
                .output_spend_status(output)
                .is_confirmed_spent()
        })
        .collect::<Vec<_>>();
    assert_eq!(
        spent_sapling_outputs.len(),
        expected_inputs_for_transaction_2 as usize
    );
}

/// the simplest test that sends from a specific shielded pool to another specific pool. error variant.
pub async fn shpool_to_pool_insufficient_error<CC>(
    shpool: ShieldedProtocol,
    pool: PoolType,
    underflow_amount: u64,
) where
    CC: ConductChain,
{
    let mut environment = CC::setup().await;

    let mut primary = environment.fund_client_orchard(1_000_000).await;
    let mut secondary = environment.create_client();
    let secondary_addr = get_base_address(&secondary, PoolType::Shielded(shpool)).await;

    let expected_fee = fee_tables::one_to_one(Some(shpool), pool, true);
    let secondary_fund = 100_000 + expected_fee - underflow_amount;
    with_assertions::propose_send_bump_sync_all_recipients(
        &mut environment,
        &mut primary,
        vec![(&secondary_addr, secondary_fund, None)],
        vec![&mut secondary],
        false,
    )
    .await
    .unwrap();

    let tertiary = environment.create_client();

    let tertiary_fund = 100_000;
    assert_eq!(
        from_inputs::propose(
            &mut secondary,
            vec![(
                tertiary
                    .wallet
                    .lock()
                    .await
                    .get_first_address(pool)
                    .unwrap()
                    .as_str(),
                tertiary_fund,
                None,
            )],
        )
        .await
        .unwrap_err()
        .to_string(),
        format!(
            "Insufficient balance (have {}, need {} including fee)",
            secondary_fund,
            tertiary_fund + expected_fee
        )
    );
}

/// the simplest test that sends from a specific shielded pool to another specific pool. also known as simpool.
pub async fn to_pool_unfunded_error<CC>(pool: PoolType, try_amount: u64)
where
    CC: ConductChain,
{
    let mut environment = CC::setup().await;

    let mut secondary = environment.create_client();
    let tertiary = environment.create_client();

    secondary.sync_and_await().await.unwrap();

    let expected_fee = fee_tables::one_to_one(None, pool, true);

    assert_eq!(
        from_inputs::propose(
            &mut secondary,
            vec![(
                tertiary
                    .wallet
                    .lock()
                    .await
                    .get_first_address(pool)
                    .unwrap()
                    .as_str(),
                try_amount,
                None,
            )],
        )
        .await
        .unwrap_err()
        .to_string(),
        format!(
            "Insufficient balance (have {}, need {} including fee)",
            0,
            try_amount + expected_fee
        )
    );
}

/// the simplest test that sends from a specific shielded pool to another specific pool. also known as simpool.
pub async fn any_source_sends_to_any_receiver<CC>(
    shpool: ShieldedProtocol,
    pool: PoolType,
    receiver_value: u64,
    change: u64,
    test_mempool: bool,
) where
    CC: ConductChain,
{
    timestamped_test_log(format!("starting a {:?} to {} test", shpool, pool).as_str());

    let mut environment = CC::setup().await;

    let mut primary = environment.create_faucet().await;
    let mut secondary = environment.create_client();
    let mut tertiary = environment.create_client();

    let expected_fee = fee_tables::one_to_one(Some(shpool), pool, true);

    with_assertions::propose_send_bump_sync_all_recipients(
        &mut environment,
        &mut primary,
        vec![(
            &get_base_address(&secondary, PoolType::Shielded(shpool)).await,
            receiver_value + change + expected_fee,
            None,
        )],
        vec![&mut secondary],
        test_mempool,
    )
    .await
    .unwrap();

    let (recorded_fee, recorded_value, recorded_change) =
        with_assertions::propose_send_bump_sync_all_recipients(
            &mut environment,
            &mut secondary,
            vec![(
                &get_base_address(&tertiary, pool).await,
                receiver_value,
                None,
            )],
            vec![&mut tertiary],
            test_mempool,
        )
        .await
        .unwrap();
    assert_eq!(
        (recorded_fee, recorded_value, recorded_change),
        (expected_fee, receiver_value, change)
    );
}