zingolib 7.0.0

Zingo backend library.
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
//! Zingo-Testutils
//! Holds functionality for zingo testing

#![warn(missing_docs)]

use std::num::NonZeroU32;
use std::{io::Read, string::String, time::Duration};

use pepper_sync::config::{PerformanceLevel, SyncConfig, TransparentAddressDiscovery};
use pepper_sync::keys::decode_address;
use zcash_address::unified::Fvk;
use zcash_keys::address::UnifiedAddress;
use zcash_keys::encoding::AddressCodec;
use zcash_protocol::consensus::NetworkConstants;
use zcash_protocol::{PoolType, ShieldedPool, consensus};
use zingo_common_components::protocol::{ActivationHeights, ActivationHeightsBuilder};

use crate::lightclient::LightClient;
use crate::lightclient::error::LightClientError;
use crate::wallet::WalletSettings;
use crate::wallet::keys::unified::UnifiedKeyStore;
use crate::wallet::output::SpendStatus;
use crate::wallet::summary::data::{
    BasicCoinSummary, BasicNoteSummary, OutgoingNoteSummary, TransactionSummary,
};

/// The era the in-process tests run under: every network upgrade through
/// NU7 active at height 1, so a mock chain validates the branch id mainnet
/// carries from the NU7 activation. The regtest tier's era is
/// `zingolib_testutils::scenarios::default_test_activation_heights`, which
/// leaves NU7 off until an indexer serves it.
#[must_use]
pub fn mock_activation_heights() -> ActivationHeights {
    mock_activation_heights_with(|era| era)
}

/// The in-process era with `adjust` applied to its builder, for a test that
/// moves one activation to make a boundary or switches one off.
pub fn mock_activation_heights_with(
    adjust: impl FnOnce(ActivationHeightsBuilder) -> ActivationHeightsBuilder,
) -> ActivationHeights {
    const GENESIS_SUCCESSOR: Option<u32> = Some(1);
    adjust(
        ActivationHeights::builder()
            .set_overwinter(GENESIS_SUCCESSOR)
            .set_sapling(GENESIS_SUCCESSOR)
            .set_blossom(GENESIS_SUCCESSOR)
            .set_heartwood(GENESIS_SUCCESSOR)
            .set_canopy(GENESIS_SUCCESSOR)
            .set_nu5(GENESIS_SUCCESSOR)
            .set_nu6(GENESIS_SUCCESSOR)
            .set_nu6_1(GENESIS_SUCCESSOR)
            .set_nu6_2(GENESIS_SUCCESSOR)
            .set_nu6_3(GENESIS_SUCCESSOR)
            .set_nu7(GENESIS_SUCCESSOR),
    )
    .build()
}

/// The in-process era with NU6.3 activating at `activation` and NU7 switched off.
#[must_use]
pub fn mock_activation_heights_deferring_nu6_3(activation: u32) -> ActivationHeights {
    mock_activation_heights_with(|era| era.set_nu6_3(Some(activation)).set_nu7(None))
}

pub mod assertions;
pub mod chain_generics;
pub mod fee_tables;
pub mod lightclient;
pub mod macros;
pub mod migration;
pub mod mock_indexer;
pub mod paths;
pub mod socks5_relay;
pub mod synthetic_wallet;

// Re-export test dependencies for convenience
pub use portpicker;
pub use tempfile;

/// Default wallet settings for testing
pub fn default_test_wallet_settings() -> WalletSettings {
    WalletSettings {
        sync_config: SyncConfig {
            transparent_address_discovery: TransparentAddressDiscovery::minimal(),
            performance_level: PerformanceLevel::High,
            shutdown_on_completion: true,
        },
        min_confirmations: NonZeroU32::try_from(1).expect("hard-coded non-zero integer"),
    }
}

