Skip to main content

zcash_client_backend/data_api/
testing.rs

1//! Utilities for testing wallets based upon the [`crate::data_api`] traits.
2
3use std::{
4    cell::Cell,
5    collections::{BTreeMap, HashMap, HashSet},
6    convert::Infallible,
7    fmt,
8    hash::Hash,
9    num::NonZeroU32,
10    ops::Range,
11    time::Duration,
12};
13
14#[cfg(feature = "pczt")]
15use super::wallet::{create_pczt_from_proposal, extract_and_store_transaction_from_pczt};
16use assert_matches::assert_matches;
17use group::ff::Field;
18use incrementalmerkletree::{Marking, Position, Retention};
19use nonempty::NonEmpty;
20use rand::{CryptoRng, Rng, RngExt, SeedableRng};
21use rand_chacha::ChaChaRng;
22use secrecy::{ExposeSecret, Secret, SecretVec};
23use shardtree::{
24    ShardTree,
25    error::ShardTreeError,
26    store::{ShardStore as _, memory::MemoryShardStore},
27};
28use subtle::ConditionallySelectable;
29#[cfg(feature = "transparent-inputs")]
30use {
31    super::{
32        CoinbaseFilter, TransactionsInvolvingAddress, TransparentBalances,
33        wallet::{
34            input_selection::ShieldingSelector, propose_shielding, propose_shielding_coinbase,
35            shield_transparent_funds,
36        },
37    },
38    crate::wallet::TransparentAddressMetadata,
39    ::transparent::{
40        address::{Script, TransparentAddress},
41        bundle::OutPoint,
42    },
43    zcash_keys::keys::transparent::{TransparentKeyScope, gap_limits::GapLimits},
44};
45
46use ::sapling::{
47    Rseed,
48    note_encryption::{SaplingDomain, sapling_note_encryption},
49    prover::mock::{MockOutputProver, MockSpendProver},
50    util::generate_random_rseed,
51    value::NoteValue as SaplingNoteValue,
52    zip32::{DiversifiableFullViewingKey, ExtendedSpendingKey},
53};
54use zcash_address::ZcashAddress;
55use zcash_keys::{
56    address::{Address, UnifiedAddress},
57    keys::{UnifiedAddressRequest, UnifiedFullViewingKey, UnifiedSpendingKey},
58};
59use zcash_note_encryption::Domain;
60use zcash_primitives::{
61    block::BlockHash,
62    transaction::{Transaction, TxId, components::sapling::zip212_enforcement, fees::FeeRule},
63};
64#[cfg(feature = "pczt")]
65use zcash_proofs::prover::LocalTxProver;
66use zcash_protocol::{
67    ShieldedPool,
68    consensus::{self, BlockHeight, Network, NetworkUpgrade, Parameters as _},
69    local_consensus::LocalNetwork,
70    memo::{Memo, MemoBytes},
71    value::{ZatBalance, Zatoshis},
72};
73#[cfg(feature = "transparent-key-import")]
74use zcash_script::script;
75use zip32::{DiversifierIndex, Scope};
76use zip321::Payment;
77#[cfg(feature = "orchard")]
78use {
79    super::ORCHARD_SHARD_HEIGHT,
80    crate::proto::compact_formats::CompactOrchardAction,
81    ::orchard::{
82        keys::{FullViewingKey as OrchardFullViewingKey, SpendingKey as OrchardSpendingKey},
83        note::{ExtractedNoteCommitment, Note as OrchardNote, NoteVersion, RandomSeed, Rho},
84        note_encryption::{IronwoodDomain, IronwoodNoteEncryption},
85        tree::MerkleHashOrchard,
86        value::NoteValue as OrchardNoteValue,
87    },
88    group::ff::PrimeField,
89    pasta_curves::pallas,
90    zcash_note_encryption::ShieldedOutput,
91    zcash_protocol::consensus::NetworkConstants,
92};
93
94use super::{
95    Account, AccountBalance, AccountBirthday, AccountMeta, AccountPurpose, AccountSource,
96    AddressInfo, BlockMetadata, ChangeReceivers, DecryptedTransaction, InputSource, NoteFilter,
97    NullifierQuery, ReceivedNotes, ReceivedTransactionOutput, SAPLING_SHARD_HEIGHT, ScannedBlock,
98    SeedRelevance, SentTransaction, TransactionDataRequest, TransactionStatus,
99    WalletCommitmentTrees, WalletRead, WalletSummary, WalletTest, WalletWrite, Zip32Derivation,
100    anchor_retention::AnchorRetentionInterval,
101    chain::{BlockSource, ChainState, CommitmentTreeRoot, ScanSummary, scan_cached_blocks},
102    error::Error,
103    scanning::{ScanPriority, ScanRange},
104    wallet::{
105        ConfirmationsPolicy, SpendingKeys, create_proposed_transactions,
106        input_selection::{
107            GreedyInputSelector, InputSelector, LockFilter, LockedInputPolicy, SpendPolicy,
108        },
109        propose_send_max_transfer, propose_standard_transfer_to_address, propose_transfer,
110    },
111};
112
113#[cfg(feature = "pczt")]
114fn real_test_prover() -> &'static LocalTxProver {
115    use std::sync::OnceLock;
116
117    static PROVER: OnceLock<LocalTxProver> = OnceLock::new();
118    PROVER.get_or_init(LocalTxProver::bundled)
119}
120use crate::{
121    data_api::{
122        MaxSpendMode, OutputLockStore, PutBlocksError, TargetValue,
123        error::{LockError, RewindError},
124        wallet::TargetHeight,
125    },
126    fees::{
127        ChangeStrategy, DustOutputPolicy, StandardFeeRule,
128        standard::{self, SingleOutputChangeStrategy},
129    },
130    proposal::Proposal,
131    proto::compact_formats::{
132        self, CompactBlock, CompactSaplingOutput, CompactSaplingSpend, CompactTx,
133    },
134    util::testing::FixedClock,
135    wallet::{
136        LockOwner, Note, NoteId, OutputRef, OvkPolicy, ReceivedNote, WalletTransparentOutput,
137    },
138};
139
140pub mod pool;
141pub mod sapling;
142
143#[cfg(feature = "orchard")]
144pub mod orchard;
145#[cfg(feature = "transparent-inputs")]
146pub mod transparent;
147
148/// Information about a transaction that the wallet is interested in.
149#[derive(Debug)]
150pub struct TransactionSummary<AccountId> {
151    account_id: AccountId,
152    txid: TxId,
153    expiry_height: Option<BlockHeight>,
154    mined_height: Option<BlockHeight>,
155    account_value_delta: ZatBalance,
156    total_spent: Zatoshis,
157    total_received: Zatoshis,
158    fee_paid: Option<Zatoshis>,
159    spent_note_count: usize,
160    has_change: bool,
161    sent_note_count: usize,
162    received_note_count: usize,
163    memo_count: usize,
164    expired_unmined: bool,
165    is_shielding: bool,
166    pool_crossing_value: Option<Zatoshis>,
167}
168
169impl<AccountId> TransactionSummary<AccountId> {
170    /// Constructs a `TransactionSummary` from its parts.
171    ///
172    /// See the documentation for each getter method below to determine how each method
173    /// argument should be prepared.
174    #[allow(clippy::too_many_arguments)]
175    pub fn from_parts(
176        account_id: AccountId,
177        txid: TxId,
178        expiry_height: Option<BlockHeight>,
179        mined_height: Option<BlockHeight>,
180        account_value_delta: ZatBalance,
181        total_spent: Zatoshis,
182        total_received: Zatoshis,
183        fee_paid: Option<Zatoshis>,
184        spent_note_count: usize,
185        has_change: bool,
186        sent_note_count: usize,
187        received_note_count: usize,
188        memo_count: usize,
189        expired_unmined: bool,
190        is_shielding: bool,
191        pool_crossing_value: Option<Zatoshis>,
192    ) -> Self {
193        Self {
194            account_id,
195            txid,
196            expiry_height,
197            mined_height,
198            account_value_delta,
199            total_spent,
200            total_received,
201            fee_paid,
202            spent_note_count,
203            has_change,
204            sent_note_count,
205            received_note_count,
206            memo_count,
207            expired_unmined,
208            is_shielding,
209            pool_crossing_value,
210        }
211    }
212
213    /// Returns the wallet-internal ID for the account that this transaction was received
214    /// by or sent from.
215    pub fn account_id(&self) -> &AccountId {
216        &self.account_id
217    }
218
219    /// Returns the transaction's ID.
220    pub fn txid(&self) -> TxId {
221        self.txid
222    }
223
224    /// Returns the expiry height of the transaction, if known.
225    ///
226    /// - `None` means that the expiry height is unknown.
227    /// - `Some(0)` means that the transaction does not expire.
228    pub fn expiry_height(&self) -> Option<BlockHeight> {
229        self.expiry_height
230    }
231
232    /// Returns the height of the mined block containing this transaction, or `None` if
233    /// the wallet has not yet observed the transaction to be mined.
234    pub fn mined_height(&self) -> Option<BlockHeight> {
235        self.mined_height
236    }
237
238    /// Returns the net change in balance that this transaction caused to the account.
239    ///
240    /// For example, an account-internal transaction (such as a shielding operation) would
241    /// show `-fee_paid` as the account value delta.
242    pub fn account_value_delta(&self) -> ZatBalance {
243        self.account_value_delta
244    }
245
246    /// Returns the total value of notes spent by the account in this transaction.
247    pub fn total_spent(&self) -> Zatoshis {
248        self.total_spent
249    }
250
251    /// Returns the total value of notes received by the account in this transaction.
252    pub fn total_received(&self) -> Zatoshis {
253        self.total_received
254    }
255
256    /// Returns the fee paid by this transaction, if known.
257    pub fn fee_paid(&self) -> Option<Zatoshis> {
258        self.fee_paid
259    }
260
261    /// Returns the number of notes spent by the account in this transaction.
262    pub fn spent_note_count(&self) -> usize {
263        self.spent_note_count
264    }
265
266    /// Returns `true` if the account received a change note as part of this transaction.
267    ///
268    /// This implies that the transaction was (at least in part) sent from the account.
269    pub fn has_change(&self) -> bool {
270        self.has_change
271    }
272
273    /// Returns the number of notes created in this transaction that were sent to a
274    /// wallet-external address.
275    pub fn sent_note_count(&self) -> usize {
276        self.sent_note_count
277    }
278
279    /// Returns the number of notes created in this transaction that were received by the
280    /// account.
281    pub fn received_note_count(&self) -> usize {
282        self.received_note_count
283    }
284
285    /// Returns `true` if, from the wallet's current view of the chain, this transaction
286    /// expired before it was mined.
287    pub fn expired_unmined(&self) -> bool {
288        self.expired_unmined
289    }
290
291    /// Returns the number of non-empty memos viewable by the account in this transaction.
292    pub fn memo_count(&self) -> usize {
293        self.memo_count
294    }
295
296    /// Returns `true` if this is detectably a shielding transaction.
297    ///
298    /// Specifically, `true` means that at a minimum:
299    /// - All of the wallet-spent and wallet-received notes are consistent with a
300    ///   shielding transaction.
301    /// - The transaction contains at least one wallet-spent output.
302    /// - The transaction contains at least one wallet-received note.
303    /// - We do not know about any external outputs of the transaction.
304    ///
305    /// There may be some shielding transactions for which this method returns `false`,
306    /// due to them not being detectable by the wallet as shielding transactions under the
307    /// above metrics.
308    pub fn is_shielding(&self) -> bool {
309        self.is_shielding
310    }
311
312    /// Returns `true` if this is detectably a wallet-internal transfer that moves the
313    /// account's own funds between shielded pools (for example, a ZIP 318
314    /// Orchard -> Ironwood migration transfer).
315    ///
316    /// Specifically, `true` means that at a minimum:
317    /// - Every wallet-spent note and wallet-received output is shielded.
318    /// - The transaction spends at least one of the account's notes.
319    /// - At least one output was received in a pool the account spent nothing from.
320    /// - We do not know about any external outputs of the transaction.
321    ///
322    /// A payment that returns value to one of the wallet's own addresses is classified
323    /// once the wallet has observed the returned output (which the scanner marks as
324    /// change); while such a transaction is unmined it is treated as an ordinary payment.
325    ///
326    /// This is exactly the condition that [`Self::pool_crossing_value`] is `Some`; the
327    /// crossed amount is what identifies the transaction, so it is the only thing stored.
328    pub fn is_pool_crossing(&self) -> bool {
329        self.pool_crossing_value.is_some()
330    }
331
332    /// Returns the total value received in pools the account did not spend from, which
333    /// is the amount that crossed pools, when this is a pool-crossing transaction as described
334    /// by [`Self::is_pool_crossing`], or `None` otherwise.
335    pub fn pool_crossing_value(&self) -> Option<Zatoshis> {
336        self.pool_crossing_value
337    }
338}
339
340/// Metadata about a block generated by [`TestState`].
341#[derive(Clone, Debug)]
342pub struct CachedBlock {
343    chain_state: ChainState,
344    sapling_end_size: u32,
345    orchard_end_size: u32,
346    ironwood_end_size: u32,
347}
348
349impl CachedBlock {
350    /// Produces metadata for a block "before shielded time", when the Sapling, Orchard, and
351    /// Ironwood trees were (by definition) empty.
352    ///
353    /// `block_height` must be a height before Sapling activation (and therefore also
354    /// before NU5 activation).
355    pub fn none(block_height: BlockHeight) -> Self {
356        Self {
357            chain_state: ChainState::empty(block_height, BlockHash([0; 32])),
358            sapling_end_size: 0,
359            orchard_end_size: 0,
360            ironwood_end_size: 0,
361        }
362    }
363
364    /// Produces metadata for a block as of the given chain state.
365    pub fn at(
366        chain_state: ChainState,
367        sapling_end_size: u32,
368        orchard_end_size: u32,
369        ironwood_end_size: u32,
370    ) -> Self {
371        assert_eq!(
372            chain_state.final_sapling_tree().tree_size() as u32,
373            sapling_end_size
374        );
375        #[cfg(feature = "orchard")]
376        assert_eq!(
377            chain_state.final_orchard_tree().tree_size() as u32,
378            orchard_end_size
379        );
380        #[cfg(feature = "orchard")]
381        assert_eq!(
382            chain_state.final_ironwood_tree().tree_size() as u32,
383            ironwood_end_size
384        );
385
386        Self {
387            chain_state,
388            sapling_end_size,
389            orchard_end_size,
390            ironwood_end_size,
391        }
392    }
393
394    fn roll_forward(&self, cb: &CompactBlock) -> Self {
395        assert_eq!(self.chain_state.block_height() + 1, cb.height());
396
397        let sapling_final_tree = cb.vtx.iter().flat_map(|tx| tx.outputs.iter()).fold(
398            self.chain_state.final_sapling_tree().clone(),
399            |mut acc, c_out| {
400                acc.append(::sapling::Node::from_cmu(&c_out.cmu().unwrap()));
401                acc
402            },
403        );
404        let sapling_end_size = sapling_final_tree.tree_size() as u32;
405
406        #[cfg(feature = "orchard")]
407        let orchard_final_tree = cb.vtx.iter().flat_map(|tx| tx.actions.iter()).fold(
408            self.chain_state.final_orchard_tree().clone(),
409            |mut acc, c_act| {
410                acc.append(MerkleHashOrchard::from_cmx(&c_act.cmx().unwrap()));
411                acc
412            },
413        );
414        #[cfg(feature = "orchard")]
415        let orchard_end_size = orchard_final_tree.tree_size() as u32;
416        #[cfg(not(feature = "orchard"))]
417        let orchard_end_size = cb.vtx.iter().fold(self.orchard_end_size, |sz, tx| {
418            sz + (tx.actions.len() as u32)
419        });
420
421        #[cfg(feature = "orchard")]
422        let ironwood_final_tree = cb
423            .vtx
424            .iter()
425            .flat_map(|tx| tx.ironwood_actions.iter())
426            .fold(
427                self.chain_state.final_ironwood_tree().clone(),
428                |mut acc, c_act| {
429                    acc.append(MerkleHashOrchard::from_cmx(&c_act.cmx().unwrap()));
430                    acc
431                },
432            );
433        #[cfg(feature = "orchard")]
434        let ironwood_end_size = ironwood_final_tree.tree_size() as u32;
435        #[cfg(not(feature = "orchard"))]
436        let ironwood_end_size = cb.vtx.iter().fold(self.ironwood_end_size, |sz, tx| {
437            sz + (tx.ironwood_actions.len() as u32)
438        });
439
440        Self {
441            chain_state: ChainState::new(
442                cb.height(),
443                cb.hash(),
444                sapling_final_tree,
445                #[cfg(feature = "orchard")]
446                orchard_final_tree,
447                #[cfg(feature = "orchard")]
448                ironwood_final_tree,
449            ),
450            sapling_end_size,
451            orchard_end_size,
452            ironwood_end_size,
453        }
454    }
455
456    /// Returns the chain state as of the end of this block.
457    pub fn chain_state(&self) -> &ChainState {
458        &self.chain_state
459    }
460
461    /// Returns the height of this block.
462    pub fn height(&self) -> BlockHeight {
463        self.chain_state.block_height()
464    }
465
466    /// Returns the size of the Sapling note commitment tree as of the end of this block.
467    pub fn sapling_end_size(&self) -> u32 {
468        self.sapling_end_size
469    }
470
471    /// Returns the size of the Orchard note commitment tree as of the end of this block.
472    pub fn orchard_end_size(&self) -> u32 {
473        self.orchard_end_size
474    }
475
476    /// Returns the size of the Ironwood note commitment tree as of the end of this block.
477    pub fn ironwood_end_size(&self) -> u32 {
478        self.ironwood_end_size
479    }
480}
481
482/// The test account configured for a [`TestState`].
483///
484/// Create this by calling either [`TestBuilder::with_account_from_sapling_activation`] or
485/// [`TestBuilder::with_account_having_current_birthday`] while setting up a test, and
486/// then access it with [`TestState::test_account`].
487#[derive(Clone)]
488pub struct TestAccount<A> {
489    account: A,
490    usk: UnifiedSpendingKey,
491    birthday: AccountBirthday,
492}
493
494impl<A> TestAccount<A> {
495    /// Returns the underlying wallet account.
496    pub fn account(&self) -> &A {
497        &self.account
498    }
499
500    /// Returns the account's unified spending key.
501    pub fn usk(&self) -> &UnifiedSpendingKey {
502        &self.usk
503    }
504
505    /// Returns the birthday that was configured for the account.
506    pub fn birthday(&self) -> &AccountBirthday {
507        &self.birthday
508    }
509}
510
511impl<A: Account> Account for TestAccount<A> {
512    type AccountId = A::AccountId;
513
514    fn id(&self) -> Self::AccountId {
515        self.account.id()
516    }
517
518    fn name(&self) -> Option<&str> {
519        self.account.name()
520    }
521
522    fn birthday_height(&self) -> BlockHeight {
523        self.account.birthday_height()
524    }
525
526    fn source(&self) -> &AccountSource {
527        self.account.source()
528    }
529
530    fn ufvk(&self) -> Option<&zcash_keys::keys::UnifiedFullViewingKey> {
531        self.account.ufvk()
532    }
533
534    fn uivk(&self) -> zcash_keys::keys::UnifiedIncomingViewingKey {
535        self.account.uivk()
536    }
537}
538
539/// Trait method exposing the ability to reset the wallet within a test.
540// TODO: Does this need to exist separately from DataStoreFactory?
541pub trait Reset: WalletTest + Sized {
542    /// A handle that confers ownership of a specific wallet instance.
543    type Handle;
544
545    /// Replaces the wallet in `st` (via [`TestState::wallet_mut`]) with a new wallet
546    /// database.
547    ///
548    /// This does not recreate accounts. The resulting wallet in `st` has no test account.
549    ///
550    /// Returns the old wallet.
551    fn reset<C>(st: &mut TestState<C, Self, LocalNetwork>) -> Self::Handle;
552}
553
554/// The state for a `zcash_client_backend` test.
555/// The fixed instant (2025-02-25T00:00:00Z) at which a [`TestState`]'s clock starts,
556/// as an offset from the Unix epoch.
557const TEST_CLOCK_EPOCH_OFFSET: Duration = Duration::from_secs(1740441600);
558
559pub struct TestState<Cache, DataStore: WalletTest, Network> {
560    cache: Cache,
561    cached_blocks: BTreeMap<BlockHeight, CachedBlock>,
562    latest_block_height: Option<BlockHeight>,
563    wallet_data: DataStore,
564    network: Network,
565    test_account: Option<(SecretVec<u8>, TestAccount<DataStore::Account>)>,
566    rng: ChaChaRng,
567    clock: FixedClock,
568}
569
570impl<Cache, DataStore: WalletTest, Network> TestState<Cache, DataStore, Network> {
571    /// Exposes the fixed clock that this test state passes to wallet operations.
572    pub fn clock(&self) -> &FixedClock {
573        &self.clock
574    }
575
576    /// Exposes an immutable reference to the test's `DataStore`.
577    pub fn wallet(&self) -> &DataStore {
578        &self.wallet_data
579    }
580
581    /// Exposes a mutable reference to the test's `DataStore`.
582    pub fn wallet_mut(&mut self) -> &mut DataStore {
583        &mut self.wallet_data
584    }
585
586    /// Exposes the test framework's source of randomness.
587    pub fn rng_mut(&mut self) -> &mut ChaChaRng {
588        &mut self.rng
589    }
590
591    /// Exposes the network in use.
592    pub fn network(&self) -> &Network {
593        &self.network
594    }
595}
596
597impl<Cache, DataStore: WalletTest, Network> Drop for TestState<Cache, DataStore, Network> {
598    fn drop(&mut self) {
599        self.wallet_data.finally();
600    }
601}
602
603impl<Cache, DataStore: WalletTest, Network: consensus::Parameters>
604    TestState<Cache, DataStore, Network>
605{
606    /// Convenience method for obtaining the Sapling activation height for the network under test.
607    pub fn sapling_activation_height(&self) -> BlockHeight {
608        self.network
609            .activation_height(NetworkUpgrade::Sapling)
610            .expect("Sapling activation height must be known.")
611    }
612
613    /// Convenience method for obtaining the NU5 activation height for the network under test.
614    #[allow(dead_code)]
615    pub fn nu5_activation_height(&self) -> BlockHeight {
616        self.network
617            .activation_height(NetworkUpgrade::Nu5)
618            .expect("NU5 activation height must be known.")
619    }
620
621    /// Exposes the seed for the test wallet.
622    pub fn test_seed(&self) -> Option<&SecretVec<u8>> {
623        self.test_account.as_ref().map(|(seed, _)| seed)
624    }
625
626    /// Returns a reference to the test account, if one was configured.
627    pub fn test_account(&self) -> Option<&TestAccount<<DataStore as WalletRead>::Account>> {
628        self.test_account.as_ref().map(|(_, acct)| acct)
629    }
630
631    /// Returns the test account's Sapling DFVK, if one was configured.
632    pub fn test_account_sapling(&self) -> Option<&DiversifiableFullViewingKey> {
633        let (_, acct) = self.test_account.as_ref()?;
634        let ufvk = acct.ufvk()?;
635        ufvk.sapling()
636    }
637
638    /// Returns the test account's Orchard FVK, if one was configured.
639    #[cfg(feature = "orchard")]
640    pub fn test_account_orchard(&self) -> Option<&::orchard::keys::FullViewingKey> {
641        let (_, acct) = self.test_account.as_ref()?;
642        let ufvk = acct.ufvk()?;
643        ufvk.orchard()
644    }
645}
646
647impl<Cache, DataStore, Network> TestState<Cache, DataStore, Network>
648where
649    DataStore: WalletTest + WalletWrite,
650    Network: consensus::Parameters,
651{
652    /// Creates a FURTHER account under the test seed, at the test account's birthday, and returns
653    /// its id and spending key.
654    ///
655    /// The wallet assigns the next unused ZIP 32 account index, so this is a sibling of the
656    /// account [`TestBuilder`] configured — the shape a test needs to check that some answer is
657    /// scoped to the account it was asked of, rather than to the wallet.
658    ///
659    /// Create every account a test needs BEFORE scanning anything: account creation adjusts the
660    /// scan queue, which clears the wallet's fully-scanned height.
661    pub fn create_account_from_test_seed(
662        &mut self,
663        account_name: &str,
664    ) -> (<DataStore as WalletRead>::AccountId, UnifiedSpendingKey) {
665        let seed = SecretVec::new(
666            self.test_seed()
667                .expect("the test state was built with a seed")
668                .expose_secret()
669                .clone(),
670        );
671        let birthday = self
672            .test_account()
673            .expect("the test state was built with an account")
674            .birthday()
675            .clone();
676        self.wallet_mut()
677            .create_account(account_name, &seed, &birthday, None)
678            .expect("creates a further account under the test seed")
679    }
680}
681
682impl<Cache: TestCache, DataStore, Network> TestState<Cache, DataStore, Network>
683where
684    Network: consensus::Parameters,
685    DataStore: WalletTest + WalletWrite,
686    <Cache::BlockSource as BlockSource>::Error: fmt::Debug,
687{
688    /// Exposes an immutable reference to the test's [`BlockSource`].
689    #[cfg(feature = "unstable")]
690    pub fn cache(&self) -> &Cache::BlockSource {
691        self.cache.block_source()
692    }
693
694    /// Returns the cached chain state corresponding to the latest block generated by this
695    /// `TestState`.
696    pub fn latest_cached_block(&self) -> Option<&CachedBlock> {
697        self.latest_block_height
698            .as_ref()
699            .and_then(|h| self.cached_blocks.get(h))
700    }
701
702    fn latest_cached_block_below_height(&self, height: BlockHeight) -> Option<&CachedBlock> {
703        self.cached_blocks.range(..height).last().map(|(_, b)| b)
704    }
705
706    fn cache_block(
707        &mut self,
708        prev_block: &CachedBlock,
709        compact_block: CompactBlock,
710    ) -> Cache::InsertResult {
711        self.cached_blocks.insert(
712            compact_block.height(),
713            prev_block.roll_forward(&compact_block),
714        );
715        self.cache.insert(&compact_block)
716    }
717
718    /// Creates a fake block at the expected next height containing a single output of the
719    /// given value, and inserts it into the cache.
720    ///
721    /// This is a proxy for `generate_next_block_multi`.
722    pub fn generate_next_block<Fvk: TestFvk>(
723        &mut self,
724        recipient_fvk: &Fvk,
725        recipient_address_type: AddressType,
726        value: Zatoshis,
727    ) -> (BlockHeight, Cache::InsertResult, Fvk::Nullifier) {
728        let (height, res, nfs) = self.generate_next_block_multi(&[FakeCompactOutput::new(
729            recipient_fvk,
730            recipient_address_type,
731            value,
732        )]);
733
734        (height, res, nfs[0])
735    }
736
737    /// Creates a fake block at the expected next height containing multiple outputs
738    /// and inserts it into the cache.
739    pub fn generate_next_block_multi<Fvk: TestFvk>(
740        &mut self,
741        outputs: &[FakeCompactOutput<Fvk>],
742    ) -> (BlockHeight, Cache::InsertResult, Vec<Fvk::Nullifier>) {
743        let pre_activation_block = CachedBlock::none(self.sapling_activation_height() - 1);
744        let prior_cached_block = self.latest_cached_block().unwrap_or(&pre_activation_block);
745        let height = prior_cached_block.height() + 1;
746
747        let (res, nfs) = self.generate_block_at(
748            height,
749            prior_cached_block.chain_state.block_hash(),
750            outputs,
751            prior_cached_block.sapling_end_size,
752            prior_cached_block.orchard_end_size,
753            prior_cached_block.ironwood_end_size,
754            false,
755        );
756
757        (height, res, nfs)
758    }
759
760    /// Adds a block at the next height containing a single transparent-only transaction that
761    /// spends `vin` and creates an output of each `(address, value)` in `vout`, and inserts it
762    /// into the cache.
763    ///
764    /// The transaction is placed at index 1 within the block, behind a placeholder occupying the
765    /// coinbase position, so that the outputs it creates are not subject to the coinbase maturity
766    /// rule. Returns the height of the block and the id of the transparent transaction.
767    #[cfg(feature = "transparent-inputs")]
768    pub fn generate_next_block_transparent(
769        &mut self,
770        vin: &[OutPoint],
771        vout: &[(TransparentAddress, Zatoshis)],
772    ) -> (BlockHeight, Cache::InsertResult, TxId) {
773        let pre_activation_block = CachedBlock::none(self.sapling_activation_height() - 1);
774        let prior_cached_block = self
775            .latest_cached_block()
776            .unwrap_or(&pre_activation_block)
777            .clone();
778        let height = prior_cached_block.height() + 1;
779
780        let mut coinbase = fake_compact_tx(&mut self.rng);
781        coinbase.index = 0;
782
783        let mut ctx = fake_compact_tx(&mut self.rng);
784        ctx.index = 1;
785        ctx.vin = vin
786            .iter()
787            .map(|outpoint| compact_formats::CompactTxIn {
788                prevout_txid: outpoint.hash().to_vec(),
789                prevout_index: outpoint.n(),
790            })
791            .collect();
792        ctx.vout = vout
793            .iter()
794            .map(|(addr, value)| compact_formats::TxOut {
795                value: value.into_u64(),
796                script_pub_key: Script::from(addr.script()).0.0,
797            })
798            .collect();
799        let txid = TxId::from_bytes(ctx.txid[..].try_into().expect("txid is 32 bytes"));
800
801        let mut cb = CompactBlock {
802            hash: {
803                let mut hash = vec![0; 32];
804                self.rng.fill_bytes(&mut hash);
805                hash
806            },
807            height: height.into(),
808            ..Default::default()
809        };
810        cb.prev_hash
811            .extend_from_slice(&prior_cached_block.chain_state.block_hash().0);
812        cb.vtx.push(coinbase);
813        cb.vtx.push(ctx);
814        cb.chain_metadata = Some(compact_formats::ChainMetadata {
815            sapling_commitment_tree_size: prior_cached_block.sapling_end_size,
816            orchard_commitment_tree_size: prior_cached_block.orchard_end_size,
817            ironwood_commitment_tree_size: prior_cached_block.ironwood_end_size,
818        });
819
820        let res = self.cache_block(&prior_cached_block, cb);
821        self.latest_block_height = Some(height);
822
823        (height, res, txid)
824    }
825
826    /// Adds an empty block to the cache, advancing the simulated chain height.
827    pub fn generate_empty_block(&mut self) -> (BlockHeight, Cache::InsertResult) {
828        let new_hash = {
829            let mut hash = vec![0; 32];
830            self.rng.fill_bytes(&mut hash);
831            hash
832        };
833
834        let pre_activation_block = CachedBlock::none(self.sapling_activation_height() - 1);
835        let prior_cached_block = self
836            .latest_cached_block()
837            .unwrap_or(&pre_activation_block)
838            .clone();
839        let new_height = prior_cached_block.height() + 1;
840
841        let mut cb = CompactBlock {
842            hash: new_hash,
843            height: new_height.into(),
844            ..Default::default()
845        };
846        cb.prev_hash
847            .extend_from_slice(&prior_cached_block.chain_state.block_hash().0);
848
849        cb.chain_metadata = Some(compact_formats::ChainMetadata {
850            sapling_commitment_tree_size: prior_cached_block.sapling_end_size,
851            orchard_commitment_tree_size: prior_cached_block.orchard_end_size,
852            ironwood_commitment_tree_size: prior_cached_block.ironwood_end_size,
853        });
854
855        let res = self.cache_block(&prior_cached_block, cb);
856        self.latest_block_height = Some(new_height);
857
858        (new_height, res)
859    }
860
861    /// Creates a fake block with the given height and hash containing the requested outputs, and
862    /// inserts it into the cache.
863    ///
864    /// This generated block will be treated as the latest block, and subsequent calls to
865    /// [`Self::generate_next_block`] will build on it.
866    #[allow(clippy::too_many_arguments)]
867    pub fn generate_block_at<Fvk: TestFvk>(
868        &mut self,
869        height: BlockHeight,
870        prev_hash: BlockHash,
871        outputs: &[FakeCompactOutput<Fvk>],
872        initial_sapling_tree_size: u32,
873        initial_orchard_tree_size: u32,
874        initial_ironwood_tree_size: u32,
875        allow_broken_hash_chain: bool,
876    ) -> (Cache::InsertResult, Vec<Fvk::Nullifier>) {
877        let mut prior_cached_block = self
878            .latest_cached_block_below_height(height)
879            .cloned()
880            .unwrap_or_else(|| CachedBlock::none(self.sapling_activation_height() - 1));
881        assert!(prior_cached_block.chain_state.block_height() < height);
882        assert!(prior_cached_block.sapling_end_size <= initial_sapling_tree_size);
883        assert!(prior_cached_block.orchard_end_size <= initial_orchard_tree_size);
884        assert!(prior_cached_block.ironwood_end_size <= initial_ironwood_tree_size);
885
886        // If the block height has increased or the Sapling and/or Orchard tree sizes have changed,
887        // we need to generate a new prior cached block that the block to be generated can
888        // successfully chain from, with the provided tree sizes.
889        if prior_cached_block.chain_state.block_height() == height - 1 {
890            if !allow_broken_hash_chain {
891                assert_eq!(prev_hash, prior_cached_block.chain_state.block_hash());
892            }
893        } else {
894            let final_sapling_tree =
895                (prior_cached_block.sapling_end_size..initial_sapling_tree_size).fold(
896                    prior_cached_block.chain_state.final_sapling_tree().clone(),
897                    |mut acc, _| {
898                        acc.append(::sapling::Node::from_scalar(bls12_381::Scalar::random(
899                            &mut self.rng,
900                        )));
901                        acc
902                    },
903                );
904
905            #[cfg(feature = "orchard")]
906            let final_orchard_tree =
907                (prior_cached_block.orchard_end_size..initial_orchard_tree_size).fold(
908                    prior_cached_block.chain_state.final_orchard_tree().clone(),
909                    |mut acc, _| {
910                        acc.append(MerkleHashOrchard::random(&mut self.rng));
911                        acc
912                    },
913                );
914
915            #[cfg(feature = "orchard")]
916            let final_ironwood_tree =
917                (prior_cached_block.ironwood_end_size..initial_ironwood_tree_size).fold(
918                    prior_cached_block.chain_state.final_ironwood_tree().clone(),
919                    |mut acc, _| {
920                        acc.append(MerkleHashOrchard::random(&mut self.rng));
921                        acc
922                    },
923                );
924
925            prior_cached_block = CachedBlock::at(
926                ChainState::new(
927                    height - 1,
928                    prev_hash,
929                    final_sapling_tree,
930                    #[cfg(feature = "orchard")]
931                    final_orchard_tree,
932                    #[cfg(feature = "orchard")]
933                    final_ironwood_tree,
934                ),
935                initial_sapling_tree_size,
936                initial_orchard_tree_size,
937                initial_ironwood_tree_size,
938            );
939
940            self.cached_blocks
941                .insert(height - 1, prior_cached_block.clone());
942        }
943
944        let (cb, nfs) = fake_compact_block(
945            &self.network,
946            height,
947            prev_hash,
948            None,
949            outputs,
950            initial_sapling_tree_size,
951            initial_orchard_tree_size,
952            initial_ironwood_tree_size,
953            &mut self.rng,
954        );
955        assert_eq!(cb.height(), height);
956
957        let res = self.cache_block(&prior_cached_block, cb);
958        self.latest_block_height = Some(height);
959
960        (res, nfs)
961    }
962
963    /// Creates a fake block at the expected next height spending the given note, and
964    /// inserts it into the cache.
965    pub fn generate_next_block_spending<Fvk: TestFvk>(
966        &mut self,
967        sender_fvk: &Fvk,
968        note: (Fvk::Nullifier, Zatoshis),
969        to: impl Into<Address>,
970        value: Zatoshis,
971    ) -> (BlockHeight, Cache::InsertResult) {
972        let prior_cached_block = self
973            .latest_cached_block()
974            .cloned()
975            .unwrap_or_else(|| CachedBlock::none(self.sapling_activation_height() - 1));
976        let height = prior_cached_block.height() + 1;
977
978        let cb = fake_compact_block_spending(
979            &self.network,
980            height,
981            prior_cached_block.chain_state.block_hash(),
982            note,
983            sender_fvk,
984            to.into(),
985            value,
986            prior_cached_block.sapling_end_size,
987            prior_cached_block.orchard_end_size,
988            prior_cached_block.ironwood_end_size,
989            &mut self.rng,
990        );
991        assert_eq!(cb.height(), height);
992
993        let res = self.cache_block(&prior_cached_block, cb);
994        self.latest_block_height = Some(height);
995
996        (height, res)
997    }
998
999    /// Creates a fake block at the expected next height containing only the wallet
1000    /// transaction with the given txid, and inserts it into the cache.
1001    ///
1002    /// This generated block will be treated as the latest block, and subsequent calls to
1003    /// [`Self::generate_next_block`] (or similar) will build on it.
1004    pub fn generate_next_block_including(
1005        &mut self,
1006        txid: TxId,
1007    ) -> (BlockHeight, Cache::InsertResult) {
1008        let tx = self
1009            .wallet()
1010            .get_transaction(txid)
1011            .unwrap()
1012            .expect("TxId should exist in the wallet");
1013
1014        // Index 0 is by definition a coinbase transaction, and the wallet doesn't
1015        // construct coinbase transactions. So we pretend here that the block has a
1016        // coinbase transaction that does not have shielded coinbase outputs.
1017        self.generate_next_block_from_tx(1, &tx)
1018    }
1019
1020    /// Creates a fake block at the expected next height containing only the given
1021    /// transaction, and inserts it into the cache.
1022    ///
1023    /// This generated block will be treated as the latest block, and subsequent calls to
1024    /// [`Self::generate_next_block`] will build on it.
1025    pub fn generate_next_block_from_tx(
1026        &mut self,
1027        tx_index: usize,
1028        tx: &Transaction,
1029    ) -> (BlockHeight, Cache::InsertResult) {
1030        let prior_cached_block = self
1031            .latest_cached_block()
1032            .cloned()
1033            .unwrap_or_else(|| CachedBlock::none(self.sapling_activation_height() - 1));
1034        let height = prior_cached_block.height() + 1;
1035
1036        let cb = fake_compact_block_from_tx(
1037            height,
1038            prior_cached_block.chain_state.block_hash(),
1039            tx_index,
1040            tx,
1041            prior_cached_block.sapling_end_size,
1042            prior_cached_block.orchard_end_size,
1043            prior_cached_block.ironwood_end_size,
1044            &mut self.rng,
1045        );
1046        assert_eq!(cb.height(), height);
1047
1048        let res = self.cache_block(&prior_cached_block, cb);
1049        self.latest_block_height = Some(height);
1050
1051        (height, res)
1052    }
1053
1054    /// Truncates the test wallet and block cache to the specified height, discarding all data from
1055    /// blocks at heights greater than the specified height, excluding transaction data that may
1056    /// not be recoverable from the chain.
1057    pub fn truncate_to_height(&mut self, height: BlockHeight) {
1058        self.wallet_mut().truncate_to_height(height).unwrap();
1059        self.cache.truncate_to_height(height);
1060        self.cached_blocks.split_off(&(height + 1));
1061        self.latest_block_height = Some(height);
1062    }
1063
1064    /// Truncates the test wallet to the specified height, and resets the cache's latest block
1065    /// height but does not truncate the block cache. This is useful for circumstances when you
1066    /// want to re-scan a set of cached blocks.
1067    pub fn truncate_to_height_retaining_cache(&mut self, height: BlockHeight) {
1068        self.wallet_mut().truncate_to_height(height).unwrap();
1069        self.latest_block_height = Some(height);
1070    }
1071
1072    /// Truncates the block cache to the specified height without touching the wallet, so
1073    /// that subsequent `generate_next_block_*` calls extend a divergent chain from that
1074    /// height. This is useful for simulating a reorg after rewinding the wallet via
1075    /// [`WalletWrite::rewind_to_chain_state`], which performs its own (deeper) truncation
1076    /// of wallet data.
1077    pub fn truncate_cache_to_height(&mut self, height: BlockHeight) {
1078        self.cache.truncate_to_height(height);
1079        self.cached_blocks.split_off(&(height + 1));
1080        self.latest_block_height = Some(height);
1081    }
1082}
1083
1084impl<Cache, DbT, ParamsT> TestState<Cache, DbT, ParamsT>
1085where
1086    Cache: TestCache,
1087    <Cache::BlockSource as BlockSource>::Error: fmt::Debug,
1088    ParamsT: consensus::Parameters + Send + 'static,
1089    DbT: InputSource + WalletTest + WalletWrite + WalletCommitmentTrees,
1090    <DbT as WalletRead>::AccountId:
1091        std::fmt::Debug + ConditionallySelectable + Default + Send + Sync + 'static,
1092{
1093    /// Invokes [`scan_cached_blocks`] with the given arguments, expecting success.
1094    pub fn scan_cached_blocks(&mut self, from_height: BlockHeight, limit: usize) -> ScanSummary {
1095        let result = self.try_scan_cached_blocks(from_height, limit);
1096        assert_matches!(result, Ok(_));
1097        result.unwrap()
1098    }
1099
1100    /// Invokes [`scan_cached_blocks`] with the given arguments.
1101    pub fn try_scan_cached_blocks(
1102        &mut self,
1103        from_height: BlockHeight,
1104        limit: usize,
1105    ) -> Result<
1106        ScanSummary,
1107        super::chain::error::Error<
1108            <DbT as WalletRead>::Error,
1109            <Cache::BlockSource as BlockSource>::Error,
1110        >,
1111    > {
1112        let prior_cached_block = self
1113            .latest_cached_block_below_height(from_height)
1114            .cloned()
1115            .unwrap_or_else(|| CachedBlock::none(from_height - 1));
1116
1117        scan_cached_blocks(
1118            &self.network,
1119            self.cache.block_source(),
1120            &mut self.wallet_data,
1121            from_height,
1122            &prior_cached_block.chain_state,
1123            limit,
1124        )
1125    }
1126
1127    /// Invokes [`scan_cached_blocks`] with a caller-supplied `from_state` instead of deriving it
1128    /// from the block cache.
1129    ///
1130    /// This is primarily useful for tests that need to drive [`WalletWrite::put_blocks`] with a
1131    /// `from_state` that is deliberately inconsistent with the wallet's stored note commitment
1132    /// tree state, in order to exercise the resulting error paths.
1133    pub fn try_scan_cached_blocks_with_state(
1134        &mut self,
1135        from_height: BlockHeight,
1136        from_state: &ChainState,
1137        limit: usize,
1138    ) -> Result<
1139        ScanSummary,
1140        super::chain::error::Error<
1141            <DbT as WalletRead>::Error,
1142            <Cache::BlockSource as BlockSource>::Error,
1143        >,
1144    > {
1145        scan_cached_blocks(
1146            &self.network,
1147            self.cache.block_source(),
1148            &mut self.wallet_data,
1149            from_height,
1150            from_state,
1151            limit,
1152        )
1153    }
1154
1155    /// Insert shard roots for both trees.
1156    pub fn put_subtree_roots(
1157        &mut self,
1158        sapling_start_index: u64,
1159        sapling_roots: &[CommitmentTreeRoot<::sapling::Node>],
1160        #[cfg(feature = "orchard")] orchard_start_index: u64,
1161        #[cfg(feature = "orchard")] orchard_roots: &[CommitmentTreeRoot<MerkleHashOrchard>],
1162    ) -> Result<(), ShardTreeError<<DbT as WalletCommitmentTrees>::Error>> {
1163        self.wallet_mut()
1164            .put_sapling_subtree_roots(sapling_start_index, sapling_roots)?;
1165
1166        #[cfg(feature = "orchard")]
1167        self.wallet_mut()
1168            .put_orchard_subtree_roots(orchard_start_index, orchard_roots)?;
1169
1170        Ok(())
1171    }
1172
1173    /// Generates `n` empty blocks, scans each, and returns the wallet's resulting fully-scanned
1174    /// height.
1175    ///
1176    /// This is the "let the chain advance" step of a test that needs the scanned region to reach a
1177    /// chosen depth above some earlier height — an anchor boundary a fixed number of blocks below
1178    /// the tip, say — with none of the intervening blocks carrying wallet-relevant data.
1179    pub fn generate_and_scan_empty_blocks(&mut self, n: usize) -> BlockHeight {
1180        for _ in 0..n {
1181            let (height, _) = self.generate_empty_block();
1182            self.scan_cached_blocks(height, 1);
1183        }
1184        self.wallet()
1185            .block_fully_scanned()
1186            .expect("the wallet reports its fully-scanned block")
1187            .expect("the wallet is fully scanned")
1188            .block_height()
1189    }
1190
1191    /// The root of the wallet's own Orchard note commitment tree at the checkpoint `height`, as an
1192    /// anchor: the value a transaction proved against that height would have installed.
1193    ///
1194    /// `None` when the tree holds no checkpoint there; the tree's own error when it holds one but
1195    /// cannot complete a root over the shard data it retains.
1196    #[cfg(feature = "orchard")]
1197    pub fn orchard_anchor_at(
1198        &mut self,
1199        height: BlockHeight,
1200    ) -> Result<Option<::orchard::Anchor>, ShardTreeError<<DbT as WalletCommitmentTrees>::Error>>
1201    {
1202        self.wallet_mut()
1203            .with_orchard_tree_mut(|tree| tree.root_at_checkpoint_id(&height))
1204            .map(|root| root.map(::orchard::Anchor::from))
1205    }
1206}
1207
1208impl<Cache, DbT, ParamsT, AccountIdT, ErrT> TestState<Cache, DbT, ParamsT>
1209where
1210    ParamsT: consensus::Parameters + Send + 'static,
1211    AccountIdT: std::fmt::Debug + std::cmp::Eq + std::hash::Hash,
1212    ErrT: std::fmt::Debug,
1213    DbT: InputSource<AccountId = AccountIdT, Error = ErrT>
1214        + WalletTest
1215        + WalletRead<AccountId = AccountIdT, Error = ErrT>
1216        + WalletWrite
1217        + WalletCommitmentTrees,
1218    <DbT as WalletRead>::AccountId: ConditionallySelectable + Default + Send + 'static,
1219{
1220    // Creates a transaction that sends the specified value from the given account to
1221    // the provided recipient address, using a greedy input selector and the default
1222    // mutli-output change strategy.
1223    pub fn create_standard_transaction(
1224        &mut self,
1225        from_account: &TestAccount<DbT::Account>,
1226        to: ZcashAddress,
1227        value: Zatoshis,
1228    ) -> Result<
1229        NonEmpty<TxId>,
1230        super::wallet::TransferErrT<
1231            DbT,
1232            GreedyInputSelector<DbT>,
1233            standard::MultiOutputChangeStrategy<DbT>,
1234        >,
1235    > {
1236        let input_selector = GreedyInputSelector::new();
1237
1238        #[cfg(not(feature = "orchard"))]
1239        let fallback_change_pool = ShieldedPool::Sapling;
1240        #[cfg(feature = "orchard")]
1241        let fallback_change_pool = ShieldedPool::Orchard;
1242
1243        let change_strategy =
1244            single_output_change_strategy(StandardFeeRule::Zip317, None, fallback_change_pool);
1245
1246        let request =
1247            zip321::TransactionRequest::new(vec![Payment::without_memo(to, value)]).unwrap();
1248
1249        self.spend(
1250            &input_selector,
1251            &change_strategy,
1252            from_account.usk(),
1253            request,
1254            OvkPolicy::Sender,
1255            ConfirmationsPolicy::MIN,
1256        )
1257    }
1258
1259    /// Prepares and executes the given [`zip321::TransactionRequest`] in a single step.
1260    #[allow(clippy::type_complexity)]
1261    pub fn spend<InputsT, ChangeT>(
1262        &mut self,
1263        input_selector: &InputsT,
1264        change_strategy: &ChangeT,
1265        usk: &UnifiedSpendingKey,
1266        request: zip321::TransactionRequest,
1267        ovk_policy: OvkPolicy,
1268        confirmations_policy: ConfirmationsPolicy,
1269    ) -> Result<NonEmpty<TxId>, super::wallet::TransferErrT<DbT, InputsT, ChangeT>>
1270    where
1271        InputsT: InputSelector<InputSource = DbT>,
1272        ChangeT: ChangeStrategy<MetaSource = DbT>,
1273    {
1274        let network = self.network().clone();
1275
1276        let account = self
1277            .wallet()
1278            .get_account_for_ufvk(&usk.to_unified_full_viewing_key())
1279            .map_err(Error::DataSource)?
1280            .ok_or(Error::KeyNotRecognized)?;
1281
1282        let proposal = propose_transfer(
1283            self.wallet_mut(),
1284            &network,
1285            account.id(),
1286            input_selector,
1287            change_strategy,
1288            request,
1289            confirmations_policy,
1290            &SpendPolicy::default(),
1291            None,
1292            None,
1293        )?;
1294
1295        let clock = self.clock.clone();
1296        create_proposed_transactions(
1297            &mut self.wallet_data,
1298            &network,
1299            &clock,
1300            &mut self.rng,
1301            &MockSpendProver,
1302            &MockOutputProver,
1303            &SpendingKeys::from_unified_spending_key(usk.clone()),
1304            ovk_policy,
1305            &proposal,
1306            None,
1307        )
1308    }
1309
1310    /// Invokes [`propose_transfer`] with the given arguments.
1311    #[allow(clippy::type_complexity)]
1312    pub fn propose_transfer<InputsT, ChangeT>(
1313        &mut self,
1314        spend_from_account: <DbT as InputSource>::AccountId,
1315        input_selector: &InputsT,
1316        change_strategy: &ChangeT,
1317        request: zip321::TransactionRequest,
1318        confirmations_policy: ConfirmationsPolicy,
1319    ) -> Result<
1320        Proposal<ChangeT::FeeRule, <DbT as InputSource>::NoteRef>,
1321        super::wallet::ProposeTransferErrT<DbT, Infallible, InputsT, ChangeT>,
1322    >
1323    where
1324        InputsT: InputSelector<InputSource = DbT>,
1325        ChangeT: ChangeStrategy<MetaSource = DbT>,
1326    {
1327        let network = self.network().clone();
1328        propose_transfer::<_, _, _, _, Infallible>(
1329            self.wallet_mut(),
1330            &network,
1331            spend_from_account,
1332            input_selector,
1333            change_strategy,
1334            request,
1335            confirmations_policy,
1336            &SpendPolicy::default(),
1337            None,
1338            None,
1339        )
1340    }
1341
1342    /// Invokes [`propose_transfer`] with the given arguments and an explicit
1343    /// [`SpendPolicy`].
1344    ///
1345    /// Unlike [`Self::propose_transfer`], which always uses the default spend
1346    /// policy (every shielded pool, no transparent), this allows tests to opt in
1347    /// to spending the account's transparent UTXOs or to restrict the shielded
1348    /// pools notes may be drawn from.
1349    #[allow(clippy::type_complexity)]
1350    pub fn propose_transfer_with_policy<InputsT, ChangeT>(
1351        &mut self,
1352        spend_from_account: <DbT as InputSource>::AccountId,
1353        input_selector: &InputsT,
1354        change_strategy: &ChangeT,
1355        request: zip321::TransactionRequest,
1356        confirmations_policy: ConfirmationsPolicy,
1357        spend_policy: &SpendPolicy,
1358    ) -> Result<
1359        Proposal<ChangeT::FeeRule, <DbT as InputSource>::NoteRef>,
1360        super::wallet::ProposeTransferErrT<DbT, Infallible, InputsT, ChangeT>,
1361    >
1362    where
1363        InputsT: InputSelector<InputSource = DbT>,
1364        ChangeT: ChangeStrategy<MetaSource = DbT>,
1365    {
1366        let network = self.network().clone();
1367        propose_transfer::<_, _, _, _, Infallible>(
1368            self.wallet_mut(),
1369            &network,
1370            spend_from_account,
1371            input_selector,
1372            change_strategy,
1373            request,
1374            confirmations_policy,
1375            spend_policy,
1376            None,
1377            None,
1378        )
1379    }
1380
1381    /// Invokes [`propose_transfer`] with the given arguments.
1382    #[allow(clippy::type_complexity)]
1383    pub fn propose_send_max_transfer<FeeRuleT>(
1384        &mut self,
1385        spend_from_account: <DbT as InputSource>::AccountId,
1386        fee_rule: &FeeRuleT,
1387        to: ZcashAddress,
1388        memo: Option<MemoBytes>,
1389        mode: MaxSpendMode,
1390        confirmations_policy: ConfirmationsPolicy,
1391    ) -> Result<
1392        Proposal<FeeRuleT, <DbT as InputSource>::NoteRef>,
1393        super::wallet::ProposeSendMaxErrT<DbT, Infallible, FeeRuleT>,
1394    >
1395    where
1396        FeeRuleT: FeeRule + Clone,
1397    {
1398        let network = self.network().clone();
1399        propose_send_max_transfer::<_, _, _, Infallible>(
1400            self.wallet_mut(),
1401            &network,
1402            spend_from_account,
1403            &[ShieldedPool::Sapling, ShieldedPool::Orchard],
1404            fee_rule,
1405            to,
1406            memo,
1407            mode,
1408            confirmations_policy,
1409            &LockedInputPolicy::Exclude,
1410            None,
1411        )
1412    }
1413
1414    /// Invokes [`propose_standard_transfer_to_address`] with the given arguments.
1415    #[allow(clippy::type_complexity)]
1416    #[allow(clippy::too_many_arguments)]
1417    pub fn propose_standard_transfer<CommitmentTreeErrT>(
1418        &mut self,
1419        spend_from_account: <DbT as InputSource>::AccountId,
1420        fee_rule: StandardFeeRule,
1421        confirmations_policy: ConfirmationsPolicy,
1422        to: &Address,
1423        amount: Zatoshis,
1424        memo: Option<MemoBytes>,
1425        change_memo: Option<MemoBytes>,
1426        fallback_change_pool: ShieldedPool,
1427    ) -> Result<
1428        Proposal<StandardFeeRule, <DbT as InputSource>::NoteRef>,
1429        super::wallet::ProposeTransferErrT<
1430            DbT,
1431            CommitmentTreeErrT,
1432            GreedyInputSelector<DbT>,
1433            SingleOutputChangeStrategy<DbT>,
1434        >,
1435    > {
1436        let network = self.network().clone();
1437        let result = propose_standard_transfer_to_address::<_, _, CommitmentTreeErrT>(
1438            self.wallet_mut(),
1439            &network,
1440            fee_rule,
1441            spend_from_account,
1442            confirmations_policy,
1443            to,
1444            amount,
1445            memo,
1446            change_memo,
1447            fallback_change_pool,
1448            None,
1449            None,
1450        );
1451
1452        if let Ok(proposal) = &result {
1453            check_proposal_serialization_roundtrip(&network, self.wallet(), proposal);
1454        }
1455
1456        result
1457    }
1458
1459    /// Invokes [`propose_shielding`] with the given arguments.
1460    ///
1461    /// [`propose_shielding`]: crate::data_api::wallet::propose_shielding
1462    #[cfg(feature = "transparent-inputs")]
1463    #[allow(clippy::type_complexity)]
1464    #[allow(clippy::too_many_arguments)]
1465    #[allow(dead_code)]
1466    pub fn propose_shielding<InputsT, ChangeT>(
1467        &mut self,
1468        input_selector: &InputsT,
1469        change_strategy: &ChangeT,
1470        shielding_threshold: Zatoshis,
1471        from_addrs: &[TransparentAddress],
1472        to_account: <InputsT::InputSource as InputSource>::AccountId,
1473        confirmations_policy: ConfirmationsPolicy,
1474        output_filter: CoinbaseFilter,
1475    ) -> Result<
1476        Proposal<ChangeT::FeeRule, Infallible>,
1477        super::wallet::ProposeShieldingErrT<DbT, Infallible, InputsT, ChangeT>,
1478    >
1479    where
1480        InputsT: ShieldingSelector<InputSource = DbT>,
1481        ChangeT: ChangeStrategy<MetaSource = DbT>,
1482    {
1483        let network = self.network().clone();
1484        propose_shielding::<_, _, _, _, Infallible>(
1485            self.wallet_mut(),
1486            &network,
1487            input_selector,
1488            change_strategy,
1489            shielding_threshold,
1490            from_addrs,
1491            to_account,
1492            confirmations_policy,
1493            output_filter,
1494            None,
1495        )
1496    }
1497
1498    /// Invokes [`propose_shielding_coinbase`] with the given arguments.
1499    ///
1500    /// [`propose_shielding_coinbase`]: crate::data_api::wallet::propose_shielding_coinbase
1501    #[cfg(feature = "transparent-inputs")]
1502    #[allow(clippy::type_complexity)]
1503    #[allow(clippy::too_many_arguments)]
1504    #[allow(dead_code)]
1505    pub fn propose_shielding_coinbase<InputsT, FeeRuleT>(
1506        &mut self,
1507        input_selector: &InputsT,
1508        fee_rule: &FeeRuleT,
1509        shielding_threshold: Zatoshis,
1510        from_addrs: &[TransparentAddress],
1511        to_address: zcash_address::ZcashAddress,
1512        memo: Option<zcash_protocol::memo::MemoBytes>,
1513        limit: Option<usize>,
1514    ) -> Result<
1515        Proposal<FeeRuleT, Infallible>,
1516        super::wallet::ProposeShieldingCoinbaseErrT<DbT, Infallible, InputsT, FeeRuleT>,
1517    >
1518    where
1519        InputsT: ShieldingSelector<InputSource = DbT>,
1520        FeeRuleT: zcash_primitives::transaction::fees::FeeRule + Clone,
1521    {
1522        let network = self.network().clone();
1523        propose_shielding_coinbase::<_, _, _, _, Infallible>(
1524            self.wallet_mut(),
1525            &network,
1526            input_selector,
1527            fee_rule,
1528            shielding_threshold,
1529            from_addrs,
1530            to_address,
1531            memo,
1532            limit,
1533            None,
1534        )
1535    }
1536
1537    /// Invokes [`create_proposed_transactions`] with the given arguments.
1538    #[allow(clippy::type_complexity)]
1539    pub fn create_proposed_transactions<InputsErrT, FeeRuleT, ChangeErrT, N>(
1540        &mut self,
1541        usk: &UnifiedSpendingKey,
1542        ovk_policy: OvkPolicy,
1543        proposal: &Proposal<FeeRuleT, N>,
1544    ) -> Result<NonEmpty<TxId>, super::wallet::CreateErrT<DbT, InputsErrT, FeeRuleT, ChangeErrT, N>>
1545    where
1546        FeeRuleT: FeeRule,
1547    {
1548        let network = self.network().clone();
1549        let clock = self.clock.clone();
1550        create_proposed_transactions(
1551            &mut self.wallet_data,
1552            &network,
1553            &clock,
1554            &mut self.rng,
1555            &MockSpendProver,
1556            &MockOutputProver,
1557            &SpendingKeys::from_unified_spending_key(usk.clone()),
1558            ovk_policy,
1559            proposal,
1560            None,
1561        )
1562    }
1563
1564    /// Invokes [`create_pczt_from_proposal`] with the given arguments.
1565    ///
1566    /// [`create_pczt_from_proposal`]: super::wallet::create_pczt_from_proposal
1567    #[cfg(feature = "pczt")]
1568    #[allow(clippy::type_complexity)]
1569    pub fn create_pczt_from_proposal<InputsErrT, FeeRuleT, ChangeErrT>(
1570        &mut self,
1571        spend_from_account: <DbT as InputSource>::AccountId,
1572        ovk_policy: OvkPolicy,
1573        proposal: &Proposal<FeeRuleT, <DbT as InputSource>::NoteRef>,
1574        expiry_height: Option<BlockHeight>,
1575    ) -> Result<
1576        pczt::Pczt,
1577        super::wallet::CreateErrT<DbT, InputsErrT, FeeRuleT, ChangeErrT, DbT::NoteRef>,
1578    >
1579    where
1580        <DbT as WalletRead>::AccountId: serde::Serialize,
1581        FeeRuleT: FeeRule,
1582    {
1583        let network = self.network().clone();
1584
1585        let clock = self.clock.clone();
1586        create_pczt_from_proposal(
1587            &mut self.wallet_data,
1588            &network,
1589            &clock,
1590            &mut self.rng,
1591            spend_from_account,
1592            ovk_policy,
1593            proposal,
1594            expiry_height,
1595            ::zcash_primitives::transaction::builder::BundlePadding::DEFAULT,
1596        )
1597    }
1598
1599    /// Invokes [`extract_and_store_transaction_from_pczt`] with the given arguments.
1600    ///
1601    /// [`extract_and_store_transaction_from_pczt`]: super::wallet::extract_and_store_transaction_from_pczt
1602    #[cfg(feature = "pczt")]
1603    #[allow(clippy::type_complexity)]
1604    pub fn extract_and_store_transaction_from_pczt(
1605        &mut self,
1606        pczt: pczt::Pczt,
1607    ) -> Result<TxId, super::wallet::ExtractErrT<DbT, DbT::NoteRef>>
1608    where
1609        <DbT as WalletRead>::AccountId: serde::de::DeserializeOwned,
1610    {
1611        let prover = real_test_prover();
1612        let (spend_vk, output_vk) = prover.verifying_keys();
1613
1614        let clock = self.clock.clone();
1615        extract_and_store_transaction_from_pczt(
1616            &mut self.wallet_data,
1617            &clock,
1618            &mut self.rng,
1619            pczt,
1620            Some((&spend_vk, &output_vk)),
1621            None,
1622        )
1623    }
1624
1625    /// Invokes [`shield_transparent_funds`] with the given arguments.
1626    ///
1627    /// [`shield_transparent_funds`]: crate::data_api::wallet::shield_transparent_funds
1628    #[cfg(feature = "transparent-inputs")]
1629    #[allow(clippy::type_complexity)]
1630    #[allow(clippy::too_many_arguments)]
1631    pub fn shield_transparent_funds<InputsT, ChangeT>(
1632        &mut self,
1633        input_selector: &InputsT,
1634        change_strategy: &ChangeT,
1635        shielding_threshold: Zatoshis,
1636        usk: &UnifiedSpendingKey,
1637        from_addrs: &[TransparentAddress],
1638        to_account: <DbT as InputSource>::AccountId,
1639        confirmations_policy: ConfirmationsPolicy,
1640    ) -> Result<NonEmpty<TxId>, super::wallet::ShieldErrT<DbT, InputsT, ChangeT>>
1641    where
1642        InputsT: ShieldingSelector<InputSource = DbT>,
1643        ChangeT: ChangeStrategy<MetaSource = DbT>,
1644    {
1645        let network = self.network().clone();
1646        let clock = self.clock.clone();
1647        shield_transparent_funds(
1648            &mut self.wallet_data,
1649            &network,
1650            &clock,
1651            &mut self.rng,
1652            &MockSpendProver,
1653            &MockOutputProver,
1654            input_selector,
1655            change_strategy,
1656            shielding_threshold,
1657            &SpendingKeys::from_unified_spending_key(usk.clone()),
1658            from_addrs,
1659            to_account,
1660            confirmations_policy,
1661        )
1662    }
1663
1664    fn with_account_balance<T, F: FnOnce(&AccountBalance) -> T>(
1665        &self,
1666        account: AccountIdT,
1667        confirmations_policy: ConfirmationsPolicy,
1668        f: F,
1669    ) -> T {
1670        let binding = self
1671            .wallet()
1672            .get_wallet_summary(confirmations_policy)
1673            .unwrap()
1674            .unwrap();
1675        f(binding.account_balances().get(&account).unwrap())
1676    }
1677
1678    /// Returns the total balance in the given account at this point in the test.
1679    pub fn get_total_balance(&self, account: AccountIdT) -> Zatoshis {
1680        self.with_account_balance(account, ConfirmationsPolicy::MIN, |balance| balance.total())
1681    }
1682
1683    /// Returns the locked balance in the given account at this point in the test.
1684    pub fn get_locked_balance(&self, account: AccountIdT) -> Zatoshis {
1685        self.with_account_balance(account, ConfirmationsPolicy::MIN, |balance| {
1686            balance.locked_value()
1687        })
1688    }
1689
1690    /// Returns the balance in the given account that is spendable with the given number
1691    /// of confirmations at this point in the test.
1692    pub fn get_spendable_balance(
1693        &self,
1694        account: AccountIdT,
1695        confirmations_policy: ConfirmationsPolicy,
1696    ) -> Zatoshis {
1697        self.with_account_balance(account, confirmations_policy, |balance| {
1698            balance.spendable_value()
1699        })
1700    }
1701
1702    /// Returns the balance in the given account that is detected but not yet spendable
1703    /// with the given number of confirmations at this point in the test.
1704    pub fn get_pending_shielded_balance(
1705        &self,
1706        account: AccountIdT,
1707        confirmations_policy: ConfirmationsPolicy,
1708    ) -> Zatoshis {
1709        self.with_account_balance(account, confirmations_policy, |balance| {
1710            balance.value_pending_spendability() + balance.change_pending_confirmation()
1711        })
1712        .unwrap()
1713    }
1714
1715    /// Returns the amount of change in the given account that is not yet spendable with
1716    /// the given number of confirmations at this point in the test.
1717    #[allow(dead_code)]
1718    pub fn get_pending_change(
1719        &self,
1720        account: AccountIdT,
1721        confirmations_policy: ConfirmationsPolicy,
1722    ) -> Zatoshis {
1723        self.with_account_balance(account, confirmations_policy, |balance| {
1724            balance.change_pending_confirmation()
1725        })
1726    }
1727
1728    /// Returns a summary of the wallet at this point in the test.
1729    pub fn get_wallet_summary(
1730        &self,
1731        confirmations_policy: ConfirmationsPolicy,
1732    ) -> Option<WalletSummary<AccountIdT>> {
1733        self.wallet()
1734            .get_wallet_summary(confirmations_policy)
1735            .unwrap()
1736    }
1737}
1738
1739impl<Cache, DbT, ParamsT, AccountIdT, ErrT> TestState<Cache, DbT, ParamsT>
1740where
1741    ParamsT: consensus::Parameters + Send + 'static,
1742    AccountIdT: std::cmp::Eq + std::hash::Hash,
1743    ErrT: std::fmt::Debug,
1744    DbT: InputSource<AccountId = AccountIdT, Error = ErrT>
1745        + WalletTest
1746        + WalletRead<AccountId = AccountIdT, Error = ErrT>
1747        + WalletWrite
1748        + WalletCommitmentTrees,
1749    <DbT as WalletRead>::AccountId: ConditionallySelectable + Default + Send + 'static,
1750{
1751    /// Returns a transaction from the history.
1752    #[allow(dead_code)]
1753    pub fn get_tx_from_history(
1754        &self,
1755        txid: TxId,
1756    ) -> Result<Option<TransactionSummary<AccountIdT>>, ErrT> {
1757        let history = self.wallet().get_tx_history()?;
1758        Ok(history.into_iter().find(|tx| tx.txid() == txid))
1759    }
1760}
1761
1762impl<Cache, DbT: WalletRead + Reset> TestState<Cache, DbT, LocalNetwork> {
1763    /// Resets the wallet using a new wallet database but with the same cache of blocks,
1764    /// and returns the old wallet database file.
1765    ///
1766    /// This does not recreate accounts, nor does it rescan the cached blocks.
1767    /// The resulting wallet has no test account.
1768    /// Before using any `generate_*` method on the reset state, call `reset_latest_cached_block()`.
1769    pub fn reset(&mut self) -> DbT::Handle {
1770        self.latest_block_height = None;
1771        self.test_account = None;
1772        DbT::reset(self)
1773    }
1774
1775    //    /// Reset the latest cached block to the most recent one in the cache database.
1776    //    #[allow(dead_code)]
1777    //    pub fn reset_latest_cached_block(&mut self) {
1778    //        self.cache
1779    //            .block_source()
1780    //            .with_blocks::<_, Infallible>(None, None, |block: CompactBlock| {
1781    //                let chain_metadata = block.chain_metadata.unwrap();
1782    //                self.latest_cached_block = Some(CachedBlock::at(
1783    //                    BlockHash::from_slice(block.hash.as_slice()),
1784    //                    BlockHeight::from_u32(block.height.try_into().unwrap()),
1785    //                    chain_metadata.sapling_commitment_tree_size,
1786    //                    chain_metadata.orchard_commitment_tree_size,
1787    //                ));
1788    //                Ok(())
1789    //            })
1790    //            .unwrap();
1791    //    }
1792}
1793
1794pub fn single_output_change_strategy<DbT: InputSource>(
1795    fee_rule: StandardFeeRule,
1796    change_memo: Option<&str>,
1797    fallback_change_pool: ShieldedPool,
1798) -> standard::SingleOutputChangeStrategy<DbT> {
1799    let change_memo = change_memo.map(|m| MemoBytes::from(m.parse::<Memo>().unwrap()));
1800    standard::SingleOutputChangeStrategy::new(
1801        fee_rule,
1802        change_memo,
1803        fallback_change_pool,
1804        DustOutputPolicy::default(),
1805    )
1806}
1807
1808// Checks that a protobuf proposal serialized from the provided proposal value correctly parses to
1809// the same proposal value.
1810fn check_proposal_serialization_roundtrip<ParamsT: consensus::Parameters, DbT: InputSource>(
1811    params: &ParamsT,
1812    wallet_data: &DbT,
1813    proposal: &Proposal<StandardFeeRule, DbT::NoteRef>,
1814) {
1815    let proposal_proto = crate::proto::proposal::Proposal::from_standard_proposal(proposal);
1816    let deserialized_proposal = proposal_proto.try_into_standard_proposal(params, wallet_data);
1817    assert_matches!(deserialized_proposal, Ok(r) if &r == proposal);
1818}
1819
1820/// The initial chain state for a test.
1821///
1822/// This is returned from the closure passed to [`TestBuilder::with_initial_chain_state`]
1823/// to configure the test state with a starting chain position, to which subsequent test
1824/// activity is applied.
1825pub struct InitialChainState {
1826    /// Information about the chain's state as of the chain tip.
1827    pub chain_state: ChainState,
1828    /// Roots of the completed Sapling subtrees as of this chain state.
1829    pub prior_sapling_roots: Vec<CommitmentTreeRoot<::sapling::Node>>,
1830    /// Roots of the completed Orchard subtrees as of this chain state.
1831    #[cfg(feature = "orchard")]
1832    pub prior_orchard_roots: Vec<CommitmentTreeRoot<MerkleHashOrchard>>,
1833}
1834
1835/// Trait representing the ability to construct a new data store for use in a test.
1836pub trait DataStoreFactory {
1837    type Error: core::fmt::Debug;
1838    type AccountId: std::fmt::Debug
1839        + ConditionallySelectable
1840        + Default
1841        + Hash
1842        + Eq
1843        + Send
1844        + Sync
1845        + 'static;
1846    type Account: Account<AccountId = Self::AccountId> + Clone;
1847    type DsError: core::fmt::Debug;
1848    type DataStore: InputSource<AccountId = Self::AccountId, Error = Self::DsError>
1849        + WalletRead<AccountId = Self::AccountId, Account = Self::Account, Error = Self::DsError>
1850        + WalletTest
1851        + WalletWrite
1852        + WalletCommitmentTrees;
1853
1854    /// Constructs a new data store.
1855    fn new_data_store(
1856        &self,
1857        network: LocalNetwork,
1858        anchor_retention_interval: Option<AnchorRetentionInterval>,
1859        #[cfg(feature = "transparent-inputs")] gap_limits: Option<GapLimits>,
1860    ) -> Result<Self::DataStore, Self::Error>;
1861}
1862
1863/// A [`TestState`] builder, that configures the environment for a test.
1864pub struct TestBuilder<Cache, DataStoreFactory> {
1865    rng: ChaChaRng,
1866    network: LocalNetwork,
1867    cache: Cache,
1868    ds_factory: DataStoreFactory,
1869    initial_chain_state: Option<InitialChainState>,
1870    account_birthday: Option<AccountBirthday>,
1871    account_index: Option<zip32::AccountId>,
1872    anchor_retention_interval: Option<AnchorRetentionInterval>,
1873    #[cfg(feature = "transparent-inputs")]
1874    gap_limits: Option<GapLimits>,
1875}
1876
1877impl TestBuilder<(), ()> {
1878    /// The default network used by [`TestBuilder::new`].
1879    ///
1880    /// This is a fake network where Sapling through NU5 activate at the same height. We
1881    /// pick height 100,000 to be large enough to handle any hard-coded test offsets.
1882    pub const DEFAULT_NETWORK: LocalNetwork = LocalNetwork {
1883        overwinter: Some(BlockHeight::from_u32(1)),
1884        sapling: Some(BlockHeight::from_u32(100_000)),
1885        blossom: Some(BlockHeight::from_u32(100_000)),
1886        heartwood: Some(BlockHeight::from_u32(100_000)),
1887        canopy: Some(BlockHeight::from_u32(100_000)),
1888        nu5: Some(BlockHeight::from_u32(100_000)),
1889        nu6: None,
1890        nu6_1: None,
1891        nu6_2: None,
1892        nu6_3: None,
1893        nu7: None,
1894        #[cfg(zcash_unstable = "nutachyon")]
1895        nu_tachyon: None,
1896    };
1897
1898    /// Constructs a new test environment builder.
1899    pub fn new() -> Self {
1900        TestBuilder {
1901            rng: ChaChaRng::seed_from_u64(0),
1902            network: Self::DEFAULT_NETWORK,
1903            cache: (),
1904            ds_factory: (),
1905            initial_chain_state: None,
1906            account_birthday: None,
1907            account_index: None,
1908            anchor_retention_interval: None,
1909            #[cfg(feature = "transparent-inputs")]
1910            gap_limits: None,
1911        }
1912    }
1913}
1914
1915impl Default for TestBuilder<(), ()> {
1916    fn default() -> Self {
1917        Self::new()
1918    }
1919}
1920
1921impl<A> TestBuilder<(), A> {
1922    /// Adds a block cache to the test environment.
1923    pub fn with_block_cache<C>(self, cache: C) -> TestBuilder<C, A> {
1924        TestBuilder {
1925            rng: self.rng,
1926            network: self.network,
1927            cache,
1928            ds_factory: self.ds_factory,
1929            initial_chain_state: self.initial_chain_state,
1930            account_birthday: self.account_birthday,
1931            account_index: self.account_index,
1932            anchor_retention_interval: self.anchor_retention_interval,
1933            #[cfg(feature = "transparent-inputs")]
1934            gap_limits: self.gap_limits,
1935        }
1936    }
1937}
1938
1939impl<A> TestBuilder<A, ()> {
1940    /// Adds a wallet data store to the test environment.
1941    pub fn with_data_store_factory<DsFactory>(
1942        self,
1943        ds_factory: DsFactory,
1944    ) -> TestBuilder<A, DsFactory> {
1945        TestBuilder {
1946            rng: self.rng,
1947            network: self.network,
1948            cache: self.cache,
1949            ds_factory,
1950            initial_chain_state: self.initial_chain_state,
1951            account_birthday: self.account_birthday,
1952            account_index: self.account_index,
1953            anchor_retention_interval: self.anchor_retention_interval,
1954            #[cfg(feature = "transparent-inputs")]
1955            gap_limits: self.gap_limits,
1956        }
1957    }
1958}
1959
1960impl<A, B> TestBuilder<A, B> {
1961    /// Overrides the network parameters used by the test (the default is
1962    /// [`TestBuilder::DEFAULT_NETWORK`]). This must be called before the account birthday is
1963    /// established (i.e. before `with_account_from_sapling_activation` /
1964    /// `with_account_having_current_birthday`), because the birthday is derived from the network's
1965    /// activation heights.
1966    pub fn with_network(mut self, network: LocalNetwork) -> Self {
1967        self.network = network;
1968        self
1969    }
1970
1971    /// Overrides the interval on which the wallet retains durable anchor checkpoints (the default
1972    /// is [`AnchorRetentionInterval::ZIP_318`]).
1973    ///
1974    /// A test that must scan past a retained anchor otherwise has to generate 144 blocks per
1975    /// boundary; a short interval makes the same coverage cheap.
1976    pub fn with_anchor_retention_interval(mut self, interval: AnchorRetentionInterval) -> Self {
1977        self.anchor_retention_interval = Some(interval);
1978        self
1979    }
1980
1981    #[cfg(feature = "transparent-inputs")]
1982    pub fn with_gap_limits(self, gap_limits: GapLimits) -> TestBuilder<A, B> {
1983        TestBuilder {
1984            rng: self.rng,
1985            network: self.network,
1986            cache: self.cache,
1987            ds_factory: self.ds_factory,
1988            initial_chain_state: self.initial_chain_state,
1989            account_birthday: self.account_birthday,
1990            account_index: self.account_index,
1991            anchor_retention_interval: self.anchor_retention_interval,
1992            gap_limits: Some(gap_limits),
1993        }
1994    }
1995}
1996
1997impl<Cache, DsFactory> TestBuilder<Cache, DsFactory> {
1998    /// Configures the test to start with the given initial chain state.
1999    ///
2000    /// # Panics
2001    ///
2002    /// - Must not be called twice.
2003    /// - Must be called before [`Self::with_account_from_sapling_activation`] or
2004    ///   [`Self::with_account_having_current_birthday`].
2005    ///
2006    /// # Examples
2007    ///
2008    /// ```
2009    /// use std::num::NonZeroU8;
2010    ///
2011    /// use incrementalmerkletree::frontier::Frontier;
2012    /// use zcash_primitives::block::BlockHash;
2013    /// use zcash_protocol::consensus::{NetworkUpgrade, Parameters};
2014    /// use zcash_client_backend::data_api::{
2015    ///     chain::{ChainState, CommitmentTreeRoot},
2016    ///     testing::{InitialChainState, TestBuilder},
2017    /// };
2018    ///
2019    /// // For this test, we'll start inserting leaf notes 5 notes after the end of the
2020    /// // third subtree, with a gap of 10 blocks. After `scan_cached_blocks`, the scan
2021    /// // queue should have a requested scan range of 300..310 with `FoundNote` priority,
2022    /// // 310..320 with `Scanned` priority. We set both Sapling and Orchard to the same
2023    /// // initial tree size for simplicity.
2024    /// let prior_block_hash = BlockHash([0; 32]);
2025    /// let initial_sapling_tree_size: u32 = (0x1 << 16) * 3 + 5;
2026    /// let initial_orchard_tree_size: u32 = (0x1 << 16) * 3 + 5;
2027    /// let initial_height_offset = 310;
2028    ///
2029    /// let mut st = TestBuilder::new()
2030    ///     .with_initial_chain_state(|rng, network| {
2031    ///         // For simplicity, assume Sapling and NU5 activated at the same height.
2032    ///         let sapling_activation_height =
2033    ///             network.activation_height(NetworkUpgrade::Sapling).unwrap();
2034    ///
2035    ///         // Construct a fake chain state for the end of block 300
2036    ///         let (prior_sapling_roots, sapling_initial_tree) =
2037    ///             Frontier::random_with_prior_subtree_roots(
2038    ///                 rng,
2039    ///                 initial_sapling_tree_size.into(),
2040    ///                 NonZeroU8::new(16).unwrap(),
2041    ///             );
2042    ///         let prior_sapling_roots = prior_sapling_roots
2043    ///             .into_iter()
2044    ///             .zip(1u32..)
2045    ///             .map(|(root, i)| {
2046    ///                 CommitmentTreeRoot::from_parts(sapling_activation_height + (100 * i), root)
2047    ///             })
2048    ///             .collect::<Vec<_>>();
2049    ///
2050    ///         #[cfg(feature = "orchard")]
2051    ///         let (prior_orchard_roots, orchard_initial_tree) =
2052    ///             Frontier::random_with_prior_subtree_roots(
2053    ///                 rng,
2054    ///                 initial_orchard_tree_size.into(),
2055    ///                 NonZeroU8::new(16).unwrap(),
2056    ///             );
2057    ///         #[cfg(feature = "orchard")]
2058    ///         let prior_orchard_roots = prior_orchard_roots
2059    ///             .into_iter()
2060    ///             .zip(1u32..)
2061    ///             .map(|(root, i)| {
2062    ///                 CommitmentTreeRoot::from_parts(sapling_activation_height + (100 * i), root)
2063    ///             })
2064    ///             .collect::<Vec<_>>();
2065    ///
2066    ///         InitialChainState {
2067    ///             chain_state: ChainState::new(
2068    ///                 sapling_activation_height + initial_height_offset - 1,
2069    ///                 prior_block_hash,
2070    ///                 sapling_initial_tree,
2071    ///                 #[cfg(feature = "orchard")]
2072    ///                 orchard_initial_tree,
2073    ///                 #[cfg(feature = "orchard")]
2074    ///                 Frontier::empty(),
2075    ///             ),
2076    ///             prior_sapling_roots,
2077    ///             #[cfg(feature = "orchard")]
2078    ///             prior_orchard_roots,
2079    ///         }
2080    ///     });
2081    /// ```
2082    pub fn with_initial_chain_state(
2083        mut self,
2084        chain_state: impl FnOnce(&mut ChaChaRng, &LocalNetwork) -> InitialChainState,
2085    ) -> Self {
2086        assert!(self.initial_chain_state.is_none());
2087        assert!(self.account_birthday.is_none());
2088        self.initial_chain_state = Some(chain_state(&mut self.rng, &self.network));
2089        self
2090    }
2091
2092    /// Configures the environment with a [`TestAccount`] that has a birthday at Sapling
2093    /// activation.
2094    ///
2095    /// # Panics
2096    ///
2097    /// - Must not be called twice.
2098    /// - Do not call both [`Self::with_account_having_current_birthday`] and this method.
2099    pub fn with_account_from_sapling_activation(mut self, prev_hash: BlockHash) -> Self {
2100        assert!(self.account_birthday.is_none());
2101        self.account_birthday = Some(AccountBirthday::from_parts(
2102            ChainState::empty(
2103                self.network
2104                    .activation_height(NetworkUpgrade::Sapling)
2105                    .unwrap()
2106                    - 1,
2107                prev_hash,
2108            ),
2109            None,
2110        ));
2111        self
2112    }
2113
2114    /// Configures the environment with a [`TestAccount`] that has a birthday one block
2115    /// after the initial chain state.
2116    ///
2117    /// # Panics
2118    ///
2119    /// - Must not be called twice.
2120    /// - Must call [`Self::with_initial_chain_state`] before calling this method.
2121    /// - Do not call both [`Self::with_account_from_sapling_activation`] and this method.
2122    pub fn with_account_having_current_birthday(mut self) -> Self {
2123        assert!(self.account_birthday.is_none());
2124        assert!(self.initial_chain_state.is_some());
2125        self.account_birthday = Some(AccountBirthday::from_parts(
2126            self.initial_chain_state
2127                .as_ref()
2128                .unwrap()
2129                .chain_state
2130                .clone(),
2131            None,
2132        ));
2133        self
2134    }
2135
2136    /// Sets the account index for the test account.
2137    ///
2138    /// Does nothing unless either [`Self::with_account_from_sapling_activation`] or
2139    /// [`Self::with_account_having_current_birthday`] is also called.
2140    ///
2141    /// # Panics
2142    ///
2143    /// - Must not be called twice.
2144    pub fn set_account_index(mut self, index: zip32::AccountId) -> Self {
2145        assert!(self.account_index.is_none());
2146        self.account_index = Some(index);
2147        self
2148    }
2149}
2150
2151impl<Cache, DsFactory: DataStoreFactory> TestBuilder<Cache, DsFactory> {
2152    /// Builds the state for this test.
2153    pub fn build(self) -> TestState<Cache, DsFactory::DataStore, LocalNetwork> {
2154        let mut cached_blocks = BTreeMap::new();
2155        let mut wallet_data = self
2156            .ds_factory
2157            .new_data_store(
2158                self.network,
2159                self.anchor_retention_interval,
2160                #[cfg(feature = "transparent-inputs")]
2161                self.gap_limits,
2162            )
2163            .unwrap();
2164
2165        if let Some(initial_state) = &self.initial_chain_state {
2166            wallet_data
2167                .put_sapling_subtree_roots(0, &initial_state.prior_sapling_roots)
2168                .unwrap();
2169            wallet_data
2170                .with_sapling_tree_mut(|t| {
2171                    t.insert_frontier(
2172                        initial_state.chain_state.final_sapling_tree().clone(),
2173                        Retention::Checkpoint {
2174                            id: initial_state.chain_state.block_height(),
2175                            marking: Marking::Reference,
2176                        },
2177                    )
2178                })
2179                .unwrap();
2180
2181            #[cfg(feature = "orchard")]
2182            {
2183                wallet_data
2184                    .put_orchard_subtree_roots(0, &initial_state.prior_orchard_roots)
2185                    .unwrap();
2186                wallet_data
2187                    .with_orchard_tree_mut(|t| {
2188                        t.insert_frontier(
2189                            initial_state.chain_state.final_orchard_tree().clone(),
2190                            Retention::Checkpoint {
2191                                id: initial_state.chain_state.block_height(),
2192                                marking: Marking::Reference,
2193                            },
2194                        )
2195                    })
2196                    .unwrap();
2197            }
2198
2199            let final_sapling_tree_size =
2200                initial_state.chain_state.final_sapling_tree().tree_size() as u32;
2201            let _final_orchard_tree_size = 0;
2202            #[cfg(feature = "orchard")]
2203            let _final_orchard_tree_size =
2204                initial_state.chain_state.final_orchard_tree().tree_size() as u32;
2205            let _final_ironwood_tree_size = 0;
2206            #[cfg(feature = "orchard")]
2207            let _final_ironwood_tree_size =
2208                initial_state.chain_state.final_ironwood_tree().tree_size() as u32;
2209
2210            cached_blocks.insert(
2211                initial_state.chain_state.block_height(),
2212                CachedBlock {
2213                    chain_state: initial_state.chain_state.clone(),
2214                    sapling_end_size: final_sapling_tree_size,
2215                    orchard_end_size: _final_orchard_tree_size,
2216                    ironwood_end_size: _final_ironwood_tree_size,
2217                },
2218            );
2219        };
2220
2221        let test_account = self.account_birthday.map(|birthday| {
2222            let seed = Secret::new(vec![0u8; 32]);
2223            let (account, usk) = match self.account_index {
2224                Some(index) => wallet_data
2225                    .import_account_hd("", &seed, index, &birthday, None)
2226                    .expect("test account import succeeds"),
2227                None => {
2228                    let result = wallet_data
2229                        .create_account("", &seed, &birthday, None)
2230                        .expect("test account creation succeeds");
2231                    (
2232                        wallet_data
2233                            .get_account(result.0)
2234                            .expect("retrieval of just-created account succeeds")
2235                            .expect("an account was created"),
2236                        result.1,
2237                    )
2238                }
2239            };
2240            (
2241                seed,
2242                TestAccount {
2243                    account,
2244                    usk,
2245                    birthday,
2246                },
2247            )
2248        });
2249
2250        TestState {
2251            cache: self.cache,
2252            cached_blocks,
2253            latest_block_height: self
2254                .initial_chain_state
2255                .map(|s| s.chain_state.block_height()),
2256            wallet_data,
2257            network: self.network,
2258            test_account,
2259            rng: self.rng,
2260            clock: FixedClock::new(std::time::UNIX_EPOCH + TEST_CLOCK_EPOCH_OFFSET),
2261        }
2262    }
2263}
2264
2265/// Trait used by tests that require a full viewing key.
2266pub trait TestFvk: Clone {
2267    /// The type of nullifier corresponding to the kind of note that this full viewing key
2268    /// can detect (and that its corresponding spending key can spend).
2269    type Nullifier: Copy;
2270    /// The type of outgoing viewing key corresponding to this full viewing key;
2271    type OutgoingViewingKey;
2272
2273    /// Returns the [`Self::OutgoingViewingKey`] corresponding to this full viewing key, for the
2274    /// given scope.
2275    fn to_ovk(&self, scope: zip32::Scope) -> Self::OutgoingViewingKey;
2276
2277    /// Returns the bytes of the [`Self::OutgoingViewingKey`] corresponding to this full viewing
2278    /// key, for the given scope.
2279    fn ovk_bytes(&self, scope: zip32::Scope) -> [u8; 32];
2280
2281    /// Adds a single spend to the given [`CompactTx`] of a note previously received by
2282    /// this full viewing key.
2283    fn add_spend<R: Rng + CryptoRng>(&self, ctx: &mut CompactTx, nf: Self::Nullifier, rng: &mut R);
2284
2285    /// Adds a single output to the given [`CompactTx`], where the output will be discovered when
2286    /// scanning with an incoming viewing key corresponding to this FVK. Its outputs will also be
2287    /// discoverable when scanning with the provided OVK, if any.
2288    ///
2289    /// `recipient_address_type` allows configuring what shielded address to produce from this FVK
2290    /// as the recipient of the newly created output.
2291    ///
2292    /// Returns the nullifier of the newly created note, so that tests can readily have it on hand
2293    /// for the purpose of spending that note.
2294    #[allow(clippy::too_many_arguments)]
2295    fn add_output<P: consensus::Parameters, R: Rng + CryptoRng>(
2296        &self,
2297        ctx: &mut CompactTx,
2298        params: &P,
2299        height: BlockHeight,
2300        sender_ovk: Option<&Self::OutgoingViewingKey>,
2301        recipient_address_type: AddressType,
2302        value: Zatoshis,
2303        initial_sapling_tree_size: u32,
2304        // we don't require an initial Orchard tree size because we don't need it to compute
2305        // the nullifier.
2306        rng: &mut R,
2307    ) -> Self::Nullifier;
2308
2309    /// Adds both a spend and an output to the given [`CompactTx`], where the output will be
2310    /// discovered when scanning with the incoming viewing key corresponding to this FVK. Its
2311    /// outputs will also be discoverable when scanning with the provided OVK, if any.
2312    ///
2313    /// - If this is a Sapling full viewing key, the transaction will gain both a Spend
2314    ///   and an Output.
2315    /// - If this is an Orchard full viewing key, the transaction will gain an Action.
2316    ///
2317    /// `recipient_address_type` allows configuring what shielded address to produce from this FVK as the
2318    /// recipient of the newly created output.
2319    ///
2320    /// Returns the nullifier full the newly created note which will need to be revealed when that
2321    /// note is later spent.
2322    #[allow(clippy::too_many_arguments)]
2323    fn add_logical_action<P: consensus::Parameters, R: Rng + CryptoRng>(
2324        &self,
2325        ctx: &mut CompactTx,
2326        params: &P,
2327        height: BlockHeight,
2328        nf_to_reveal_in_spend: Self::Nullifier,
2329        sender_ovk: Option<&Self::OutgoingViewingKey>,
2330        recipient_address_type: AddressType,
2331        value: Zatoshis,
2332        initial_sapling_tree_size: u32,
2333        // we don't require an initial Orchard tree size because we don't need it to compute
2334        // the nullifier.
2335        rng: &mut R,
2336    ) -> Self::Nullifier;
2337}
2338
2339impl<A: TestFvk> TestFvk for &A {
2340    type Nullifier = A::Nullifier;
2341    type OutgoingViewingKey = A::OutgoingViewingKey;
2342
2343    fn to_ovk(&self, scope: zip32::Scope) -> Self::OutgoingViewingKey {
2344        (*self).to_ovk(scope)
2345    }
2346
2347    fn ovk_bytes(&self, scope: zip32::Scope) -> [u8; 32] {
2348        (*self).ovk_bytes(scope)
2349    }
2350
2351    fn add_spend<R: Rng + CryptoRng>(&self, ctx: &mut CompactTx, nf: Self::Nullifier, rng: &mut R) {
2352        (*self).add_spend(ctx, nf, rng)
2353    }
2354
2355    fn add_output<P: consensus::Parameters, R: Rng + CryptoRng>(
2356        &self,
2357        ctx: &mut CompactTx,
2358        params: &P,
2359        height: BlockHeight,
2360        sender_ovk: Option<&Self::OutgoingViewingKey>,
2361        recipient_address_type: AddressType,
2362        value: Zatoshis,
2363        initial_sapling_tree_size: u32,
2364        // we don't require an initial Orchard tree size because we don't need it to compute
2365        // the nullifier.
2366        rng: &mut R,
2367    ) -> Self::Nullifier {
2368        (*self).add_output(
2369            ctx,
2370            params,
2371            height,
2372            sender_ovk,
2373            recipient_address_type,
2374            value,
2375            initial_sapling_tree_size,
2376            rng,
2377        )
2378    }
2379
2380    fn add_logical_action<P: consensus::Parameters, R: Rng + CryptoRng>(
2381        &self,
2382        ctx: &mut CompactTx,
2383        params: &P,
2384        height: BlockHeight,
2385        nf_to_reveal_in_spend: Self::Nullifier,
2386        sender_ovk: Option<&Self::OutgoingViewingKey>,
2387        recipient_address_type: AddressType,
2388        value: Zatoshis,
2389        initial_sapling_tree_size: u32,
2390        // we don't require an initial Orchard tree size because we don't need it to compute
2391        // the nullifier.
2392        rng: &mut R,
2393    ) -> Self::Nullifier {
2394        (*self).add_logical_action(
2395            ctx,
2396            params,
2397            height,
2398            nf_to_reveal_in_spend,
2399            sender_ovk,
2400            recipient_address_type,
2401            value,
2402            initial_sapling_tree_size,
2403            rng,
2404        )
2405    }
2406}
2407
2408impl TestFvk for DiversifiableFullViewingKey {
2409    type Nullifier = ::sapling::Nullifier;
2410    type OutgoingViewingKey = ::sapling::keys::OutgoingViewingKey;
2411
2412    fn to_ovk(&self, scope: zip32::Scope) -> Self::OutgoingViewingKey {
2413        self.to_ovk(scope)
2414    }
2415
2416    fn ovk_bytes(&self, scope: zip32::Scope) -> [u8; 32] {
2417        self.to_ovk(scope).0
2418    }
2419
2420    fn add_spend<R: Rng + CryptoRng>(&self, ctx: &mut CompactTx, nf: Self::Nullifier, _: &mut R) {
2421        let cspend = CompactSaplingSpend { nf: nf.to_vec() };
2422        ctx.spends.push(cspend);
2423    }
2424
2425    fn add_output<P: consensus::Parameters, R: Rng + CryptoRng>(
2426        &self,
2427        ctx: &mut CompactTx,
2428        params: &P,
2429        height: BlockHeight,
2430        sender_ovk: Option<&Self::OutgoingViewingKey>,
2431        recipient_address_type: AddressType,
2432        value: Zatoshis,
2433        initial_sapling_tree_size: u32,
2434        rng: &mut R,
2435    ) -> Self::Nullifier {
2436        let recipient = match recipient_address_type {
2437            AddressType::DefaultExternal => self.default_address().1,
2438            AddressType::DiversifiedExternal(idx) => self.find_address(idx).unwrap().1,
2439            AddressType::Internal => self.change_address().1,
2440        };
2441
2442        let position = initial_sapling_tree_size + ctx.outputs.len() as u32;
2443
2444        let (cout, note) =
2445            compact_sapling_output(params, height, recipient, value, sender_ovk.copied(), rng);
2446        ctx.outputs.push(cout);
2447
2448        note.nf(self.fvk().vk.nk(), u64::from(position))
2449    }
2450
2451    #[allow(clippy::too_many_arguments)]
2452    fn add_logical_action<P: consensus::Parameters, R: Rng + CryptoRng>(
2453        &self,
2454        ctx: &mut CompactTx,
2455        params: &P,
2456        height: BlockHeight,
2457        nf_to_reveal_in_spend: Self::Nullifier,
2458        sender_ovk: Option<&Self::OutgoingViewingKey>,
2459        recipient_address_type: AddressType,
2460        value: Zatoshis,
2461        initial_sapling_tree_size: u32,
2462        rng: &mut R,
2463    ) -> Self::Nullifier {
2464        self.add_spend(ctx, nf_to_reveal_in_spend, rng);
2465        self.add_output(
2466            ctx,
2467            params,
2468            height,
2469            sender_ovk,
2470            recipient_address_type,
2471            value,
2472            initial_sapling_tree_size,
2473            rng,
2474        )
2475    }
2476}
2477
2478#[cfg(feature = "orchard")]
2479impl TestFvk for ::orchard::keys::FullViewingKey {
2480    type Nullifier = ::orchard::note::Nullifier;
2481    type OutgoingViewingKey = ::orchard::keys::OutgoingViewingKey;
2482
2483    fn to_ovk(&self, scope: zip32::Scope) -> Self::OutgoingViewingKey {
2484        self.to_ovk(scope)
2485    }
2486
2487    fn ovk_bytes(&self, scope: zip32::Scope) -> [u8; 32] {
2488        *self.to_ovk(scope).as_ref()
2489    }
2490
2491    fn add_spend<R: Rng + CryptoRng>(
2492        &self,
2493        ctx: &mut CompactTx,
2494        nullifier_to_reveal: Self::Nullifier,
2495        rng: &mut R,
2496    ) {
2497        // Generate a dummy recipient; the output will be zero-valued and be encrypted with a
2498        // random OVK.
2499        let recipient = loop {
2500            let mut bytes = [0; 32];
2501            rng.fill_bytes(&mut bytes);
2502            let sk = ::orchard::keys::SpendingKey::from_bytes(bytes);
2503            if sk.is_some().into() {
2504                break ::orchard::keys::FullViewingKey::from(&sk.unwrap())
2505                    .address_at(0u32, zip32::Scope::External);
2506            }
2507        };
2508
2509        let (cact, _) =
2510            compact_orchard_action(nullifier_to_reveal, recipient, Zatoshis::ZERO, None, rng);
2511        ctx.actions.push(cact);
2512    }
2513
2514    fn add_output<P: consensus::Parameters, R: Rng + CryptoRng>(
2515        &self,
2516        ctx: &mut CompactTx,
2517        _: &P,
2518        _: BlockHeight,
2519        sender_ovk: Option<&Self::OutgoingViewingKey>,
2520        recipient_address_type: AddressType,
2521        value: Zatoshis,
2522        _: u32, // the position is not required for computing the Orchard nullifier
2523        mut rng: &mut R,
2524    ) -> Self::Nullifier {
2525        // Generate a dummy nullifier for the spend
2526        let nullifier_to_reveal =
2527            ::orchard::note::Nullifier::from_bytes(&pallas::Base::random(&mut rng).to_repr())
2528                .unwrap();
2529
2530        let (j, scope) = match recipient_address_type {
2531            AddressType::DefaultExternal => (0u32.into(), zip32::Scope::External),
2532            AddressType::DiversifiedExternal(idx) => (idx, zip32::Scope::External),
2533            AddressType::Internal => (0u32.into(), zip32::Scope::Internal),
2534        };
2535
2536        let (cact, note) = compact_orchard_action(
2537            nullifier_to_reveal,
2538            self.address_at(j, scope),
2539            value,
2540            sender_ovk,
2541            rng,
2542        );
2543        ctx.actions.push(cact);
2544
2545        note.nullifier(self)
2546    }
2547
2548    fn add_logical_action<P: consensus::Parameters, R: Rng + CryptoRng>(
2549        &self,
2550        ctx: &mut CompactTx,
2551        _: &P,
2552        _: BlockHeight,
2553        nf_to_reveal_in_spend: Self::Nullifier,
2554        sender_ovk: Option<&Self::OutgoingViewingKey>,
2555        recipient_address_type: AddressType,
2556        value: Zatoshis,
2557        _: u32, // the position is not required for computing the Orchard nullifier
2558        rng: &mut R,
2559    ) -> Self::Nullifier {
2560        let (j, scope) = match recipient_address_type {
2561            AddressType::DefaultExternal => (0u32.into(), zip32::Scope::External),
2562            AddressType::DiversifiedExternal(idx) => (idx, zip32::Scope::External),
2563            AddressType::Internal => (0u32.into(), zip32::Scope::Internal),
2564        };
2565
2566        let (cact, note) = compact_orchard_action(
2567            nf_to_reveal_in_spend,
2568            self.address_at(j, scope),
2569            value,
2570            sender_ovk,
2571            rng,
2572        );
2573        ctx.actions.push(cact);
2574
2575        // Return the nullifier of the newly created output note
2576        note.nullifier(self)
2577    }
2578}
2579
2580/// A test-only viewing key that receives Ironwood (version 3) notes. It wraps the account's Orchard
2581/// full viewing key, but its outputs are version 3 notes placed in `tx.ironwood_actions` and
2582/// encrypted under the Ironwood note-encryption domain, so a wallet scanning them exercises the
2583/// Ironwood receive path.
2584#[cfg(feature = "orchard")]
2585#[derive(Clone)]
2586pub struct IronwoodFvk(pub ::orchard::keys::FullViewingKey);
2587
2588#[cfg(feature = "orchard")]
2589impl TestFvk for IronwoodFvk {
2590    type Nullifier = ::orchard::note::Nullifier;
2591    type OutgoingViewingKey = ::orchard::keys::OutgoingViewingKey;
2592
2593    fn to_ovk(&self, scope: zip32::Scope) -> Self::OutgoingViewingKey {
2594        self.0.to_ovk(scope)
2595    }
2596
2597    fn ovk_bytes(&self, scope: zip32::Scope) -> [u8; 32] {
2598        *self.0.to_ovk(scope).as_ref()
2599    }
2600
2601    fn add_spend<R: Rng + CryptoRng>(
2602        &self,
2603        ctx: &mut CompactTx,
2604        nullifier_to_reveal: Self::Nullifier,
2605        rng: &mut R,
2606    ) {
2607        // Generate a dummy recipient; the output will be zero-valued and be encrypted with a
2608        // random OVK.
2609        let recipient = loop {
2610            let mut bytes = [0; 32];
2611            rng.fill_bytes(&mut bytes);
2612            let sk = ::orchard::keys::SpendingKey::from_bytes(bytes);
2613            if sk.is_some().into() {
2614                break ::orchard::keys::FullViewingKey::from(&sk.unwrap())
2615                    .address_at(0u32, zip32::Scope::External);
2616            }
2617        };
2618
2619        let (cact, _) =
2620            compact_ironwood_action(nullifier_to_reveal, recipient, Zatoshis::ZERO, None, rng);
2621        ctx.ironwood_actions.push(cact);
2622    }
2623
2624    fn add_output<P: consensus::Parameters, R: Rng + CryptoRng>(
2625        &self,
2626        ctx: &mut CompactTx,
2627        _: &P,
2628        _: BlockHeight,
2629        sender_ovk: Option<&Self::OutgoingViewingKey>,
2630        recipient_address_type: AddressType,
2631        value: Zatoshis,
2632        _: u32, // the position is not required for computing the Orchard nullifier
2633        mut rng: &mut R,
2634    ) -> Self::Nullifier {
2635        // Generate a dummy nullifier for the spend
2636        let nullifier_to_reveal =
2637            ::orchard::note::Nullifier::from_bytes(&pallas::Base::random(&mut rng).to_repr())
2638                .unwrap();
2639
2640        let (j, scope) = match recipient_address_type {
2641            AddressType::DefaultExternal => (0u32.into(), zip32::Scope::External),
2642            AddressType::DiversifiedExternal(idx) => (idx, zip32::Scope::External),
2643            AddressType::Internal => (0u32.into(), zip32::Scope::Internal),
2644        };
2645
2646        let (cact, note) = compact_ironwood_action(
2647            nullifier_to_reveal,
2648            self.0.address_at(j, scope),
2649            value,
2650            sender_ovk,
2651            rng,
2652        );
2653        ctx.ironwood_actions.push(cact);
2654
2655        note.nullifier(&self.0)
2656    }
2657
2658    fn add_logical_action<P: consensus::Parameters, R: Rng + CryptoRng>(
2659        &self,
2660        ctx: &mut CompactTx,
2661        _: &P,
2662        _: BlockHeight,
2663        nf_to_reveal_in_spend: Self::Nullifier,
2664        sender_ovk: Option<&Self::OutgoingViewingKey>,
2665        recipient_address_type: AddressType,
2666        value: Zatoshis,
2667        _: u32, // the position is not required for computing the Orchard nullifier
2668        rng: &mut R,
2669    ) -> Self::Nullifier {
2670        let (j, scope) = match recipient_address_type {
2671            AddressType::DefaultExternal => (0u32.into(), zip32::Scope::External),
2672            AddressType::DiversifiedExternal(idx) => (idx, zip32::Scope::External),
2673            AddressType::Internal => (0u32.into(), zip32::Scope::Internal),
2674        };
2675
2676        let (cact, note) = compact_ironwood_action(
2677            nf_to_reveal_in_spend,
2678            self.0.address_at(j, scope),
2679            value,
2680            sender_ovk,
2681            rng,
2682        );
2683        ctx.ironwood_actions.push(cact);
2684
2685        // Return the nullifier of the newly created output note
2686        note.nullifier(&self.0)
2687    }
2688}
2689
2690/// Configures how a [`TestFvk`] receives a particular output.
2691///
2692/// Used with [`TestFvk::add_output`] and [`TestFvk::add_logical_action`].
2693#[derive(Clone, Copy, Debug)]
2694pub enum AddressType {
2695    /// The output will be sent to the default address of the full viewing key.
2696    DefaultExternal,
2697    /// The output will be sent to the specified diversified address of the full viewing
2698    /// key.
2699    #[allow(dead_code)]
2700    DiversifiedExternal(DiversifierIndex),
2701    /// The output will be sent to the internal receiver of the full viewing key.
2702    ///
2703    /// Such outputs are treated as "wallet-internal". A "recipient address" is **NEVER**
2704    /// exposed to users.
2705    Internal,
2706}
2707
2708/// Creates a `CompactSaplingOutput` at the given height paying the given recipient.
2709///
2710/// Returns the `CompactSaplingOutput` and the new note.
2711fn compact_sapling_output<P: consensus::Parameters, R: Rng + CryptoRng>(
2712    params: &P,
2713    height: BlockHeight,
2714    recipient: ::sapling::PaymentAddress,
2715    value: Zatoshis,
2716    sender_ovk: Option<::sapling::keys::OutgoingViewingKey>,
2717    rng: &mut R,
2718) -> (CompactSaplingOutput, ::sapling::Note) {
2719    let rseed = generate_random_rseed(zip212_enforcement(params, height), rng);
2720    let note = ::sapling::Note::from_parts(
2721        recipient,
2722        ::sapling::value::NoteValue::from_raw(value.into_u64()),
2723        rseed,
2724    );
2725    let encryptor = sapling_note_encryption(
2726        sender_ovk,
2727        note.clone(),
2728        MemoBytes::empty().into_bytes(),
2729        rng,
2730    );
2731    let cmu = note.cmu().to_bytes().to_vec();
2732    let ephemeral_key = SaplingDomain::epk_bytes(encryptor.epk()).0.to_vec();
2733    let enc_ciphertext = encryptor.encrypt_note_plaintext();
2734
2735    (
2736        CompactSaplingOutput {
2737            cmu,
2738            ephemeral_key,
2739            ciphertext: enc_ciphertext.0[..::sapling::note_encryption::COMPACT_NOTE_SIZE].to_vec(),
2740        },
2741        note,
2742    )
2743}
2744
2745/// Creates a `CompactOrchardAction` at the given height paying the given recipient.
2746///
2747/// Returns the `CompactOrchardAction` and the new note.
2748#[cfg(feature = "orchard")]
2749fn compact_orchard_action<R: Rng + CryptoRng>(
2750    nf_old: ::orchard::note::Nullifier,
2751    recipient: ::orchard::Address,
2752    value: Zatoshis,
2753    sender_ovk: Option<&::orchard::keys::OutgoingViewingKey>,
2754    rng: &mut R,
2755) -> (CompactOrchardAction, ::orchard::Note) {
2756    let (compact_action, note) = ::orchard::note_encryption::testing::fake_compact_action(
2757        rng,
2758        nf_old,
2759        recipient,
2760        ::orchard::value::NoteValue::from_raw(value.into_u64()),
2761        sender_ovk.cloned(),
2762    );
2763
2764    (
2765        CompactOrchardAction {
2766            nullifier: compact_action.nullifier().to_bytes().to_vec(),
2767            cmx: compact_action.cmx().to_bytes().to_vec(),
2768            ephemeral_key:
2769                ShieldedOutput::<::orchard::note_encryption::OrchardDomain>::ephemeral_key(
2770                    &compact_action,
2771                )
2772                .0
2773                .to_vec(),
2774            ciphertext:
2775                ShieldedOutput::<::orchard::note_encryption::OrchardDomain>::enc_ciphertext_compact(
2776                    &compact_action,
2777                )
2778                .0
2779                .to_vec(),
2780        },
2781        note,
2782    )
2783}
2784
2785/// Builds a version 3 (Ironwood) compact action paying `recipient` the given value, encrypted
2786/// under the Ironwood note-encryption domain, for placement in `tx.ironwood_actions`. Returns the
2787/// `CompactOrchardAction` and the note. This mirrors [`compact_orchard_action`], but constructs the
2788/// action directly because the orchard crate's `fake_compact_action` only produces version 2 notes.
2789#[cfg(feature = "orchard")]
2790fn compact_ironwood_action<R: Rng + CryptoRng>(
2791    nf_old: ::orchard::note::Nullifier,
2792    recipient: ::orchard::Address,
2793    value: Zatoshis,
2794    sender_ovk: Option<&::orchard::keys::OutgoingViewingKey>,
2795    rng: &mut R,
2796) -> (CompactOrchardAction, ::orchard::Note) {
2797    // Derive `rho` from the revealed nullifier exactly as the crate does internally
2798    // (`Rho::from_nf_old(nf) == Rho(nf.inner())`), so that the domain the scanner reconstructs via
2799    // `IronwoodDomain::for_compact_action(nf_old)` matches and decryption succeeds.
2800    let rho = Rho::from_bytes(&nf_old.to_bytes()).unwrap();
2801    let rseed = loop {
2802        let mut bytes = [0u8; 32];
2803        rng.fill_bytes(&mut bytes);
2804        if let Some(rseed) = Option::from(RandomSeed::from_bytes(bytes, &rho)) {
2805            break rseed;
2806        }
2807    };
2808    let note = OrchardNote::from_parts(
2809        recipient,
2810        ::orchard::value::NoteValue::from_raw(value.into_u64()),
2811        rho,
2812        rseed,
2813        NoteVersion::V3,
2814    )
2815    .unwrap();
2816    let encryptor = IronwoodNoteEncryption::new(sender_ovk.cloned(), note, [0u8; 512]);
2817    let cmx = ExtractedNoteCommitment::from(note.commitment());
2818    let ephemeral_key = IronwoodDomain::epk_bytes(encryptor.epk());
2819    let enc_ciphertext = encryptor.encrypt_note_plaintext();
2820
2821    (
2822        CompactOrchardAction {
2823            nullifier: nf_old.to_bytes().to_vec(),
2824            cmx: cmx.to_bytes().to_vec(),
2825            ephemeral_key: ephemeral_key.0.to_vec(),
2826            ciphertext: enc_ciphertext.0[..::orchard::note_encryption::COMPACT_NOTE_SIZE].to_vec(),
2827        },
2828        note,
2829    )
2830}
2831
2832/// Creates a fake `CompactTx` with a random transaction ID and no spends or outputs.
2833fn fake_compact_tx<R: Rng + CryptoRng>(rng: &mut R) -> CompactTx {
2834    let mut ctx = CompactTx::default();
2835    let mut txid = vec![0; 32];
2836    rng.fill_bytes(&mut txid);
2837    ctx.txid = txid;
2838
2839    ctx
2840}
2841
2842/// A fake output of a [`CompactTx`].
2843///
2844/// Used with the following block generators:
2845/// - [`TestState::generate_next_block_multi`]
2846/// - [`TestState::generate_block_at`]
2847#[derive(Clone)]
2848pub struct FakeCompactOutput<Fvk> {
2849    recipient_fvk: Fvk,
2850    recipient_address_type: AddressType,
2851    value: Zatoshis,
2852}
2853
2854impl<Fvk> FakeCompactOutput<Fvk> {
2855    /// Constructs a new fake output with the given properties.
2856    pub fn new(recipient_fvk: Fvk, recipient_address_type: AddressType, value: Zatoshis) -> Self {
2857        Self {
2858            recipient_fvk,
2859            recipient_address_type,
2860            value,
2861        }
2862    }
2863
2864    /// Constructs a new random fake external output to the given FVK with a value in the range
2865    /// 10000..1000000 ZAT.
2866    pub fn random<R: Rng>(rng: &mut R, recipient_fvk: Fvk) -> Self {
2867        Self {
2868            recipient_fvk,
2869            recipient_address_type: AddressType::DefaultExternal,
2870            value: Zatoshis::const_from_u64(rng.random_range(10000..1000000)),
2871        }
2872    }
2873}
2874
2875/// Create a fake CompactBlock at the given height, containing the specified fake compact outputs.
2876///
2877/// Returns the newly created compact block, along with the nullifier for each note created in that
2878/// block.
2879#[allow(clippy::too_many_arguments)]
2880fn fake_compact_block<P: consensus::Parameters, Fvk: TestFvk>(
2881    params: &P,
2882    height: BlockHeight,
2883    prev_hash: BlockHash,
2884    sender_ovk: Option<&Fvk::OutgoingViewingKey>,
2885    outputs: &[FakeCompactOutput<Fvk>],
2886    initial_sapling_tree_size: u32,
2887    initial_orchard_tree_size: u32,
2888    initial_ironwood_tree_size: u32,
2889    mut rng: impl CryptoRng,
2890) -> (CompactBlock, Vec<Fvk::Nullifier>) {
2891    // Create a fake CompactBlock containing the note
2892    let mut ctx = fake_compact_tx(&mut rng);
2893    let mut nfs = vec![];
2894    for output in outputs {
2895        let nf = output.recipient_fvk.add_output(
2896            &mut ctx,
2897            params,
2898            height,
2899            sender_ovk,
2900            output.recipient_address_type,
2901            output.value,
2902            initial_sapling_tree_size,
2903            &mut rng,
2904        );
2905        nfs.push(nf);
2906    }
2907
2908    let cb = fake_compact_block_from_compact_tx(
2909        ctx,
2910        height,
2911        prev_hash,
2912        initial_sapling_tree_size,
2913        initial_orchard_tree_size,
2914        initial_ironwood_tree_size,
2915        rng,
2916    );
2917    (cb, nfs)
2918}
2919
2920/// Create a fake CompactBlock at the given height containing only the given transaction.
2921// TODO: `tx` could be a slice and we could add multiple transactions here
2922#[allow(clippy::too_many_arguments)]
2923fn fake_compact_block_from_tx(
2924    height: BlockHeight,
2925    prev_hash: BlockHash,
2926    tx_index: usize,
2927    tx: &Transaction,
2928    initial_sapling_tree_size: u32,
2929    initial_orchard_tree_size: u32,
2930    initial_ironwood_tree_size: u32,
2931    rng: impl Rng,
2932) -> CompactBlock {
2933    // Create a fake CompactTx containing the transaction.
2934    let mut ctx = CompactTx {
2935        index: tx_index as u64,
2936        txid: tx.txid().as_ref().to_vec(),
2937        ..Default::default()
2938    };
2939
2940    if let Some(bundle) = tx.sapling_bundle() {
2941        for spend in bundle.shielded_spends() {
2942            ctx.spends.push(spend.into());
2943        }
2944        for output in bundle.shielded_outputs() {
2945            ctx.outputs.push(output.into());
2946        }
2947    }
2948
2949    #[cfg(feature = "orchard")]
2950    if let Some(bundle) = tx.orchard_bundle() {
2951        for action in bundle.actions() {
2952            ctx.actions.push(action.into());
2953        }
2954    }
2955
2956    #[cfg(feature = "orchard")]
2957    if let Some(bundle) = tx.ironwood_bundle() {
2958        for action in bundle.actions() {
2959            ctx.ironwood_actions.push(action.into());
2960        }
2961    }
2962
2963    fake_compact_block_from_compact_tx(
2964        ctx,
2965        height,
2966        prev_hash,
2967        initial_sapling_tree_size,
2968        initial_orchard_tree_size,
2969        initial_ironwood_tree_size,
2970        rng,
2971    )
2972}
2973
2974/// Create a fake CompactBlock at the given height, spending a single note from the
2975/// given address.
2976#[allow(clippy::too_many_arguments)]
2977fn fake_compact_block_spending<P: consensus::Parameters, Fvk: TestFvk>(
2978    params: &P,
2979    height: BlockHeight,
2980    prev_hash: BlockHash,
2981    (nf, in_value): (Fvk::Nullifier, Zatoshis),
2982    sender_fvk: &Fvk,
2983    to: Address,
2984    value: Zatoshis,
2985    initial_sapling_tree_size: u32,
2986    initial_orchard_tree_size: u32,
2987    initial_ironwood_tree_size: u32,
2988    mut rng: impl CryptoRng,
2989) -> CompactBlock {
2990    let mut ctx = fake_compact_tx(&mut rng);
2991
2992    // Create a fake spend and a fake Note for the change
2993    sender_fvk.add_logical_action(
2994        &mut ctx,
2995        params,
2996        height,
2997        nf,
2998        Some(&sender_fvk.to_ovk(zip32::Scope::Internal)),
2999        AddressType::Internal,
3000        (in_value - value).unwrap(),
3001        initial_sapling_tree_size,
3002        &mut rng,
3003    );
3004
3005    // Create a fake Note for the payment
3006    let ovk_bytes = sender_fvk.ovk_bytes(zip32::Scope::External);
3007    match to {
3008        Address::Sapling(recipient) => ctx.outputs.push(
3009            compact_sapling_output(
3010                params,
3011                height,
3012                *recipient,
3013                value,
3014                Some(::sapling::keys::OutgoingViewingKey(ovk_bytes)),
3015                &mut rng,
3016            )
3017            .0,
3018        ),
3019        Address::Transparent(_) | Address::Tex(_) => {
3020            panic!("transparent addresses not supported in compact blocks")
3021        }
3022        Address::Unified(ua) => {
3023            // This is annoying to implement, because the protocol-aware UA type has no
3024            // concept of ZIP 316 preference order.
3025            let mut done = false;
3026
3027            #[cfg(feature = "orchard")]
3028            if let Some(recipient) = ua.orchard() {
3029                // Generate a dummy nullifier
3030                let nullifier = ::orchard::note::Nullifier::from_bytes(
3031                    &pallas::Base::random(&mut rng).to_repr(),
3032                )
3033                .unwrap();
3034
3035                ctx.actions.push(
3036                    compact_orchard_action(
3037                        nullifier,
3038                        *recipient,
3039                        value,
3040                        Some(&::orchard::keys::OutgoingViewingKey::from(ovk_bytes)),
3041                        &mut rng,
3042                    )
3043                    .0,
3044                );
3045                done = true;
3046            }
3047
3048            if !done && let Some(recipient) = ua.sapling() {
3049                ctx.outputs.push(
3050                    compact_sapling_output(
3051                        params,
3052                        height,
3053                        *recipient,
3054                        value,
3055                        Some(::sapling::keys::OutgoingViewingKey(ovk_bytes)),
3056                        &mut rng,
3057                    )
3058                    .0,
3059                );
3060                done = true;
3061            }
3062            if !done {
3063                panic!("No supported shielded receiver to send funds to");
3064            }
3065        }
3066    }
3067
3068    fake_compact_block_from_compact_tx(
3069        ctx,
3070        height,
3071        prev_hash,
3072        initial_sapling_tree_size,
3073        initial_orchard_tree_size,
3074        initial_ironwood_tree_size,
3075        rng,
3076    )
3077}
3078
3079fn fake_compact_block_from_compact_tx(
3080    ctx: CompactTx,
3081    height: BlockHeight,
3082    prev_hash: BlockHash,
3083    initial_sapling_tree_size: u32,
3084    initial_orchard_tree_size: u32,
3085    initial_ironwood_tree_size: u32,
3086    mut rng: impl Rng,
3087) -> CompactBlock {
3088    let mut cb = CompactBlock {
3089        hash: {
3090            let mut hash = vec![0; 32];
3091            rng.fill_bytes(&mut hash);
3092            hash
3093        },
3094        height: height.into(),
3095        ..Default::default()
3096    };
3097    cb.prev_hash.extend_from_slice(&prev_hash.0);
3098    cb.vtx.push(ctx);
3099    cb.chain_metadata = Some(compact_formats::ChainMetadata {
3100        sapling_commitment_tree_size: initial_sapling_tree_size
3101            + cb.vtx.iter().map(|tx| tx.outputs.len() as u32).sum::<u32>(),
3102        orchard_commitment_tree_size: initial_orchard_tree_size
3103            + cb.vtx.iter().map(|tx| tx.actions.len() as u32).sum::<u32>(),
3104        ironwood_commitment_tree_size: initial_ironwood_tree_size
3105            + cb.vtx
3106                .iter()
3107                .map(|tx| tx.ironwood_actions.len() as u32)
3108                .sum::<u32>(),
3109    });
3110    cb
3111}
3112
3113// A trait that must be implemented for all test caches, for returning metadata about inserted
3114// values.
3115pub trait CacheInsertionResult {
3116    fn txids(&self) -> &[TxId];
3117}
3118
3119/// Trait used by tests that require a block cache.
3120pub trait TestCache {
3121    type BsError: core::fmt::Debug;
3122    type BlockSource: BlockSource<Error = Self::BsError>;
3123    type InsertResult: CacheInsertionResult;
3124
3125    /// Exposes the block cache as a [`BlockSource`].
3126    fn block_source(&self) -> &Self::BlockSource;
3127
3128    /// Inserts a CompactBlock into the cache DB.
3129    fn insert(&mut self, cb: &CompactBlock) -> Self::InsertResult;
3130
3131    /// Deletes block data from the cache, retaining blocks at heights less than or equal to the
3132    /// specified height.
3133    fn truncate_to_height(&mut self, height: BlockHeight);
3134}
3135
3136/// A convenience type for the note commitments contained within a [`CompactBlock`].
3137///
3138/// Indended for use as (part of) the [`TestCache::InsertResult`] associated type.
3139pub struct NoteCommitments {
3140    sapling: Vec<::sapling::Node>,
3141    #[cfg(feature = "orchard")]
3142    orchard: Vec<MerkleHashOrchard>,
3143}
3144
3145impl NoteCommitments {
3146    /// Extracts the note commitments from the given compact block.
3147    pub fn from_compact_block(cb: &CompactBlock) -> Self {
3148        NoteCommitments {
3149            sapling: cb
3150                .vtx
3151                .iter()
3152                .flat_map(|tx| {
3153                    tx.outputs
3154                        .iter()
3155                        .map(|out| ::sapling::Node::from_cmu(&out.cmu().unwrap()))
3156                })
3157                .collect(),
3158            #[cfg(feature = "orchard")]
3159            orchard: cb
3160                .vtx
3161                .iter()
3162                .flat_map(|tx| {
3163                    tx.actions
3164                        .iter()
3165                        .map(|act| MerkleHashOrchard::from_cmx(&act.cmx().unwrap()))
3166                })
3167                .collect(),
3168        }
3169    }
3170
3171    /// Returns the Sapling note commitments.
3172    #[allow(dead_code)]
3173    pub fn sapling(&self) -> &[::sapling::Node] {
3174        self.sapling.as_ref()
3175    }
3176
3177    /// Returns the Orchard note commitments.
3178    #[cfg(feature = "orchard")]
3179    pub fn orchard(&self) -> &[MerkleHashOrchard] {
3180        self.orchard.as_ref()
3181    }
3182}
3183
3184/// A mock wallet data source that implements the bare minimum necessary to function.
3185pub struct MockWalletDb {
3186    pub network: Network,
3187    pub sapling_tree: ShardTree<
3188        MemoryShardStore<::sapling::Node, BlockHeight>,
3189        { SAPLING_SHARD_HEIGHT * 2 },
3190        SAPLING_SHARD_HEIGHT,
3191    >,
3192    #[cfg(feature = "orchard")]
3193    pub orchard_tree: ShardTree<
3194        MemoryShardStore<::orchard::tree::MerkleHashOrchard, BlockHeight>,
3195        { ORCHARD_SHARD_HEIGHT * 2 },
3196        ORCHARD_SHARD_HEIGHT,
3197    >,
3198    account_ids: Vec<u32>,
3199    addresses_by_account: HashMap<u32, Vec<AddressInfo>>,
3200    ufvks_by_account: HashMap<u32, UnifiedFullViewingKey>,
3201}
3202
3203impl MockWalletDb {
3204    /// Constructs a new mock wallet data source.
3205    pub fn new(network: Network) -> Self {
3206        Self {
3207            network,
3208            sapling_tree: ShardTree::new(MemoryShardStore::empty(), 100),
3209            #[cfg(feature = "orchard")]
3210            orchard_tree: ShardTree::new(MemoryShardStore::empty(), 100),
3211            account_ids: vec![],
3212            addresses_by_account: HashMap::new(),
3213            ufvks_by_account: HashMap::new(),
3214        }
3215    }
3216
3217    #[cfg(test)]
3218    pub(crate) fn from_account_addresses(
3219        network: Network,
3220        entries: impl IntoIterator<Item = (u32, Vec<AddressInfo>)>,
3221    ) -> Self {
3222        let mut wallet = Self::new(network);
3223        for (account_id, addresses) in entries {
3224            wallet.account_ids.push(account_id);
3225            wallet.addresses_by_account.insert(account_id, addresses);
3226        }
3227        wallet.account_ids.sort_unstable();
3228        wallet
3229    }
3230
3231    #[cfg(test)]
3232    pub(crate) fn from_account_ufvks(
3233        network: Network,
3234        entries: impl IntoIterator<Item = (u32, UnifiedFullViewingKey)>,
3235    ) -> Self {
3236        let mut wallet = Self::new(network);
3237        for (account_id, ufvk) in entries {
3238            wallet.account_ids.push(account_id);
3239            wallet.ufvks_by_account.insert(account_id, ufvk);
3240        }
3241        wallet.account_ids.sort_unstable();
3242        wallet
3243    }
3244}
3245
3246impl InputSource for MockWalletDb {
3247    type Error = ();
3248    type NoteRef = u32;
3249    type AccountId = u32;
3250
3251    fn anchor_computable(
3252        &self,
3253        protocol: ShieldedPool,
3254        height: BlockHeight,
3255    ) -> Result<bool, Self::Error> {
3256        match protocol {
3257            ShieldedPool::Sapling => Ok(self
3258                .sapling_tree
3259                .store()
3260                .get_checkpoint(&height)
3261                .map_err(|_| ())?
3262                .is_some()),
3263            #[cfg(feature = "orchard")]
3264            ShieldedPool::Orchard => Ok(self
3265                .orchard_tree
3266                .store()
3267                .get_checkpoint(&height)
3268                .map_err(|_| ())?
3269                .is_some()),
3270            // The mock maintains no Ironwood tree (and no Orchard tree without the `orchard`
3271            // feature), so no anchor is computable there.
3272            _ => Ok(false),
3273        }
3274    }
3275
3276    fn get_spendable_note(
3277        &self,
3278        _txid: &TxId,
3279        _protocol: ShieldedPool,
3280        _index: u32,
3281        _target_height: TargetHeight,
3282        _lock_filter: LockFilter<'_>,
3283    ) -> Result<Option<ReceivedNote<Self::NoteRef, Note>>, Self::Error> {
3284        Ok(None)
3285    }
3286
3287    fn select_spendable_notes(
3288        &self,
3289        _account: Self::AccountId,
3290        _target_value: TargetValue,
3291        _sources: &[ShieldedPool],
3292        _target_height: TargetHeight,
3293        _confirmations_policy: ConfirmationsPolicy,
3294        _exclude: &[Self::NoteRef],
3295        _lock_filter: LockFilter<'_>,
3296    ) -> Result<ReceivedNotes<Self::NoteRef>, Self::Error> {
3297        Ok(ReceivedNotes::empty())
3298    }
3299
3300    fn select_unspent_notes(
3301        &self,
3302        _account: Self::AccountId,
3303        _sources: &[ShieldedPool],
3304        _target_height: TargetHeight,
3305        _exclude: &[Self::NoteRef],
3306        _lock_filter: LockFilter<'_>,
3307    ) -> Result<ReceivedNotes<Self::NoteRef>, Self::Error> {
3308        Err(())
3309    }
3310
3311    fn get_change_receivers(&self, account: Self::AccountId) -> Result<ChangeReceivers, ()> {
3312        self.ufvks_by_account
3313            .get(&account)
3314            .map(|ufvk| ChangeReceivers::from_uivk(&ufvk.to_unified_incoming_viewing_key()))
3315            .ok_or(())
3316    }
3317
3318    fn get_account_metadata(
3319        &self,
3320        _account: Self::AccountId,
3321        _selector: &NoteFilter,
3322        _target_height: TargetHeight,
3323        _exclude: &[Self::NoteRef],
3324        _lock_filter: LockFilter<'_>,
3325    ) -> Result<AccountMeta, Self::Error> {
3326        Err(())
3327    }
3328}
3329
3330impl WalletRead for MockWalletDb {
3331    type Error = ();
3332    type AccountId = u32;
3333    type Account = (Self::AccountId, UnifiedFullViewingKey, BlockHeight);
3334
3335    fn get_account_ids(&self) -> Result<Vec<Self::AccountId>, Self::Error> {
3336        Ok(self.account_ids.clone())
3337    }
3338
3339    fn get_account(
3340        &self,
3341        account_id: Self::AccountId,
3342    ) -> Result<Option<Self::Account>, Self::Error> {
3343        Ok(self
3344            .ufvks_by_account
3345            .get(&account_id)
3346            .cloned()
3347            .map(|ufvk| (account_id, ufvk, BlockHeight::from(1))))
3348    }
3349
3350    fn get_derived_account(
3351        &self,
3352        _derivation: &Zip32Derivation,
3353    ) -> Result<Option<Self::Account>, Self::Error> {
3354        Ok(None)
3355    }
3356
3357    fn validate_seed(
3358        &self,
3359        _account_id: Self::AccountId,
3360        _seed: &SecretVec<u8>,
3361    ) -> Result<bool, Self::Error> {
3362        Ok(false)
3363    }
3364
3365    fn seed_relevance_to_derived_accounts(
3366        &self,
3367        _seed: &SecretVec<u8>,
3368    ) -> Result<SeedRelevance<Self::AccountId>, Self::Error> {
3369        Ok(SeedRelevance::NoAccounts)
3370    }
3371
3372    fn get_account_for_ufvk(
3373        &self,
3374        _ufvk: &UnifiedFullViewingKey,
3375    ) -> Result<Option<Self::Account>, Self::Error> {
3376        Ok(None)
3377    }
3378
3379    fn list_addresses(&self, account: Self::AccountId) -> Result<Vec<AddressInfo>, Self::Error> {
3380        Ok(self
3381            .addresses_by_account
3382            .get(&account)
3383            .cloned()
3384            .unwrap_or_default())
3385    }
3386
3387    fn find_account_for_address<P: consensus::Parameters>(
3388        &self,
3389        params: &P,
3390        address: &zcash_keys::address::Address,
3391    ) -> Result<Option<Self::AccountId>, super::error::FindAccountForAddressError<Self::Error>>
3392    {
3393        super::defaults::find_account_for_address(self, params, address)
3394    }
3395
3396    fn get_last_generated_address_matching(
3397        &self,
3398        _account: Self::AccountId,
3399        _request: UnifiedAddressRequest,
3400    ) -> Result<Option<UnifiedAddress>, Self::Error> {
3401        Ok(None)
3402    }
3403
3404    fn get_account_birthday(&self, _account: Self::AccountId) -> Result<BlockHeight, Self::Error> {
3405        Err(())
3406    }
3407
3408    fn get_wallet_birthday(&self) -> Result<Option<BlockHeight>, Self::Error> {
3409        Ok(None)
3410    }
3411
3412    fn get_wallet_recover_until(&self) -> Result<Option<BlockHeight>, Self::Error> {
3413        Ok(None)
3414    }
3415
3416    fn get_wallet_summary(
3417        &self,
3418        _confirmations_policy: ConfirmationsPolicy,
3419    ) -> Result<Option<WalletSummary<Self::AccountId>>, Self::Error> {
3420        Ok(None)
3421    }
3422
3423    fn chain_height(&self) -> Result<Option<BlockHeight>, Self::Error> {
3424        Ok(None)
3425    }
3426
3427    fn get_block_hash(&self, _block_height: BlockHeight) -> Result<Option<BlockHash>, Self::Error> {
3428        Ok(None)
3429    }
3430
3431    fn block_metadata(&self, _height: BlockHeight) -> Result<Option<BlockMetadata>, Self::Error> {
3432        Ok(None)
3433    }
3434
3435    fn block_fully_scanned(&self) -> Result<Option<BlockMetadata>, Self::Error> {
3436        Ok(None)
3437    }
3438
3439    fn get_max_height_hash(&self) -> Result<Option<(BlockHeight, BlockHash)>, Self::Error> {
3440        Ok(None)
3441    }
3442
3443    fn block_max_scanned(&self) -> Result<Option<BlockMetadata>, Self::Error> {
3444        Ok(None)
3445    }
3446
3447    fn suggest_scan_ranges(&self) -> Result<Vec<ScanRange>, Self::Error> {
3448        Ok(vec![])
3449    }
3450
3451    fn get_target_and_anchor_heights(
3452        &self,
3453        _min_confirmations: NonZeroU32,
3454    ) -> Result<Option<(TargetHeight, BlockHeight)>, Self::Error> {
3455        Ok(None)
3456    }
3457
3458    fn get_tx_height(&self, _txid: TxId) -> Result<Option<BlockHeight>, Self::Error> {
3459        Ok(None)
3460    }
3461
3462    fn get_unified_full_viewing_keys(
3463        &self,
3464    ) -> Result<HashMap<Self::AccountId, UnifiedFullViewingKey>, Self::Error> {
3465        Ok(HashMap::new())
3466    }
3467
3468    fn get_memo(&self, _id_note: NoteId) -> Result<Option<Memo>, Self::Error> {
3469        Ok(None)
3470    }
3471
3472    fn get_transaction(&self, _txid: TxId) -> Result<Option<Transaction>, Self::Error> {
3473        Ok(None)
3474    }
3475
3476    fn get_sapling_nullifiers(
3477        &self,
3478        _query: NullifierQuery,
3479    ) -> Result<Vec<(Self::AccountId, ::sapling::Nullifier)>, Self::Error> {
3480        Ok(Vec::new())
3481    }
3482
3483    #[cfg(feature = "orchard")]
3484    fn get_orchard_nullifiers(
3485        &self,
3486        _query: NullifierQuery,
3487    ) -> Result<Vec<(Self::AccountId, ::orchard::note::Nullifier)>, Self::Error> {
3488        Ok(Vec::new())
3489    }
3490
3491    #[cfg(feature = "orchard")]
3492    fn get_ironwood_nullifiers(
3493        &self,
3494        _query: NullifierQuery,
3495    ) -> Result<Vec<(Self::AccountId, ::orchard::note::Nullifier)>, Self::Error> {
3496        Ok(Vec::new())
3497    }
3498
3499    #[cfg(feature = "transparent-inputs")]
3500    fn get_unspent_transparent_outpoints(
3501        &self,
3502    ) -> Result<HashMap<OutPoint, Self::AccountId>, Self::Error> {
3503        Ok(HashMap::new())
3504    }
3505
3506    #[cfg(feature = "transparent-inputs")]
3507    fn get_transparent_receiver_accounts(
3508        &self,
3509    ) -> Result<
3510        HashMap<TransparentAddress, (Self::AccountId, Option<TransparentKeyScope>)>,
3511        Self::Error,
3512    > {
3513        Ok(HashMap::new())
3514    }
3515
3516    #[cfg(feature = "transparent-inputs")]
3517    fn get_transparent_receivers(
3518        &self,
3519        _account: Self::AccountId,
3520        _include_change: bool,
3521        _include_standalone: bool,
3522    ) -> Result<HashMap<TransparentAddress, TransparentAddressMetadata>, Self::Error> {
3523        Ok(HashMap::new())
3524    }
3525
3526    #[cfg(feature = "transparent-inputs")]
3527    fn get_transparent_balances(
3528        &self,
3529        _account: Self::AccountId,
3530        _target_height: TargetHeight,
3531        _confirmations_policy: ConfirmationsPolicy,
3532    ) -> Result<TransparentBalances, Self::Error> {
3533        Ok(HashMap::new())
3534    }
3535
3536    #[cfg(feature = "transparent-inputs")]
3537    fn get_transparent_address_metadata(
3538        &self,
3539        _account: Self::AccountId,
3540        _address: &TransparentAddress,
3541    ) -> Result<Option<TransparentAddressMetadata>, Self::Error> {
3542        Ok(None)
3543    }
3544
3545    #[cfg(feature = "transparent-inputs")]
3546    fn utxo_query_height(&self, _account: Self::AccountId) -> Result<BlockHeight, Self::Error> {
3547        Ok(BlockHeight::from(0u32))
3548    }
3549
3550    fn transaction_data_requests(&self) -> Result<Vec<TransactionDataRequest>, Self::Error> {
3551        Ok(vec![])
3552    }
3553
3554    fn get_received_outputs(
3555        &self,
3556        _txid: TxId,
3557        _target_height: TargetHeight,
3558        _confirmations_policy: ConfirmationsPolicy,
3559    ) -> Result<Vec<ReceivedTransactionOutput>, Self::Error> {
3560        Ok(vec![])
3561    }
3562}
3563
3564impl OutputLockStore for MockWalletDb {
3565    type Error = ();
3566    type AccountId = u32;
3567
3568    fn lock_outputs(
3569        &mut self,
3570        _outputs: &[OutputRef],
3571        _owner: LockOwner,
3572        _lock_expiry_height: BlockHeight,
3573    ) -> Result<usize, LockError<Self::Error>> {
3574        Ok(0)
3575    }
3576
3577    fn unlock_output(
3578        &mut self,
3579        _output: &OutputRef,
3580        _owner: LockOwner,
3581    ) -> Result<bool, Self::Error> {
3582        Ok(false)
3583    }
3584
3585    fn clear_locked_outputs(&mut self, _account: Self::AccountId) -> Result<usize, Self::Error> {
3586        Ok(0)
3587    }
3588
3589    fn get_locked_outputs(&self, _account: Self::AccountId) -> Result<Vec<OutputRef>, Self::Error> {
3590        Ok(Vec::new())
3591    }
3592}
3593
3594impl WalletWrite for MockWalletDb {
3595    type UtxoRef = u32;
3596
3597    fn create_account(
3598        &mut self,
3599        _account_name: &str,
3600        seed: &SecretVec<u8>,
3601        _birthday: &AccountBirthday,
3602        _key_source: Option<&str>,
3603    ) -> Result<(<Self as WalletRead>::AccountId, UnifiedSpendingKey), <Self as WalletRead>::Error>
3604    {
3605        let account = zip32::AccountId::ZERO;
3606        UnifiedSpendingKey::from_seed(&self.network, seed.expose_secret(), account)
3607            .map(|k| (u32::from(account), k))
3608            .map_err(|_| ())
3609    }
3610
3611    fn import_account_hd(
3612        &mut self,
3613        _account_name: &str,
3614        _seed: &SecretVec<u8>,
3615        _account_index: zip32::AccountId,
3616        _birthday: &AccountBirthday,
3617        _key_source: Option<&str>,
3618    ) -> Result<(Self::Account, UnifiedSpendingKey), <Self as WalletRead>::Error> {
3619        todo!()
3620    }
3621
3622    fn import_account_ufvk(
3623        &mut self,
3624        _account_name: &str,
3625        _unified_key: &UnifiedFullViewingKey,
3626        _birthday: &AccountBirthday,
3627        _purpose: AccountPurpose,
3628        _key_source: Option<&str>,
3629    ) -> Result<Self::Account, <Self as WalletRead>::Error> {
3630        todo!()
3631    }
3632
3633    fn delete_account(
3634        &mut self,
3635        _account: <Self as WalletRead>::AccountId,
3636    ) -> Result<(), <Self as WalletRead>::Error> {
3637        todo!()
3638    }
3639
3640    fn set_account_name(
3641        &mut self,
3642        _account: <Self as WalletRead>::AccountId,
3643        _name: &str,
3644    ) -> Result<(), <Self as WalletRead>::Error> {
3645        todo!()
3646    }
3647
3648    #[cfg(feature = "transparent-key-import")]
3649    fn import_standalone_transparent_pubkey(
3650        &mut self,
3651        _account: <Self as WalletRead>::AccountId,
3652        _address: secp256k1::PublicKey,
3653    ) -> Result<(), <Self as WalletRead>::Error> {
3654        todo!()
3655    }
3656
3657    #[cfg(feature = "transparent-key-import")]
3658    fn import_standalone_transparent_script(
3659        &mut self,
3660        _account: <Self as WalletRead>::AccountId,
3661        _script: script::Redeem,
3662    ) -> Result<(), <Self as WalletRead>::Error> {
3663        todo!()
3664    }
3665
3666    fn get_next_available_address(
3667        &mut self,
3668        _account: <Self as WalletRead>::AccountId,
3669        _request: UnifiedAddressRequest,
3670    ) -> Result<Option<(UnifiedAddress, DiversifierIndex)>, <Self as WalletRead>::Error> {
3671        Ok(None)
3672    }
3673
3674    fn get_address_for_index(
3675        &mut self,
3676        _account: <Self as WalletRead>::AccountId,
3677        _diversifier_index: DiversifierIndex,
3678        _request: UnifiedAddressRequest,
3679    ) -> Result<Option<UnifiedAddress>, <Self as WalletRead>::Error> {
3680        Ok(None)
3681    }
3682
3683    #[allow(clippy::type_complexity)]
3684    fn put_blocks(
3685        &mut self,
3686        _from_state: &ChainState,
3687        _blocks: Vec<ScannedBlock<<Self as WalletRead>::AccountId>>,
3688    ) -> Result<(), PutBlocksError<<Self as WalletRead>::Error>> {
3689        Ok(())
3690    }
3691
3692    fn update_chain_tip(
3693        &mut self,
3694        _tip_height: BlockHeight,
3695    ) -> Result<(), <Self as WalletRead>::Error> {
3696        Ok(())
3697    }
3698
3699    fn prune_scan_queue_below(
3700        &mut self,
3701        _height: BlockHeight,
3702        _retain_with_priority: Option<ScanPriority>,
3703    ) -> Result<u64, <Self as WalletRead>::Error> {
3704        Ok(0)
3705    }
3706
3707    fn queue_rescan(
3708        &mut self,
3709        _range: Range<BlockHeight>,
3710    ) -> Result<(), <Self as WalletRead>::Error> {
3711        Ok(())
3712    }
3713
3714    fn store_decrypted_tx(
3715        &mut self,
3716        _received_tx: DecryptedTransaction<Transaction, <Self as WalletRead>::AccountId>,
3717    ) -> Result<(), <Self as WalletRead>::Error> {
3718        Ok(())
3719    }
3720
3721    fn set_tx_trust(
3722        &mut self,
3723        _txid: TxId,
3724        _trusted: bool,
3725    ) -> Result<(), <Self as WalletRead>::Error> {
3726        Ok(())
3727    }
3728
3729    fn store_transactions_to_be_sent(
3730        &mut self,
3731        _transactions: &[SentTransaction<<Self as WalletRead>::AccountId>],
3732    ) -> Result<(), <Self as WalletRead>::Error> {
3733        Ok(())
3734    }
3735
3736    fn truncate_to_height(
3737        &mut self,
3738        _block_height: BlockHeight,
3739    ) -> Result<BlockHeight, <Self as WalletRead>::Error> {
3740        Err(())
3741    }
3742
3743    fn truncate_to_chain_state(
3744        &mut self,
3745        _chain_state: ChainState,
3746    ) -> Result<(), <Self as WalletRead>::Error> {
3747        Err(())
3748    }
3749
3750    fn rewind_to_chain_state(
3751        &mut self,
3752        _chain_state: ChainState,
3753        _reset_account_birthdays: HashSet<<Self as WalletRead>::AccountId>,
3754    ) -> Result<(), RewindError<<Self as WalletRead>::AccountId, <Self as WalletRead>::Error>> {
3755        Err(RewindError::DataSource(()))
3756    }
3757
3758    /// Adds a transparent UTXO received by the wallet to the data store.
3759    fn put_received_transparent_utxo(
3760        &mut self,
3761        _output: &WalletTransparentOutput<<Self as WalletRead>::AccountId>,
3762    ) -> Result<Self::UtxoRef, <Self as WalletRead>::Error> {
3763        Ok(0)
3764    }
3765
3766    #[cfg(feature = "transparent-inputs")]
3767    fn reserve_next_n_ephemeral_addresses(
3768        &mut self,
3769        _account_id: <Self as WalletRead>::AccountId,
3770        _n: usize,
3771    ) -> Result<Vec<(TransparentAddress, TransparentAddressMetadata)>, <Self as WalletRead>::Error>
3772    {
3773        Err(())
3774    }
3775
3776    #[cfg(feature = "transparent-inputs")]
3777    fn reserve_next_n_internal_addresses(
3778        &mut self,
3779        _account_id: <Self as WalletRead>::AccountId,
3780        _n: usize,
3781    ) -> Result<Vec<(TransparentAddress, TransparentAddressMetadata)>, <Self as WalletRead>::Error>
3782    {
3783        Err(())
3784    }
3785
3786    fn set_transaction_status(
3787        &mut self,
3788        _txid: TxId,
3789        _status: TransactionStatus,
3790    ) -> Result<(), <Self as WalletRead>::Error> {
3791        Ok(())
3792    }
3793
3794    #[cfg(feature = "transparent-inputs")]
3795    fn notify_address_checked(
3796        &mut self,
3797        _request: TransactionsInvolvingAddress,
3798        _as_of_height: BlockHeight,
3799    ) -> Result<(), <Self as WalletRead>::Error> {
3800        Ok(())
3801    }
3802}
3803
3804impl WalletCommitmentTrees for MockWalletDb {
3805    type Error = Infallible;
3806    type SaplingShardStore<'a> = MemoryShardStore<::sapling::Node, BlockHeight>;
3807
3808    fn with_sapling_tree_mut<F, A, E>(&mut self, mut callback: F) -> Result<A, E>
3809    where
3810        for<'a> F: FnMut(
3811            &'a mut ShardTree<
3812                Self::SaplingShardStore<'a>,
3813                { ::sapling::NOTE_COMMITMENT_TREE_DEPTH },
3814                SAPLING_SHARD_HEIGHT,
3815            >,
3816        ) -> Result<A, E>,
3817        E: From<ShardTreeError<Infallible>>,
3818    {
3819        callback(&mut self.sapling_tree)
3820    }
3821
3822    fn put_sapling_subtree_roots(
3823        &mut self,
3824        start_index: u64,
3825        roots: &[CommitmentTreeRoot<::sapling::Node>],
3826    ) -> Result<(), ShardTreeError<Self::Error>> {
3827        self.with_sapling_tree_mut(|t| {
3828            for (root, i) in roots.iter().zip(0u64..) {
3829                let root_addr = incrementalmerkletree::Address::from_parts(
3830                    SAPLING_SHARD_HEIGHT.into(),
3831                    start_index + i,
3832                );
3833                t.insert(root_addr, *root.root_hash())?;
3834            }
3835            Ok::<_, ShardTreeError<Self::Error>>(())
3836        })?;
3837
3838        Ok(())
3839    }
3840
3841    fn get_sapling_subtree_root(
3842        &mut self,
3843        index: u64,
3844    ) -> Result<Option<::sapling::Node>, ShardTreeError<Self::Error>> {
3845        self.with_sapling_tree_mut(|t| {
3846            let addr =
3847                incrementalmerkletree::Address::from_parts(SAPLING_SHARD_HEIGHT.into(), index);
3848            Ok::<_, ShardTreeError<Self::Error>>(
3849                t.store()
3850                    .get_shard(addr)
3851                    .map_err(ShardTreeError::Storage)?
3852                    .and_then(|shard| match shard.root() {
3853                        tree if tree.is_leaf() => tree.leaf_value().copied(),
3854                        tree => tree.annotation().and_then(|ann| ann.as_deref().copied()),
3855                    }),
3856            )
3857        })
3858    }
3859
3860    #[cfg(feature = "orchard")]
3861    type OrchardShardStore<'a> = MemoryShardStore<::orchard::tree::MerkleHashOrchard, BlockHeight>;
3862
3863    #[cfg(feature = "orchard")]
3864    fn with_orchard_tree_mut<F, A, E>(&mut self, mut callback: F) -> Result<A, E>
3865    where
3866        for<'a> F: FnMut(
3867            &'a mut ShardTree<
3868                Self::OrchardShardStore<'a>,
3869                { ORCHARD_SHARD_HEIGHT * 2 },
3870                ORCHARD_SHARD_HEIGHT,
3871            >,
3872        ) -> Result<A, E>,
3873        E: From<ShardTreeError<Self::Error>>,
3874    {
3875        callback(&mut self.orchard_tree)
3876    }
3877
3878    /// Adds a sequence of note commitment tree subtree roots to the data store.
3879    #[cfg(feature = "orchard")]
3880    fn put_orchard_subtree_roots(
3881        &mut self,
3882        start_index: u64,
3883        roots: &[CommitmentTreeRoot<::orchard::tree::MerkleHashOrchard>],
3884    ) -> Result<(), ShardTreeError<Self::Error>> {
3885        self.with_orchard_tree_mut(|t| {
3886            for (root, i) in roots.iter().zip(0u64..) {
3887                let root_addr = incrementalmerkletree::Address::from_parts(
3888                    ORCHARD_SHARD_HEIGHT.into(),
3889                    start_index + i,
3890                );
3891                t.insert(root_addr, *root.root_hash())?;
3892            }
3893            Ok::<_, ShardTreeError<Self::Error>>(())
3894        })?;
3895
3896        Ok(())
3897    }
3898
3899    #[cfg(feature = "orchard")]
3900    fn get_orchard_subtree_root(
3901        &mut self,
3902        index: u64,
3903    ) -> Result<Option<::orchard::tree::MerkleHashOrchard>, ShardTreeError<Self::Error>> {
3904        self.with_orchard_tree_mut(|t| {
3905            let addr =
3906                incrementalmerkletree::Address::from_parts(ORCHARD_SHARD_HEIGHT.into(), index);
3907            Ok::<_, ShardTreeError<Self::Error>>(
3908                t.store()
3909                    .get_shard(addr)
3910                    .map_err(ShardTreeError::Storage)?
3911                    .and_then(|shard| match shard.root() {
3912                        tree if tree.is_leaf() => tree.leaf_value().copied(),
3913                        tree => tree.annotation().and_then(|ann| ann.as_deref().copied()),
3914                    }),
3915            )
3916        })
3917    }
3918}
3919
3920/// How [`FixedNotes`] treats a filter argument (`sources` or `exclude`) of the selection
3921/// methods of [`InputSource`].
3922#[derive(Clone, Copy)]
3923enum FilterHandling {
3924    /// The filter is applied, as [`InputSource`] requires.
3925    Honored,
3926    /// The filter is ignored, breaking the contract of [`InputSource`], for tests of what input
3927    /// selection does against such a source.
3928    Ignored,
3929}
3930
3931/// Errors of [`FixedNotes`].
3932#[derive(Debug)]
3933#[non_exhaustive]
3934pub enum FixedNotesError {
3935    /// More selections were made than [`FixedNotes::with_selection_limit`] allows.
3936    SelectionLimitReached,
3937    /// The fixture does not implement the operation.
3938    Unsupported,
3939}
3940
3941impl fmt::Display for FixedNotesError {
3942    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3943        match self {
3944            Self::SelectionLimitReached => {
3945                write!(f, "the fixture's selection limit was reached")
3946            }
3947            Self::Unsupported => write!(f, "the fixture does not implement the operation"),
3948        }
3949    }
3950}
3951
3952impl std::error::Error for FixedNotesError {}
3953
3954/// A Sapling note of `value` to the default address of the master key of the empty seed.
3955fn fixed_sapling_note(value: Zatoshis) -> ::sapling::Note {
3956    let (_, recipient) = ExtendedSpendingKey::master(&[])
3957        .expect("the master key of the empty seed is valid")
3958        .default_address();
3959    ::sapling::Note::from_parts(
3960        recipient,
3961        SaplingNoteValue::from_raw(value.into_u64()),
3962        Rseed::AfterZip212([0; 32]),
3963    )
3964}
3965
3966/// An Orchard-protocol note of `value` and `version` to the default address of the account
3967/// derived from the all-zero seed.
3968#[cfg(feature = "orchard")]
3969fn fixed_orchard_note(value: Zatoshis, version: NoteVersion) -> OrchardNote {
3970    let sk = OrchardSpendingKey::from_zip32_seed(
3971        &[0; 32],
3972        NetworkConstants::coin_type(&Network::TestNetwork),
3973        zip32::AccountId::ZERO,
3974    )
3975    .expect("the all-zero seed derives a valid Orchard spending key");
3976    let recipient = OrchardFullViewingKey::from(&sk).address_at(0u32, Scope::External);
3977    let rho = Option::from(Rho::from_bytes(&[0; 32])).expect("zero is a canonical rho");
3978    let mut rng = ChaChaRng::from_seed([0; 32]);
3979    let rseed = loop {
3980        if let Some(rseed) = Option::from(RandomSeed::from_bytes(rng.random(), &rho)) {
3981            break rseed;
3982        }
3983    };
3984    Option::from(OrchardNote::from_parts(
3985        recipient,
3986        OrchardNoteValue::from_raw(value.into_u64()),
3987        rho,
3988        rseed,
3989        version,
3990    ))
3991    .expect("the parts form a valid Orchard note")
3992}
3993
3994/// A note held by [`FixedNotes`].
3995enum FixedNote {
3996    Sapling(ReceivedNote<u32, ::sapling::Note>),
3997    #[cfg(feature = "orchard")]
3998    Orchard(ReceivedNote<u32, OrchardNote>),
3999    #[cfg(feature = "orchard")]
4000    Ironwood(ReceivedNote<u32, OrchardNote>),
4001}
4002
4003impl FixedNote {
4004    /// Builds a note of `value` in `pool`, received at `output_index` of the all-zero txid.
4005    fn new(pool: ShieldedPool, id: u32, value: Zatoshis, output_index: u16) -> Self {
4006        fn received<NoteT>(id: u32, output_index: u16, note: NoteT) -> ReceivedNote<u32, NoteT> {
4007            ReceivedNote::from_parts(
4008                id,
4009                TxId::from_bytes([0; 32]),
4010                output_index,
4011                note,
4012                Scope::External,
4013                Position::from(u64::from(output_index)),
4014                None,
4015                None,
4016            )
4017        }
4018        match pool {
4019            ShieldedPool::Sapling => {
4020                Self::Sapling(received(id, output_index, fixed_sapling_note(value)))
4021            }
4022            #[cfg(feature = "orchard")]
4023            ShieldedPool::Orchard => Self::Orchard(received(
4024                id,
4025                output_index,
4026                fixed_orchard_note(value, NoteVersion::V2),
4027            )),
4028            #[cfg(feature = "orchard")]
4029            ShieldedPool::Ironwood => Self::Ironwood(received(
4030                id,
4031                output_index,
4032                fixed_orchard_note(value, NoteVersion::V3),
4033            )),
4034            #[cfg(not(feature = "orchard"))]
4035            ShieldedPool::Orchard | ShieldedPool::Ironwood => {
4036                panic!("Orchard and Ironwood notes need the `orchard` feature")
4037            }
4038        }
4039    }
4040
4041    fn pool(&self) -> ShieldedPool {
4042        match self {
4043            Self::Sapling(_) => ShieldedPool::Sapling,
4044            #[cfg(feature = "orchard")]
4045            Self::Orchard(_) => ShieldedPool::Orchard,
4046            #[cfg(feature = "orchard")]
4047            Self::Ironwood(_) => ShieldedPool::Ironwood,
4048        }
4049    }
4050
4051    fn id(&self) -> u32 {
4052        match self {
4053            Self::Sapling(note) => *note.internal_note_id(),
4054            #[cfg(feature = "orchard")]
4055            Self::Orchard(note) | Self::Ironwood(note) => *note.internal_note_id(),
4056        }
4057    }
4058
4059    fn value(&self) -> Zatoshis {
4060        match self {
4061            Self::Sapling(note) => note.note_value(),
4062            #[cfg(feature = "orchard")]
4063            Self::Orchard(note) | Self::Ironwood(note) => note.note_value(),
4064        }
4065        .expect("the note was built from a valid value")
4066    }
4067}
4068
4069/// An [`InputSource`] holding a fixed list of shielded notes, for tests that drive input
4070/// selection without a wallet database.
4071///
4072/// Selection takes the notes in the order given, within the pools asked for, until the target
4073/// value is reached. Unlike `zcash_client_sqlite`, it does not withhold notes at or below the
4074/// marginal fee. Every note is spendable by any account, and every account can receive change
4075/// in every shielded pool and has no transparent receiver. The selection methods,
4076/// [`InputSource::select_unspent_notes`] and [`InputSource::get_change_receivers`] are
4077/// implemented; every other operation returns [`FixedNotesError::Unsupported`].
4078pub struct FixedNotes {
4079    notes: Vec<FixedNote>,
4080    sources_handling: FilterHandling,
4081    exclude_handling: FilterHandling,
4082    selection_limit: Option<usize>,
4083    selections: Cell<usize>,
4084}
4085
4086impl FixedNotes {
4087    /// Holds one note per entry, given as its pool, identifier and value in selection order.
4088    /// Each note is received at its own output index of a single transaction.
4089    ///
4090    /// # Panics
4091    ///
4092    /// When the notes' total value exceeds the monetary range, when there are more notes than
4093    /// a `u16` output index can number, and without the `orchard` feature on an Orchard or
4094    /// Ironwood entry.
4095    pub fn new(notes: &[(ShieldedPool, u32, Zatoshis)]) -> Self {
4096        let notes: Vec<FixedNote> = notes
4097            .iter()
4098            .zip(0u16..)
4099            .map(|((pool, id, value), output_index)| {
4100                FixedNote::new(*pool, *id, *value, output_index)
4101            })
4102            .collect();
4103        notes
4104            .iter()
4105            .map(FixedNote::value)
4106            .sum::<Option<Zatoshis>>()
4107            .expect("the notes' total value fits the monetary range");
4108        Self {
4109            notes,
4110            sources_handling: FilterHandling::Honored,
4111            exclude_handling: FilterHandling::Honored,
4112            selection_limit: None,
4113            selections: Cell::new(0),
4114        }
4115    }
4116
4117    /// Returns the source with the `sources` argument of the selection methods ignored, so
4118    /// that it returns notes from pools it was not asked for, breaking the contract of
4119    /// [`InputSource`].
4120    pub fn ignoring_sources(self) -> Self {
4121        Self {
4122            sources_handling: FilterHandling::Ignored,
4123            ..self
4124        }
4125    }
4126
4127    /// Returns the source with the `exclude` argument of the selection methods ignored, so
4128    /// that it returns excluded notes, breaking the contract of [`InputSource`].
4129    pub fn ignoring_exclude(self) -> Self {
4130        Self {
4131            exclude_handling: FilterHandling::Ignored,
4132            ..self
4133        }
4134    }
4135
4136    /// Returns the source failing with [`FixedNotesError::SelectionLimitReached`] past `limit`
4137    /// calls to [`InputSource::select_spendable_notes`], so that a test of input selection's
4138    /// termination fails instead of hanging.
4139    pub fn with_selection_limit(self, limit: usize) -> Self {
4140        Self {
4141            selection_limit: Some(limit),
4142            ..self
4143        }
4144    }
4145
4146    /// Returns the notes in `sources` not excluded, in order, until their value reaches
4147    /// `target`, or all of them when `target` is `None`.
4148    fn select(
4149        &self,
4150        sources: &[ShieldedPool],
4151        exclude: &[u32],
4152        target: Option<Zatoshis>,
4153    ) -> ReceivedNotes<u32> {
4154        let in_sources = |pool: ShieldedPool| match self.sources_handling {
4155            FilterHandling::Honored => sources.contains(&pool),
4156            FilterHandling::Ignored => true,
4157        };
4158        let excluded = |id: u32| match self.exclude_handling {
4159            FilterHandling::Honored => exclude.contains(&id),
4160            FilterHandling::Ignored => false,
4161        };
4162        let mut selected_value = Zatoshis::ZERO;
4163        let mut sapling = vec![];
4164        #[cfg(feature = "orchard")]
4165        let mut orchard = vec![];
4166        #[cfg(feature = "orchard")]
4167        let mut ironwood = vec![];
4168        for note in &self.notes {
4169            if target.is_some_and(|target| selected_value >= target) {
4170                break;
4171            }
4172            if !in_sources(note.pool()) || excluded(note.id()) {
4173                continue;
4174            }
4175            selected_value = (selected_value + note.value())
4176                .expect("a partial sum of a total in the monetary range is in it too");
4177            match note {
4178                FixedNote::Sapling(note) => sapling.push(note.clone()),
4179                #[cfg(feature = "orchard")]
4180                FixedNote::Orchard(note) => orchard.push(note.clone()),
4181                #[cfg(feature = "orchard")]
4182                FixedNote::Ironwood(note) => ironwood.push(note.clone()),
4183            }
4184        }
4185        ReceivedNotes::new(
4186            sapling,
4187            #[cfg(feature = "orchard")]
4188            orchard,
4189            #[cfg(feature = "orchard")]
4190            ironwood,
4191        )
4192    }
4193}
4194
4195impl InputSource for FixedNotes {
4196    type Error = FixedNotesError;
4197    type AccountId = u32;
4198    type NoteRef = u32;
4199
4200    fn get_spendable_note(
4201        &self,
4202        _txid: &TxId,
4203        _protocol: ShieldedPool,
4204        _index: u32,
4205        _target_height: TargetHeight,
4206        _lock_filter: LockFilter<'_>,
4207    ) -> Result<Option<ReceivedNote<Self::NoteRef, Note>>, Self::Error> {
4208        Err(FixedNotesError::Unsupported)
4209    }
4210
4211    fn anchor_computable(
4212        &self,
4213        _protocol: ShieldedPool,
4214        _height: BlockHeight,
4215    ) -> Result<bool, Self::Error> {
4216        Err(FixedNotesError::Unsupported)
4217    }
4218
4219    fn select_spendable_notes(
4220        &self,
4221        _account: Self::AccountId,
4222        target_value: TargetValue,
4223        sources: &[ShieldedPool],
4224        _target_height: TargetHeight,
4225        _confirmations_policy: ConfirmationsPolicy,
4226        exclude: &[Self::NoteRef],
4227        _lock_filter: LockFilter<'_>,
4228    ) -> Result<ReceivedNotes<Self::NoteRef>, Self::Error> {
4229        let selections = self.selections.get() + 1;
4230        if self.selection_limit.is_some_and(|limit| selections > limit) {
4231            return Err(FixedNotesError::SelectionLimitReached);
4232        }
4233        self.selections.set(selections);
4234        let target = match target_value {
4235            TargetValue::AtLeast(target) => Some(target),
4236            TargetValue::AllFunds(_) => None,
4237        };
4238        Ok(self.select(sources, exclude, target))
4239    }
4240
4241    fn select_unspent_notes(
4242        &self,
4243        _account: Self::AccountId,
4244        sources: &[ShieldedPool],
4245        _target_height: TargetHeight,
4246        exclude: &[Self::NoteRef],
4247        _lock_filter: LockFilter<'_>,
4248    ) -> Result<ReceivedNotes<Self::NoteRef>, Self::Error> {
4249        Ok(self.select(sources, exclude, None))
4250    }
4251
4252    fn get_change_receivers(
4253        &self,
4254        _account: Self::AccountId,
4255    ) -> Result<ChangeReceivers, Self::Error> {
4256        Ok(ChangeReceivers::new(
4257            true,
4258            true,
4259            #[cfg(feature = "transparent-inputs")]
4260            None,
4261        ))
4262    }
4263
4264    fn get_account_metadata(
4265        &self,
4266        _account: Self::AccountId,
4267        _selector: &NoteFilter,
4268        _target_height: TargetHeight,
4269        _exclude: &[Self::NoteRef],
4270        _lock_filter: LockFilter<'_>,
4271    ) -> Result<AccountMeta, Self::Error> {
4272        Err(FixedNotesError::Unsupported)
4273    }
4274}