/// TODO: Add Doc Comment Here!
#[must_use]
pub fn build_fvks_from_unified_keystore(unified_keystore: &UnifiedKeyStore) -> [Fvk; 3] {
    let orchard_vk: orchard::keys::FullViewingKey = unified_keystore.try_into().unwrap();
    let sapling_vk: sapling_crypto::zip32::DiversifiableFullViewingKey =
        unified_keystore.try_into().unwrap();
    let transparent_vk: zcash_transparent::keys::AccountPubKey =
        unified_keystore.try_into().unwrap();

    let mut transparent_vk_bytes = [0u8; 65];
    transparent_vk_bytes.copy_from_slice(&transparent_vk.serialize());

    [
        Fvk::Orchard(orchard_vk.to_bytes()),
        Fvk::Sapling(sapling_vk.to_bytes()),
        Fvk::P2pkh(transparent_vk_bytes),
    ]
}

/// TODO: doc comment
pub async fn assert_transaction_summary_exists(
    lightclient: &LightClient,
    expected: &TransactionSummary,
) {
    assert!(
        check_transaction_summary_exists(lightclient, expected).await,
        "wallet summaries: {}\n\n\nexpected: {}\n\n\n",
        lightclient.transaction_summaries(false).await.unwrap(),
        expected,
    );
}

/// TODO: doc comment
pub async fn check_transaction_summary_exists(
    lightclient: &LightClient,
    transaction_summary: &TransactionSummary,
) -> bool {
    lightclient
        .transaction_summaries(false)
        .await
        .unwrap()
        .iter()
        .any(|wallet_summary| {
            check_transaction_summary_equality(wallet_summary, transaction_summary)
        })
}

/// TODO: doc comment
pub fn assert_transaction_summary_equality(
    observed: &TransactionSummary,
    expected: &TransactionSummary,
) {
    assert!(
        check_transaction_summary_equality(observed, expected),
        "observed: {observed}\n\n\nexpected: {expected}\n\n\n",
    );
}

/// Transaction creation involves using a nonce, which means a non-deterministic txid.
/// Datetime is also based on time of run.
/// Check all the other fields
///   TODO:  seed random numbers in tests deterministically
#[must_use]
pub fn check_transaction_summary_equality(
    first: &TransactionSummary,
    second: &TransactionSummary,
) -> bool {
    first.status == second.status
        && first.blockheight == second.blockheight
        && first.kind == second.kind
        && first.value == second.value
        && first.fee == second.fee
        && first.zec_price == second.zec_price
        && check_note_summary_equality(&first.orchard_notes, &second.orchard_notes)
        && check_note_summary_equality(&first.sapling_notes, &second.sapling_notes)
        && check_transparent_coin_summary_equality(
            &first.transparent_coins,
            &second.transparent_coins,
        )
        && check_outgoing_note_summary_equality(
            &first.outgoing_orchard_notes,
            &second.outgoing_orchard_notes,
        )
        && check_outgoing_note_summary_equality(
            &first.outgoing_sapling_notes,
            &second.outgoing_sapling_notes,
        )
}

fn check_note_summary_equality(first: &[BasicNoteSummary], second: &[BasicNoteSummary]) -> bool {
    if first.len() != second.len() {
        return false;
    }
    for i in 0..first.len() {
        if !(first[i].value == second[i].value
            && check_spend_status_equality(first[i].spend_status, second[i].spend_status)
            && first[i].memo == second[i].memo)
        {
            return false;
        }
    }
    true
}

fn check_outgoing_note_summary_equality(
    first: &[OutgoingNoteSummary],
    second: &[OutgoingNoteSummary],
) -> bool {
    if first.len() != second.len() {
        return false;
    }
    for i in 0..first.len() {
        if !(first[i].value == second[i].value
            && first[i].memo == second[i].memo
            && first[i].recipient == second[i].recipient
            && first[i].recipient_unified_address == second[i].recipient_unified_address)
            && first[i].account_id == second[i].account_id
            && first[i].scope == second[i].scope
        {
            return false;
        }
    }
    true
}

/// TODO: doc comment
fn check_transparent_coin_summary_equality(
    first: &[BasicCoinSummary],
    second: &[BasicCoinSummary],
) -> bool {
    if first.len() != second.len() {
        return false;
    }
    for i in 0..first.len() {
        if !(first[i].value == second[i].value
            && check_spend_status_equality(first[i].spend_summary, second[i].spend_summary))
        {
            return false;
        }
    }
    true
}

fn check_spend_status_equality(first: SpendStatus, second: SpendStatus) -> bool {
    matches!(
        (first, second),
        (SpendStatus::Unspent, SpendStatus::Unspent)
            | (SpendStatus::Spent(_), SpendStatus::Spent(_))
            | (
                SpendStatus::TransmittedSpent(_),
                SpendStatus::TransmittedSpent(_)
            )
            | (SpendStatus::MempoolSpent(_), SpendStatus::MempoolSpent(_))
    )
}

/// Will hang if chain does not reach `target_block_height`
pub async fn sync_to_target_height(
    client: &mut LightClient,
    target_block_height: u32,
) -> Result<(), LightClientError> {
    // sync first so ranges exist for the `fully_scanned_height` call
    client.sync_and_await().await?;
    while u32::from(
        client
            .wallet()
            .read()
            .await
            .sync_state
            .fully_scanned_height()
            .unwrap(),
    ) < target_block_height
    {
        tokio::time::sleep(Duration::from_millis(500)).await;
        client.sync_and_await().await?;
    }
    Ok(())
}

/// TODO: Add Doc Comment Here!
pub struct RecordingReader<Reader> {
    from: Reader,
    read_lengths: Vec<usize>,
}
impl<T> Read for RecordingReader<T>
where
    T: Read,
{
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let for_info = self.from.read(buf)?;
        log::info!("{for_info:?}");
        self.read_lengths.push(for_info);
        Ok(for_info)
    }
}

/// Number of notes created and consumed in a transaction.
#[derive(Debug)]
pub struct TxNotesCount {
    /// Transparent notes in transaction.
    pub transparent_tx_notes: usize,
    /// Sapling notes in transaction.
    pub sapling_tx_notes: usize,
    /// Orchard notes in transaction.
    pub orchard_tx_notes: usize,
}

/// Number of logical actions in a transaction
#[derive(Debug)]
pub struct TxActionsCount {
    /// Transparent actions in transaction
    pub transparent_tx_actions: usize,
    /// Sapling actions in transaction
    pub sapling_tx_actions: usize,
    /// Orchard notes in transaction
    pub orchard_tx_actions: usize,
}

// FIXME: zingo2 rewrite with wallet data or note summaries
// /// Returns number of notes used as inputs for txid as TxNotesCount (transparent_notes, sapling_notes, orchard_notes).
// pub async fn tx_inputs(client: &LightClient, txid: &str) -> TxNotesCount {
//     let notes = client.do_list_notes(true).await;

//     let mut transparent_notes = 0;
//     let mut sapling_notes = 0;
//     let mut orchard_notes = 0;

//     if let JsonValue::Array(spent_utxos) = &notes["spent_utxos"] {
//         for utxo in spent_utxos {
//             if utxo["spent"] == txid || utxo["pending_spent"] == txid {
//                 transparent_notes += 1;
//             }
//         }
//     }
//     if let JsonValue::Array(pending_utxos) = &notes["pending_utxos"] {
//         for utxo in pending_utxos {
//             if utxo["spent"] == txid || utxo["pending_spent"] == txid {
//                 transparent_notes += 1;
//             }
//         }
//     }

//     if let JsonValue::Array(spent_sapling_notes) = &notes["spent_sapling_notes"] {
//         for note in spent_sapling_notes {
//             if note["spent"] == txid || note["pending_spent"] == txid {
//                 sapling_notes += 1;
//             }
//         }
//     }
//     if let JsonValue::Array(pending_sapling_notes) = &notes["pending_sapling_notes"] {
//         for note in pending_sapling_notes {
//             if note["spent"] == txid || note["pending_spent"] == txid {
//                 sapling_notes += 1;
//             }
//         }
//     }

//     if let JsonValue::Array(spent_orchard_notes) = &notes["spent_orchard_notes"] {
//         for note in spent_orchard_notes {
//             if note["spent"] == txid || note["pending_spent"] == txid {
//                 orchard_notes += 1;
//             }
//         }
//     }
//     if let JsonValue::Array(pending_orchard_notes) = &notes["pending_orchard_notes"] {
//         for note in pending_orchard_notes {
//             if note["spent"] == txid || note["pending_spent"] == txid {
//                 orchard_notes += 1;
//             }
//         }
//     }

//     TxNotesCount {
//         transparent_tx_notes: transparent_notes,
//         sapling_tx_notes: sapling_notes,
//         orchard_tx_notes: orchard_notes,
//     }
// }

// /// Returns number of notes created in txid as TxNotesCount (transparent_notes, sapling_notes, orchard_notes).
// pub async fn tx_outputs(client: &LightClient, txid: &str) -> TxNotesCount {
//     let notes = client.do_list_notes(true).await;

//     let mut transparent_notes = 0;
//     let mut sapling_notes = 0;
//     let mut orchard_notes = 0;

//     if let JsonValue::Array(unspent_utxos) = &notes["utxos"] {
//         for utxo in unspent_utxos {
//             if utxo["created_in_txid"] == txid {
//                 transparent_notes += 1;
//             }
//         }
//     }

//     if let JsonValue::Array(pending_utxos) = &notes["pending_utxos"] {
//         for utxo in pending_utxos {
//             if utxo["created_in_txid"] == txid {
//                 transparent_notes += 1;
//             }
//         }
//     }

//     if let JsonValue::Array(unspent_sapling_notes) = &notes["unspent_sapling_notes"] {
//         for note in unspent_sapling_notes {
//             if note["created_in_txid"] == txid {
//                 sapling_notes += 1;
//             }
//         }
//     }

//     if let JsonValue::Array(pending_sapling_notes) = &notes["pending_sapling_notes"] {
//         for note in pending_sapling_notes {
//             if note["created_in_txid"] == txid {
//                 sapling_notes += 1;
//             }
//         }
//     }

//     if let JsonValue::Array(unspent_orchard_notes) = &notes["unspent_orchard_notes"] {
//         for note in unspent_orchard_notes {
//             if note["created_in_txid"] == txid {
//                 orchard_notes += 1;
//             }
//         }
//     }

//     if let JsonValue::Array(pending_orchard_notes) = &notes["pending_orchard_notes"] {
//         for note in pending_orchard_notes {
//             if note["created_in_txid"] == txid {
//                 orchard_notes += 1;
//             }
//         }
//     }

//     TxNotesCount {
//         transparent_tx_notes: transparent_notes,
//         sapling_tx_notes: sapling_notes,
//         orchard_tx_notes: orchard_notes,
//     }
// }

// /// Returns total actions for txid as TxActionsCount.
// pub async fn tx_actions(
//     sender: &LightClient,
//     recipient: Option<&LightClient>,
//     txid: &str,
// ) -> TxActionsCount {
//     let tx_ins = tx_inputs(sender, txid).await;
//     let tx_outs = if let Some(rec) = recipient {
//         tx_outputs(rec, txid).await
//     } else {
//         TxNotesCount {
//             transparent_tx_notes: 0,
//             sapling_tx_notes: 0,
//             orchard_tx_notes: 0,
//         }
//     };
//     let tx_change = tx_outputs(sender, txid).await;

//     let calculated_sapling_tx_actions = cmp::max(
//         tx_ins.sapling_tx_notes,
//         tx_outs.sapling_tx_notes + tx_change.sapling_tx_notes,
//     );
//     let final_sapling_tx_actions = if calculated_sapling_tx_actions == 1 {
//         2
//     } else {
//         calculated_sapling_tx_actions
//     };

//     let calculated_orchard_tx_actions = cmp::max(
//         tx_ins.orchard_tx_notes,
//         tx_outs.orchard_tx_notes + tx_change.orchard_tx_notes,
//     );
//     let final_orchard_tx_actions = if calculated_orchard_tx_actions == 1 {
//         2
//     } else {
//         calculated_orchard_tx_actions
//     };

//     TxActionsCount {
//         transparent_tx_actions: cmp::max(
//             tx_ins.transparent_tx_notes,
//             tx_outs.transparent_tx_notes + tx_change.transparent_tx_notes,
//         ),
//         sapling_tx_actions: final_sapling_tx_actions,
//         orchard_tx_actions: final_orchard_tx_actions,
//     }
// }

// /// Returns the total transfer value of txid.
// pub async fn total_tx_value(client: &LightClient, txid: &str) -> u64 {
//     let notes = client.do_list_notes(true).await;

//     let mut tx_spend: u64 = 0;
//     let mut tx_change: u64 = 0;
//     if let JsonValue::Array(spent_utxos) = &notes["spent_utxos"] {
//         for utxo in spent_utxos {
//             if utxo["spent"] == txid || utxo["pending_spent"] == txid {
//                 tx_spend += utxo["value"].as_u64().unwrap();
//             }
//         }
//     }
//     if let JsonValue::Array(pending_utxos) = &notes["pending_utxos"] {
//         for utxo in pending_utxos {
//             if utxo["spent"] == txid || utxo["pending_spent"] == txid {
//                 tx_spend += utxo["value"].as_u64().unwrap();
//             } else if utxo["created_in_txid"] == txid {
//                 tx_change += utxo["value"].as_u64().unwrap();
//             }
//         }
//     }
//     if let JsonValue::Array(unspent_utxos) = &notes["utxos"] {
//         for utxo in unspent_utxos {
//             if utxo["created_in_txid"] == txid {
//                 tx_change += utxo["value"].as_u64().unwrap();
//             }
//         }
//     }

//     if let JsonValue::Array(spent_sapling_notes) = &notes["spent_sapling_notes"] {
//         for note in spent_sapling_notes {
//             if note["spent"] == txid || note["pending_spent"] == txid {
//                 tx_spend += note["value"].as_u64().unwrap();
//             }
//         }
//     }
//     if let JsonValue::Array(pending_sapling_notes) = &notes["pending_sapling_notes"] {
//         for note in pending_sapling_notes {
//             if note["spent"] == txid || note["pending_spent"] == txid {
//                 tx_spend += note["value"].as_u64().unwrap();
//             } else if note["created_in_txid"] == txid {
//                 tx_change += note["value"].as_u64().unwrap();
//             }
//         }
//     }
//     if let JsonValue::Array(unspent_sapling_notes) = &notes["unspent_sapling_notes"] {
//         for note in unspent_sapling_notes {
//             if note["created_in_txid"] == txid {
//                 tx_change += note["value"].as_u64().unwrap();
//             }
//         }
//     }

//     if let JsonValue::Array(spent_orchard_notes) = &notes["spent_orchard_notes"] {
//         for note in spent_orchard_notes {
//             if note["spent"] == txid || note["pending_spent"] == txid {
//                 tx_spend += note["value"].as_u64().unwrap();
//             }
//         }
//     }
//     if let JsonValue::Array(pending_orchard_notes) = &notes["pending_orchard_notes"] {
//         for note in pending_orchard_notes {
//             if note["spent"] == txid || note["pending_spent"] == txid {
//                 tx_spend += note["value"].as_u64().unwrap();
//             } else if note["created_in_txid"] == txid {
//                 tx_change += note["value"].as_u64().unwrap();
//             }
//         }
//     }
//     if let JsonValue::Array(unspent_orchard_notes) = &notes["unspent_orchard_notes"] {
//         for note in unspent_orchard_notes {
//             if note["created_in_txid"] == txid {
//                 tx_change += note["value"].as_u64().unwrap();
//             }
//         }
//     }

//     tx_spend - tx_change
// }

/// TODO: Add Doc Comment Here!
pub fn port_to_localhost_uri(port: impl std::fmt::Display) -> http::Uri {
    format!("http://localhost:{port}").parse().unwrap()
}

/// a quick and dirty way to proptest across protocols.
#[must_use]
pub fn int_to_shieldedprotocol(int: i32) -> ShieldedPool {
    match int {
        1 => ShieldedPool::Sapling,
        2 => ShieldedPool::Orchard,
        _ => panic!("invalid protocol"),
    }
}

/// a quick and dirty way to proptest across pools.
#[must_use]
pub fn int_to_pooltype(int: i32) -> PoolType {
    match int {
        0 => PoolType::Transparent,
        n => PoolType::Shielded(int_to_shieldedprotocol(n)),
    }
}

/// helperized test print.
/// if someone figures out how to improve this code it can be done in one place right here.
pub fn timestamped_test_log(text: &str) {
    tracing::info!("{}: {}", crate::utils::now(), text);
}

/// Builds and caches the post-NU6.3 Orchard proving key ahead of the first send, so a fixture that awaits this during environment setup hides the multi-second build.
pub async fn warm_orchard_proving_key() {
    use orchard::circuit::OrchardCircuitVersion;
    use zcash_primitives::transaction::builder;
    tokio::task::spawn_blocking(|| {
        builder::cached_orchard_proving_key(OrchardCircuitVersion::PostNu6_3);
    })
    .await
    .expect("proving-key warmup task must not panic");
}

/// Decimal places phase timers use when they report elapsed seconds.
const PHASE_SECONDS_PRECISION: usize = 3;

/// Awaits `fut` while logging the phase's start and its elapsed wall-clock seconds under `label`.
pub async fn timed<T>(label: &str, fut: impl std::future::Future<Output = T>) -> T {
    let start = std::time::Instant::now();
    timestamped_test_log(format!("[phase] {label} started.").as_str());
    let output = fut.await;
    timestamped_test_log(
        format!(
            "[phase] {label} finished in {:.precision$}s.",
            start.elapsed().as_secs_f64(),
            precision = PHASE_SECONDS_PRECISION
        )
        .as_str(),
    );
    output
}

#[allow(unused_macros)]
macro_rules! build_method {
    ($name:ident, $localtype:ty) => {
        #[doc = "Set the $name field of the builder."]
        pub fn $name(&mut self, $name: $localtype) -> &mut Self {
            self.$name = Some($name);
            self
        }
    };
}

#[allow(unused_macros)]
macro_rules! build_method_push {
    ($name:ident, $localtype:ty) => {
        #[doc = "Push a $ty to the builder."]
        pub fn $name(&mut self, $name: $localtype) -> &mut Self {
            self.$name.push($name);
            self
        }
    };
}
#[allow(unused_macros)]
macro_rules! build_push_list {
    ($name:ident, $builder:ident, $struct:ident) => {
        for i in &$builder.$name {
            $struct.$name.push(i.build());
        }
    };
}

#[allow(unused_imports)]
pub(crate) use build_method;
#[allow(unused_imports)]
pub(crate) use build_method_push;
#[allow(unused_imports)]
pub(crate) use build_push_list;

/// Take a P2PKH taddr and interpret it as a tex addr
pub fn interpret_taddr_as_tex_addr(
    taddr_bytes: [u8; 20],
    p: &impl zcash_protocol::consensus::Parameters,
) -> String {
    bech32::encode::<bech32::Bech32m>(
        bech32::Hrp::parse_unchecked(p.network_type().hrp_tex_address()),
        &taddr_bytes,
    )
    .unwrap()
}

/// Decodes unified address and re-encode as sapling address.
pub fn encoded_sapling_address_from_ua(
    consensus_parameters: &impl consensus::Parameters,
    encoded_unified_address: &str,
) -> String {
    let zcash_keys::address::Address::Unified(unified_address) =
        decode_address(consensus_parameters, encoded_unified_address).unwrap()
    else {
        panic!("not unified address")
    };

    unified_address
        .sapling()
        .expect("no sapling receiver")
        .encode(consensus_parameters)
}

/// Decodes unified address and re-encode with only the orchard receiver.
pub fn encoded_orchard_only_from_ua(
    consensus_parameters: &impl consensus::Parameters,
    encoded_unified_address: &str,
) -> String {
    let zcash_keys::address::Address::Unified(unified_address) =
        decode_address(consensus_parameters, encoded_unified_address).unwrap()
    else {
        panic!("not unified address")
    };

    UnifiedAddress::from_receivers(
        Some(
            unified_address
                .orchard()
                .copied()
                .expect("no orchard receiver"),
        ),
        None,
        None,
        None,
        None,
    )
    .unwrap()
    .encode(consensus_parameters)
}