Skip to main content

zcash_client_backend/data_api/testing/
pool.rs

1use std::{
2    cmp::Eq,
3    collections::HashSet,
4    convert::Infallible,
5    hash::Hash,
6    num::{NonZeroU8, NonZeroU32, NonZeroU64, NonZeroUsize},
7};
8
9use assert_matches::assert_matches;
10use incrementalmerkletree::{Hashable, Level, Position, frontier::Frontier};
11use rand::{Rng, RngExt};
12use secrecy::Secret;
13use shardtree::error::ShardTreeError;
14use subtle::ConditionallySelectable;
15
16use transparent::address::TransparentAddress;
17use zcash_keys::{
18    address::{Address, UnifiedAddress},
19    keys::{UnifiedAddressRequest, UnifiedSpendingKey},
20};
21use zcash_primitives::{
22    block::BlockHash,
23    transaction::{
24        Transaction,
25        builder::{
26            BLOSSOM_DEFAULT_TX_EXPIRY_DELTA, NU7_DEFAULT_TX_EXPIRY_DELTA, default_tx_expiry_delta,
27        },
28        fees::zip317::{FeeRule as Zip317FeeRule, marginal_fee, minimum_fee},
29    },
30};
31use zcash_protocol::{
32    ShieldedPool,
33    consensus::{self, BlockHeight, BranchId, NetworkUpgrade, Parameters},
34    local_consensus::LocalNetwork,
35    memo::{Memo, MemoBytes},
36    value::{COIN, MAX_MONEY, Zatoshis},
37};
38use zip32::Scope;
39use zip321::{Payment, TransactionRequest};
40
41use crate::{
42    data_api::{
43        self, Account as _, AccountBirthday, BoundedU8, DecryptedTransaction, InputSource,
44        MaxSpendMode, NoteFilter, Ratio, SAPLING_SHARD_HEIGHT, TargetValue, WalletCommitmentTrees,
45        WalletRead, WalletSummary, WalletTest, WalletWrite,
46        anchor_retention::AnchorRetentionInterval,
47        chain::{self, BlockSource, ChainState, CommitmentTreeRoot, ScanSummary},
48        error::{AddressExpiryError, Error},
49        scanning::ScanPriority,
50        testing::{
51            AddressType, CacheInsertionResult, FakeCompactOutput, InitialChainState, TestBuilder,
52            single_output_change_strategy,
53        },
54        wallet::{
55            ConfirmationsPolicy, TargetHeight, TransferErrT, decrypt_and_store_transaction,
56            input_selection::{GreedyInputSelector, LockFilter},
57        },
58    },
59    decrypt_transaction,
60    fees::{
61        self, DustOutputPolicy, SplitPolicy, StandardFeeRule,
62        standard::{self, SingleOutputChangeStrategy},
63    },
64    scanning::ScanError,
65    wallet::{Note, NoteId, OvkPolicy, ReceivedNote},
66};
67
68use super::{DataStoreFactory, Reset, TestCache, TestFvk, TestState};
69
70use crate::data_api::ll::wallet::PRUNING_DEPTH;
71use crate::data_api::wallet::input_selection::GreedyInputSelectorError;
72use crate::{
73    data_api::BlockMetadata,
74    scanning::{
75        ScanningKeys, SpendIdentifiers,
76        full::{decrypt_block, scan_block},
77    },
78};
79use incrementalmerkletree::Retention;
80use nonempty::NonEmpty;
81use shardtree::{ShardTree, store::ShardStore};
82use std::collections::BTreeSet;
83use zcash_primitives::block::{Block, BlockHeaderData};
84use zcash_protocol::PoolType;
85
86#[cfg(feature = "orchard")]
87use {
88    super::orchard::OrchardPoolTester,
89    crate::data_api::{ORCHARD_SHARD_HEIGHT, wallet::propose_transfer},
90    std::collections::BTreeMap,
91    zcash_primitives::transaction::{TxVersion, builder::BundlePadding},
92    zcash_protocol::zip318::{AnchorBucketInterval, MAX_RESIDUAL_VALUE},
93};
94
95#[cfg(not(feature = "orchard"))]
96use zcash_address::{
97    ZcashAddress,
98    unified::{self, Encoding as _, Receiver, Revision, Uitem},
99};
100
101// `ProposalError` also reaches this module through the `transparent-inputs` group below,
102// so this arm covers only the configuration in which that group is absent.
103#[cfg(all(feature = "orchard", not(feature = "transparent-inputs")))]
104use crate::proposal::ProposalError;
105
106// `SpendPolicy` is used only by scenarios behind one of these two features.
107#[cfg(any(feature = "orchard", feature = "transparent-inputs"))]
108use crate::data_api::wallet::input_selection::SpendPolicy;
109
110#[cfg(feature = "transparent-inputs")]
111use {
112    crate::{
113        data_api::{
114            CoinbaseFilter, OutputOfSentTx, TransactionDataRequest, TransactionStatus,
115            wallet::input_selection::TransparentSpendPolicy,
116        },
117        fees::ChangeValue,
118        proposal::{Proposal, ProposalError, StepOutput, StepOutputIndex},
119        wallet::{Exposure, TransparentAddressSource, WalletTransparentOutput},
120    },
121    secrecy::ExposeSecret,
122    std::str::FromStr,
123    transparent::bundle::{OutPoint, TxOut},
124    zcash_keys::keys::transparent::{
125        NonHardenedChildIndex, TransparentKeyScope, gap_limits::GapLimits,
126    },
127    zcash_primitives::transaction::fees::{FeeRule, transparent::InputSize},
128    zcash_protocol::{
129        TxId,
130        value::{BalanceError, ZatBalance},
131    },
132};
133
134#[cfg(feature = "pczt")]
135use {
136    crate::data_api::wallet::{SignerView, redact_pczt_for_batch_signer, redact_pczt_for_signer},
137    pczt::roles::{combiner::Combiner, prover::Prover, signer::Signer},
138    rand::rngs::SysRng,
139    rand_core::UnwrapErr,
140    transparent::builder::TransparentSigningSet,
141    zcash_primitives::transaction::builder::{BuildConfig, Builder},
142    zcash_proofs::prover::LocalTxProver,
143    zcash_protocol::consensus::ZIP212_GRACE_PERIOD,
144    zcash_script::opcode::PushValue,
145};
146
147#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
148use {
149    crate::data_api::wallet::input_selection::LockedInputPolicy,
150    zcash_protocol::consensus::COINBASE_MATURITY_BLOCKS,
151};
152
153pub mod dsl;
154use dsl::{TestDsl, TestNoteConfig, TestScenario};
155
156pub mod locking;
157pub use locking::*;
158
159/// Value of the single wallet note placed in shard 1 by the
160/// [`build_stable_shard_fixture`] and [`build_tip_shard_fixture`] fixtures.
161pub(crate) const SHARD_1_NOTE_VALUE: Zatoshis = Zatoshis::const_from_u64(150_000);
162
163/// Number of empty cached (but unscanned) blocks that
164/// [`build_shard_1_note_fixture`] places *below* the account birthday, so
165/// that a rewind which lowers the account birthday can recover by re-scanning
166/// genuine cached blocks. Deliberately not aligned with any rewind target or
167/// window boundary used by the tests, so boundary off-by-one errors cannot be
168/// masked by coincidentally-matching fixture geometry.
169pub(crate) const PRE_BIRTHDAY_BLOCKS: u32 = 55;
170
171/// Value of account A's wallet note (placed in the interior of completed
172/// shard 1) in the [`build_two_account_recovery_fixture`] fixture.
173const RECOVERY_A_NOTE_VALUE: Zatoshis = Zatoshis::const_from_u64(150_000);
174
175/// Value of account B's wallet note (placed in the chain-tip shard) in the
176/// [`build_two_account_recovery_fixture`] fixture.
177const RECOVERY_B_NOTE_VALUE: Zatoshis = Zatoshis::const_from_u64(80_000);
178
179/// The order in which [`build_shard_1_note_fixture`] scans the block holding the wallet note
180/// (Block A) and the block completing shard 1 (Block B).
181#[derive(Clone, Copy, PartialEq, Eq)]
182enum Shard1ScanOrder {
183    /// Scan Block A, then Block B, then record shard 1's root. The wallet discovers the note while
184    /// shard 1 is open.
185    NoteFirst,
186    /// Scan Block B, record shard 1's root, then scan Block A. The wallet discovers the note in a
187    /// completed shard.
188    CompletionFirst,
189}
190
191/// The number of leaves between the shard 1 fixtures' initial frontier and the end of shard 1.
192/// The frontier ends at position 131000, so shard 1's last position is 131071.
193const SHARD_1_FRONTIER_GAP: u32 = 71;
194
195/// Builds the starting state shared by the shard 1 fixtures: note commitment trees whose
196/// frontier lies [`SHARD_1_FRONTIER_GAP`] leaves short of shard 1's end,
197/// [`PRE_BIRTHDAY_BLOCKS`] cached empty blocks below the birthday, and an account imported
198/// at the birthday. Returns the test state, the account's id, its spending key, and its
199/// viewing key for pool `T`.
200fn build_shard_1_prefix_fixture<T, Dsf>(
201    ds_factory: Dsf,
202    cache: impl TestCache,
203) -> (
204    TestState<impl TestCache, Dsf::DataStore, LocalNetwork>,
205    <Dsf as DataStoreFactory>::AccountId,
206    UnifiedSpendingKey,
207    T::Fvk,
208)
209where
210    T: ShieldedPoolTester,
211    Dsf: DataStoreFactory,
212    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
213{
214    // Sapling and Orchard shards have the same height, so one shard size positions the
215    // frontier of each pool.
216    const SHARD_POSITIONS: u32 = 1 << SAPLING_SHARD_HEIGHT;
217    #[cfg(feature = "orchard")]
218    const _: () = assert!(SAPLING_SHARD_HEIGHT == ORCHARD_SHARD_HEIGHT);
219
220    // Matches the hard-coded seed used by
221    // `TestBuilder::with_account_having_current_birthday`, so the imported
222    // account carries the keys that builder-created accounts would have.
223    const TEST_SEED: [u8; 32] = [0u8; 32];
224
225    // The frontier is unaligned with shard boundaries; a boundary-aligned
226    // frontier would cause `prior_subtree_roots` to cache shard 1 and then
227    // `insert_frontier` would fail trying to reinstall its leaf into the
228    // cached-leaf-form shard.
229    let initial_tree_size: u32 = 2 * SHARD_POSITIONS - SHARD_1_FRONTIER_GAP;
230
231    let mut st = TestBuilder::new()
232        .with_data_store_factory(ds_factory)
233        .with_block_cache(cache)
234        .with_initial_chain_state(|rng, network| {
235            let birthday_height = network.activation_height(NetworkUpgrade::Nu5).unwrap() + 1000;
236
237            let (prior_sapling_roots, sapling_initial_tree) =
238                Frontier::random_with_prior_subtree_roots(
239                    rng,
240                    initial_tree_size.into(),
241                    NonZeroU8::new(SAPLING_SHARD_HEIGHT).unwrap(),
242                );
243            let prior_sapling_roots = prior_sapling_roots
244                .into_iter()
245                .map(|root| CommitmentTreeRoot::from_parts(birthday_height - 500, root))
246                .collect::<Vec<_>>();
247
248            #[cfg(feature = "orchard")]
249            let (prior_orchard_roots, orchard_initial_tree) =
250                Frontier::random_with_prior_subtree_roots(
251                    rng,
252                    initial_tree_size.into(),
253                    NonZeroU8::new(ORCHARD_SHARD_HEIGHT).unwrap(),
254                );
255            #[cfg(feature = "orchard")]
256            let prior_orchard_roots = prior_orchard_roots
257                .into_iter()
258                .map(|root| CommitmentTreeRoot::from_parts(birthday_height - 500, root))
259                .collect::<Vec<_>>();
260
261            // Ironwood is not active at these test heights, so its tree is empty.
262            #[cfg(feature = "orchard")]
263            let ironwood_initial_tree = Frontier::empty();
264
265            InitialChainState {
266                chain_state: ChainState::new(
267                    birthday_height - 1 - PRE_BIRTHDAY_BLOCKS,
268                    BlockHash([5; 32]),
269                    sapling_initial_tree,
270                    #[cfg(feature = "orchard")]
271                    orchard_initial_tree,
272                    #[cfg(feature = "orchard")]
273                    ironwood_initial_tree,
274                ),
275                prior_sapling_roots,
276                #[cfg(feature = "orchard")]
277                prior_orchard_roots,
278            }
279        })
280        .build();
281
282    // Pre-birthday history: empty blocks at
283    // `[birthday - PRE_BIRTHDAY_BLOCKS, birthday - 1]`, cached but never
284    // scanned during fixture setup. Empty blocks leave the note commitment
285    // trees untouched, so the chain state at `birthday - 1` carries the same
286    // frontier the initial chain state installed.
287    for _ in 0..PRE_BIRTHDAY_BLOCKS {
288        st.generate_empty_block();
289    }
290
291    // Import the wallet account with birthday `birthday_height`, anchored on
292    // the chain state of the cached block at `birthday - 1`. This decouples
293    // the account birthday from the cache floor: the cache extends
294    // `PRE_BIRTHDAY_BLOCKS` below the birthday.
295    let usk = UnifiedSpendingKey::from_seed(st.network(), &TEST_SEED, zip32::AccountId::ZERO)
296        .expect("account USK derivation from seed should succeed");
297    let dfvk = T::sk_to_fvk(T::usk_to_sk(&usk));
298    let birthday_prior_chain_state = st
299        .latest_cached_block()
300        .expect("pre-birthday blocks have been cached")
301        .chain_state()
302        .clone();
303    let birthday = AccountBirthday::from_parts(birthday_prior_chain_state, None);
304    let seed = Secret::new(TEST_SEED.to_vec());
305    let (account, _) = st
306        .wallet_mut()
307        .import_account_hd("primary", &seed, zip32::AccountId::ZERO, &birthday, None)
308        .expect("account import should succeed");
309    let account_id = account.id();
310
311    (st, account_id, usk, dfvk)
312}
313
314/// Shared construction for the stable- and tip-shard fixtures. Both fixtures
315/// use the same initial chain state and two real blocks (Block A places a
316/// wallet note in shard 1's interior, Block B's scan completes shard 1 via
317/// real leaves and spills 9 leaves into shard 2). They differ only in how
318/// many trailing filler blocks are scanned past Block B:
319/// * [`build_stable_shard_fixture`] appends `PRUNING_DEPTH + 10` trailing
320///   blocks, pushing the pruning floor above shard 1's `subtree_end_height`
321///   so the note stabilizes against the completed-shard interpretation.
322/// * [`build_tip_shard_fixture`] appends only 5 trailing blocks, leaving
323///   the wallet's birthday inside the chain-tip pruning window so the note
324///   stabilizes against the active-shard interpretation.
325///
326/// `scan_order` selects whether the wallet discovers the note before or after shard 1 completes.
327///
328/// The block cache also holds [`PRE_BIRTHDAY_BLOCKS`] empty blocks *below*
329/// the account birthday. These are never scanned during fixture setup —
330/// mirroring production, where the chain always has (unscanned) history
331/// below any account's birthday — but they give a rewind-then-rescan flow
332/// real cached blocks to re-scan when a rewind lowers the account birthday.
333/// To decouple the account birthday from the cache floor, the account is
334/// imported mid-fixture (once the pre-birthday blocks exist) rather than
335/// created by `TestBuilder`; its birthday frontier is the chain state of the
336/// cached block at `birthday - 1`.
337///
338/// All block sizes here are well within plausible mainnet limits (the
339/// 300-output-per-block ceiling we use as our model upper bound), and every
340/// block is generated, so the block cache is contiguous from
341/// `birthday - PRE_BIRTHDAY_BLOCKS` to `chain_tip` and any
342/// rewind-then-rescan flow can drive a continuous re-scan.
343///
344/// In the diagram, `X` is the wallet's note commitment, `f` counts
345/// non-wallet filler commitments, `P` is [`PRE_BIRTHDAY_BLOCKS`], and `N` is
346/// `trailing_filler_blocks`. The shard 1/2 boundary falls inside Block B,
347/// whose 30 leaves split 21/9 across it.
348///
349/// ```text
350/// blocks:  |<-(faked state)->|<--P empty blk-->|<------A------>|<------B------>|<-----N blk----->|
351///     birthday-P-1      birthday-P         birthday        birthday+1      birthday+2        chain_tip
352/// leaves:  |<---(2^17-71)--->|<-------0------->|<----X+49f---->|<-----30f----->|<------N f------>|
353/// shards:  |<shard 0>|<--------------------shard 1--------------------->|<-------shard 2------>|...
354/// ```
355///
356/// Wallet notes placed by this fixture:
357///
358/// | height     | position | shard | value      |
359/// |------------|----------|-------|------------|
360/// | `birthday` | 131001   | 1     | 150 000    |
361fn build_shard_1_note_fixture<T, Dsf>(
362    ds_factory: Dsf,
363    cache: impl TestCache,
364    trailing_filler_blocks: u32,
365    scan_order: Shard1ScanOrder,
366) -> (
367    TestState<impl TestCache, Dsf::DataStore, LocalNetwork>,
368    <Dsf as DataStoreFactory>::AccountId,
369    UnifiedSpendingKey,
370)
371where
372    T: ShieldedPoolTester,
373    Dsf: DataStoreFactory,
374    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
375{
376    let (mut st, account_id, usk, dfvk) = build_shard_1_prefix_fixture::<T, Dsf>(ds_factory, cache);
377
378    let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
379    let filler_value = Zatoshis::const_from_u64(1000);
380
381    // Block A at `birthday`: 50 outputs at positions 131001..131050. The
382    // first output is the wallet note (position 131001); outputs 2..50 are
383    // non-wallet fillers. The note sits deep in shard 1's interior, well
384    // away from any shard boundary.
385    let mut block_a_outputs = Vec::with_capacity(50);
386    block_a_outputs.push(FakeCompactOutput::new(
387        dfvk.clone(),
388        AddressType::DefaultExternal,
389        SHARD_1_NOTE_VALUE,
390    ));
391    for _ in 1..50 {
392        block_a_outputs.push(FakeCompactOutput::new(
393            not_our_key.clone(),
394            AddressType::DefaultExternal,
395            filler_value,
396        ));
397    }
398    let (block_a_height, _, _) = st.generate_next_block_multi(&block_a_outputs);
399    if scan_order == Shard1ScanOrder::NoteFirst {
400        st.scan_cached_blocks(block_a_height, 1);
401    }
402
403    // Block B at `birthday + 1`: 30 outputs at positions 131051..131080.
404    // Outputs 1..21 fill the remaining slots of shard 1 (positions
405    // 131051..131071); outputs 22..30 land in shard 2 (positions
406    // 131072..131080). Output 21 fills shard 1's last slot.
407    let block_b_outputs: Vec<_> = (0..30)
408        .map(|_| {
409            FakeCompactOutput::new(
410                not_our_key.clone(),
411                AddressType::DefaultExternal,
412                filler_value,
413            )
414        })
415        .collect();
416    let (block_b_height, _, _) = st.generate_next_block_multi(&block_b_outputs);
417    st.scan_cached_blocks(block_b_height, 1);
418
419    // Declare shard 1 complete at `block_b_height` (= `birthday + 1`).
420    // Scanning Block B fills shard 1's last leaf, but the wallet's scanning
421    // path does not on its own write `subtree_end_height` into the
422    // `*_tree_shards` table; that's the caller's responsibility (modelling
423    // the server-cap-sync path in production). Without this call,
424    // `mark_stabilized_notes` would never see a non-NULL
425    // `subtree_end_height` for shard 1 and the wallet note would never
426    // stabilize.
427    let shard_1_root = T::shard_root(&mut st, 1).unwrap();
428    T::put_subtree_roots(
429        &mut st,
430        1,
431        &[CommitmentTreeRoot::from_parts(block_b_height, shard_1_root)],
432    )
433    .unwrap();
434    if scan_order == Shard1ScanOrder::CompletionFirst {
435        st.scan_cached_blocks(block_a_height, 1);
436    }
437
438    // Trailing filler blocks past Block B, each adding 1 non-wallet output to
439    // shard 2.
440    if trailing_filler_blocks > 0 {
441        for _ in 0..trailing_filler_blocks {
442            st.generate_next_block(&not_our_key, AddressType::DefaultExternal, filler_value);
443        }
444        st.scan_cached_blocks(block_b_height + 1, trailing_filler_blocks as usize);
445    }
446
447    (st, account_id, usk)
448}
449
450/// Builds a fixture in which the wallet's shard 1 contains a real wallet
451/// note at position 131001, the shard completes via real scanning at
452/// `birthday + 1`, and `PRUNING_DEPTH + 10` trailing filler blocks push the
453/// pruning floor above shard 1's `subtree_end_height`. Under the corrected
454/// spendability rule the note is stabilized with `witness_settled_height =
455/// birthday + 1` (the completed-shard `subtree_end_height`).
456///
457/// Final state:
458///   `chain_tip = birthday + PRUNING_DEPTH + 11`
459///   `pruning_floor = birthday + 11`
460///   shard 1: complete (positions 65536..131071), `subtree_end_height = birthday + 1`
461///   shard 2: partial (positions 131072..131072 + 8 + PRUNING_DEPTH + 10)
462pub(crate) fn build_stable_shard_fixture<T, Dsf>(
463    ds_factory: Dsf,
464    cache: impl TestCache,
465) -> (
466    TestState<impl TestCache, Dsf::DataStore, LocalNetwork>,
467    <Dsf as DataStoreFactory>::AccountId,
468    UnifiedSpendingKey,
469)
470where
471    T: ShieldedPoolTester,
472    Dsf: DataStoreFactory,
473    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
474{
475    build_shard_1_note_fixture::<T, Dsf>(
476        ds_factory,
477        cache,
478        PRUNING_DEPTH + 10,
479        Shard1ScanOrder::NoteFirst,
480    )
481}
482
483/// Builds a fixture in which the wallet's shard 1 contains a real wallet
484/// note at position 131001 and the shard completes via real scanning at
485/// `birthday + 1`, but only 5 trailing filler blocks follow -- keeping the
486/// chain tip close enough to the birthday that the birthday height sits
487/// *inside* the chain-tip pruning window. Under the corrected spendability
488/// rule the note is stabilized via the active-shard interpretation:
489/// `witness_settled_height = birthday` (= `t.block`, Block A's height, not
490/// the shard's `subtree_end_height`).
491///
492/// Final state:
493///   `chain_tip = birthday + 6`
494///   `pruning_floor = birthday - 94`  (chain_tip - PRUNING_DEPTH)
495///   `lowest_window_checkpoint = birthday - 93`  (pruning_floor + 1)
496///   birthday sits inside the pruning window; shard 1 is complete but its
497///   `subtree_end_height` (= birthday + 1) is above the pruning floor.
498pub(crate) fn build_tip_shard_fixture<T, Dsf>(
499    ds_factory: Dsf,
500    cache: impl TestCache,
501) -> (
502    TestState<impl TestCache, Dsf::DataStore, LocalNetwork>,
503    <Dsf as DataStoreFactory>::AccountId,
504    UnifiedSpendingKey,
505)
506where
507    T: ShieldedPoolTester,
508    Dsf: DataStoreFactory,
509    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
510{
511    build_shard_1_note_fixture::<T, Dsf>(ds_factory, cache, 5, Shard1ScanOrder::NoteFirst)
512}
513
514/// Builds a two-account fixture backed by a single contiguous run of real blocks, used by the
515/// rewind-recovery tests that need genuine chain history on *both* sides of a wallet birthday.
516///
517/// Account A is the wallet's primary account (zip32 index 0 on seed `[0u8; 32]`, created by
518/// `TestBuilder`); account B is derived from the same seed at zip32 index 1 and imported once the
519/// chain has been scanned up to the block before B's birthday. Importing B mid-fixture is what
520/// lets B's own note be created in a block that the fixture generates.
521///
522/// In the diagram, `A` is account A's note commitment, `B` is account B's note commitment, and `f`
523/// counts non-wallet filler commitments. Heights are `b_A = Nu5 + 1000` (account A's birthday) and
524/// `b_A + 5` (account B's birthday, also denoted `b_B`); the trailing `PRUNING_DEPTH + 10` blocks
525/// push the pruning floor (`chain_tip - PRUNING_DEPTH`) above shard 1's `subtree_end_height`.
526///
527/// ```text
528/// blocks:  |<-(faked state)->|<----A1----->|<----A2---->|<---3 blk--->|<----B----->|<---PD+10 blk--->|
529///       nu5+999             b_A          b_A+1        b_A+2      (b_A+5;b_B)     b_B+4           chain_tip
530/// leaves:  |<---2^17 - 71--->|<---A+34f--->|<----36f--->|<----3f----->|<---B+4f--->|<----PD+10 f---->|
531/// shards:  |<shard 0>|<----------shard 1--------------->|<------------------shard 2------------------>..
532/// ```
533///
534/// * Shard 1 is completed by Block A2's last leaf and declared at
535///   `subtree_end_height = H_A + 1` via `put_subtree_roots`. Account A's note
536///   sits in its interior (position 131001), clear of any shard boundary.
537/// * Shard 2 is the partial chain-tip shard; account B's note (position
538///   131075) sits in its interior.
539/// * Blocks A1, A2, the three fillers, Block B, and the trailing fillers form
540///   one gap-free cached run, so a rewind to any height above `H_A` can be
541///   recovered by re-scanning real blocks rather than faked tree state.
542///
543/// Wallet notes placed by this fixture:
544///
545/// | account | height    | position | shard | value   |
546/// |---------|-----------|----------|-------|---------|
547/// | A       | `H_A`     | 131001   | 1     | 150 000 |
548/// | B       | `H_A + 5` | 131075   | 2     |  80 000 |
549fn build_two_account_recovery_fixture<T, Dsf>(
550    ds_factory: Dsf,
551    cache: impl TestCache,
552) -> (
553    TestState<impl TestCache, Dsf::DataStore, LocalNetwork>,
554    <Dsf as DataStoreFactory>::AccountId,
555    UnifiedSpendingKey,
556)
557where
558    T: ShieldedPoolTester,
559    Dsf: DataStoreFactory,
560    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
561{
562    // Sapling and Orchard shards have the same height, so one shard size positions the
563    // frontier of each pool.
564    const SHARD_POSITIONS: u32 = 1 << SAPLING_SHARD_HEIGHT;
565    #[cfg(feature = "orchard")]
566    const _: () = assert!(SAPLING_SHARD_HEIGHT == ORCHARD_SHARD_HEIGHT);
567
568    // Matches the hard-coded seed used by
569    // `TestBuilder::with_account_having_current_birthday`, so account B can
570    // be derived from the same seed at zip32 index 1.
571    const TEST_SEED: [u8; 32] = [0u8; 32];
572
573    // Initial frontier 71 positions short of shard 1's end (position
574    // 131000); see [`build_shard_1_note_fixture`] for why the frontier is
575    // kept off the shard boundary.
576    let initial_tree_size: u32 = 2 * SHARD_POSITIONS - 71;
577
578    let mut st = TestBuilder::new()
579        .with_data_store_factory(ds_factory)
580        .with_block_cache(cache)
581        .with_initial_chain_state(|rng, network| {
582            let birthday_height = network.activation_height(NetworkUpgrade::Nu5).unwrap() + 1000;
583
584            let (prior_sapling_roots, sapling_initial_tree) =
585                Frontier::random_with_prior_subtree_roots(
586                    rng,
587                    initial_tree_size.into(),
588                    NonZeroU8::new(SAPLING_SHARD_HEIGHT).unwrap(),
589                );
590            let prior_sapling_roots = prior_sapling_roots
591                .into_iter()
592                .map(|root| CommitmentTreeRoot::from_parts(birthday_height - 500, root))
593                .collect::<Vec<_>>();
594
595            #[cfg(feature = "orchard")]
596            let (prior_orchard_roots, orchard_initial_tree) =
597                Frontier::random_with_prior_subtree_roots(
598                    rng,
599                    initial_tree_size.into(),
600                    NonZeroU8::new(ORCHARD_SHARD_HEIGHT).unwrap(),
601                );
602            #[cfg(feature = "orchard")]
603            let prior_orchard_roots = prior_orchard_roots
604                .into_iter()
605                .map(|root| CommitmentTreeRoot::from_parts(birthday_height - 500, root))
606                .collect::<Vec<_>>();
607
608            // Ironwood is not active at these test heights, so its tree is empty.
609            #[cfg(feature = "orchard")]
610            let ironwood_initial_tree = Frontier::empty();
611
612            InitialChainState {
613                chain_state: ChainState::new(
614                    birthday_height - 1,
615                    BlockHash([5; 32]),
616                    sapling_initial_tree,
617                    #[cfg(feature = "orchard")]
618                    orchard_initial_tree,
619                    #[cfg(feature = "orchard")]
620                    ironwood_initial_tree,
621                ),
622                prior_sapling_roots,
623                #[cfg(feature = "orchard")]
624                prior_orchard_roots,
625            }
626        })
627        .with_account_having_current_birthday()
628        .build();
629
630    let dfvk_a = T::test_account_fvk(&st);
631    let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
632    let filler_value = Zatoshis::const_from_u64(1000);
633
634    // Derive account B's viewing key ahead of any scanning so Block B can
635    // carry a B-destined output.
636    let zip32_index_b = zip32::AccountId::ZERO.next().unwrap();
637    let usk_b = UnifiedSpendingKey::from_seed(st.network(), &TEST_SEED, zip32_index_b)
638        .expect("account B USK derivation from seed should succeed");
639    let fvk_b = T::sk_to_fvk(T::usk_to_sk(&usk_b));
640
641    // Block A1 at `H_A`: 35 outputs at positions 131001..131035. Output #1 is
642    // account A's wallet note (position 131001); the rest are non-wallet
643    // fillers.
644    let mut block_a1_outputs = Vec::with_capacity(35);
645    block_a1_outputs.push(FakeCompactOutput::new(
646        dfvk_a.clone(),
647        AddressType::DefaultExternal,
648        RECOVERY_A_NOTE_VALUE,
649    ));
650    for _ in 1..35 {
651        block_a1_outputs.push(FakeCompactOutput::new(
652            not_our_key.clone(),
653            AddressType::DefaultExternal,
654            filler_value,
655        ));
656    }
657    let (block_a1_height, _, _) = st.generate_next_block_multi(&block_a1_outputs);
658
659    // Block A2 at `H_A + 1`: 36 non-wallet outputs at positions
660    // 131036..131071. Output #36 fills shard 1's last leaf.
661    let block_a2_outputs: Vec<_> = (0..36)
662        .map(|_| {
663            FakeCompactOutput::new(
664                not_our_key.clone(),
665                AddressType::DefaultExternal,
666                filler_value,
667            )
668        })
669        .collect();
670    let (block_a2_height, _, _) = st.generate_next_block_multi(&block_a2_outputs);
671    st.scan_cached_blocks(block_a1_height, 2);
672
673    // Declare shard 1 complete at `H_A + 1`; scanning alone does not write
674    // `subtree_end_height` (see [`build_shard_1_note_fixture`]).
675    let shard_1_root = T::shard_root(&mut st, 1).unwrap();
676    T::put_subtree_roots(
677        &mut st,
678        1,
679        &[CommitmentTreeRoot::from_parts(
680            block_a2_height,
681            shard_1_root,
682        )],
683    )
684    .unwrap();
685
686    // Three filler blocks at `H_A + 2 ..= H_A + 4`, one non-wallet output
687    // each (positions 131072..131074, the start of shard 2).
688    for _ in 0..3 {
689        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, filler_value);
690    }
691    st.scan_cached_blocks(block_a2_height + 1, 3);
692
693    // Import account B with a birthday one block above the current tip
694    // (`H_A + 5`). The prior chain state is taken from the latest cached
695    // block so B's birthday frontier reflects real scanned history.
696    let b_prior_chain_state = st
697        .latest_cached_block()
698        .expect("blocks have been scanned")
699        .chain_state()
700        .clone();
701    let b_birthday = AccountBirthday::from_parts(b_prior_chain_state, None);
702    let seed = Secret::new(TEST_SEED.to_vec());
703    let (account_b, _) = st
704        .wallet_mut()
705        .import_account_hd("account B", &seed, zip32_index_b, &b_birthday, None)
706        .expect("account B import should succeed");
707    let account_b_id = account_b.id();
708
709    // Block B at `H_A + 5`: 5 outputs at positions 131075..131079. Output #1
710    // is account B's wallet note (position 131075); the rest are fillers.
711    let mut block_b_outputs = Vec::with_capacity(5);
712    block_b_outputs.push(FakeCompactOutput::new(
713        fvk_b.clone(),
714        AddressType::DefaultExternal,
715        RECOVERY_B_NOTE_VALUE,
716    ));
717    for _ in 1..5 {
718        block_b_outputs.push(FakeCompactOutput::new(
719            not_our_key.clone(),
720            AddressType::DefaultExternal,
721            filler_value,
722        ));
723    }
724    let (block_b_height, _, _) = st.generate_next_block_multi(&block_b_outputs);
725
726    // `PRUNING_DEPTH + 10` trailing filler blocks push the pruning floor
727    // above shard 1's `subtree_end_height`.
728    let trailing_filler_blocks = PRUNING_DEPTH + 10;
729    for _ in 0..trailing_filler_blocks {
730        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, filler_value);
731    }
732    st.scan_cached_blocks(block_b_height, 1 + trailing_filler_blocks as usize);
733
734    (st, account_b_id, usk_b)
735}
736
737/// Asserts that a send-max-spendable proposal for `account` consumes exactly
738/// `expected_balance`: the proposal's output amounts plus its required fee
739/// must sum to `expected_balance`. Catches the case where the spend path can
740/// see fewer notes than the balance path reported.
741pub(crate) fn assert_send_max_consumes_balance<T, Cache, DbT, ParamsT, AccountIdT, ErrT>(
742    st: &mut TestState<Cache, DbT, ParamsT>,
743    account_id: AccountIdT,
744    expected_balance: Zatoshis,
745) where
746    T: ShieldedPoolTester,
747    Cache: TestCache,
748    <Cache::BlockSource as BlockSource>::Error: std::fmt::Debug,
749    ParamsT: consensus::Parameters + Send + 'static,
750    AccountIdT: std::fmt::Debug + std::cmp::Eq + std::hash::Hash,
751    ErrT: std::fmt::Debug,
752    DbT: InputSource<AccountId = AccountIdT, Error = ErrT>
753        + WalletTest
754        + WalletWrite
755        + WalletRead<AccountId = AccountIdT, Error = ErrT>
756        + WalletCommitmentTrees,
757    <DbT as WalletRead>::AccountId: ConditionallySelectable + Default + Send + 'static,
758{
759    let send_max_recipient = T::sk_default_address(&T::sk(&[0xdd; 32]));
760    let proposal = st
761        .propose_send_max_transfer(
762            account_id,
763            &Zip317FeeRule::standard(),
764            send_max_recipient.to_zcash_address(st.network()),
765            None,
766            MaxSpendMode::MaxSpendable,
767            ConfirmationsPolicy::MIN,
768        )
769        .expect("send-max proposal should succeed when spendable balance is non-zero");
770    let step = proposal.steps().first();
771    let total_payments: Zatoshis = step
772        .transaction_request()
773        .payments()
774        .values()
775        .map(|p| p.amount().expect("send-max proposal payments have amounts"))
776        .sum::<Option<Zatoshis>>()
777        .expect("send-max payments should not overflow");
778    let fee = step.balance().fee_required();
779    assert_eq!(
780        (total_payments + fee).expect("payments + fee should not overflow"),
781        expected_balance,
782        "send-max proposal outputs + fee must equal the spendable balance",
783    );
784}
785
786/// Trait that exposes the pool-specific types and operations necessary to run the
787/// single-shielded-pool tests on a given pool.
788///
789/// You should not need to implement this yourself; instead use [`SaplingPoolTester`] or
790/// [`OrchardPoolTester`] as appropriate.
791///
792/// [`SaplingPoolTester`]: super::sapling::SaplingPoolTester
793#[cfg_attr(
794    feature = "orchard",
795    doc = "[`OrchardPoolTester`]: super::orchard::OrchardPoolTester"
796)]
797#[cfg_attr(
798    not(feature = "orchard"),
799    doc = "[`OrchardPoolTester`]: https://github.com/zcash/librustzcash/blob/0777cbc2def6ba6b99f96333eaf96c314c1f3a37/zcash_client_backend/src/data_api/testing/orchard.rs#L33"
800)]
801pub trait ShieldedPoolTester {
802    const SHIELDED_PROTOCOL: ShieldedPool;
803
804    type Sk;
805    type Fvk: TestFvk;
806    type MerkleTreeHash;
807    type Note;
808
809    fn test_account_fvk<Cache, DbT: WalletTest, P: consensus::Parameters>(
810        st: &TestState<Cache, DbT, P>,
811    ) -> Self::Fvk;
812    fn usk_to_sk(usk: &UnifiedSpendingKey) -> &Self::Sk;
813    fn sk(seed: &[u8]) -> Self::Sk;
814    fn sk_to_fvk(sk: &Self::Sk) -> Self::Fvk;
815    fn sk_default_address(sk: &Self::Sk) -> Address;
816    fn fvk_default_address(fvk: &Self::Fvk) -> Address;
817    fn fvks_equal(a: &Self::Fvk, b: &Self::Fvk) -> bool;
818
819    fn random_fvk(mut rng: impl Rng) -> Self::Fvk {
820        let sk = {
821            let mut sk_bytes = vec![0; 32];
822            rng.fill_bytes(&mut sk_bytes);
823            Self::sk(&sk_bytes)
824        };
825
826        Self::sk_to_fvk(&sk)
827    }
828    fn random_address(rng: impl Rng) -> Address {
829        Self::fvk_default_address(&Self::random_fvk(rng))
830    }
831
832    fn empty_tree_leaf() -> Self::MerkleTreeHash;
833    fn empty_tree_root(level: Level) -> Self::MerkleTreeHash;
834
835    fn put_subtree_roots<Cache, DbT: WalletTest + WalletCommitmentTrees, P>(
836        st: &mut TestState<Cache, DbT, P>,
837        start_index: u64,
838        roots: &[CommitmentTreeRoot<Self::MerkleTreeHash>],
839    ) -> Result<(), ShardTreeError<<DbT as WalletCommitmentTrees>::Error>>;
840
841    /// Computes the actual root of the `shard_index`-th shard from the wallet's local
842    /// shardtree state, reading whatever leaves and cached annotations are currently
843    /// stored. Used by tests that need to call [`Self::put_subtree_roots`] with a root
844    /// that matches the shard's actual computed root — for example, when declaring a
845    /// shard complete after filling its last position via `scan_cached_blocks`.
846    fn shard_root<Cache, DbT: WalletTest + WalletCommitmentTrees, P>(
847        st: &mut TestState<Cache, DbT, P>,
848        shard_index: u64,
849    ) -> Result<Self::MerkleTreeHash, ShardTreeError<<DbT as WalletCommitmentTrees>::Error>>;
850
851    fn next_subtree_index<A: Hash + Eq>(s: &WalletSummary<A>) -> u64;
852
853    fn note_value(note: &Self::Note) -> Zatoshis;
854
855    #[allow(clippy::type_complexity)]
856    fn select_spendable_notes<Cache, DbT: InputSource + WalletTest, P>(
857        st: &TestState<Cache, DbT, P>,
858        account: <DbT as InputSource>::AccountId,
859        target_value: TargetValue,
860        target_height: TargetHeight,
861        confirmations_policy: ConfirmationsPolicy,
862        exclude: &[DbT::NoteRef],
863    ) -> Result<Vec<ReceivedNote<DbT::NoteRef, Self::Note>>, <DbT as InputSource>::Error>;
864
865    #[allow(clippy::type_complexity)]
866    fn select_unspent_notes<Cache, DbT: InputSource + WalletTest, P>(
867        st: &TestState<Cache, DbT, P>,
868        account: <DbT as InputSource>::AccountId,
869        target_height: TargetHeight,
870        exclude: &[DbT::NoteRef],
871    ) -> Result<Vec<ReceivedNote<DbT::NoteRef, Self::Note>>, <DbT as InputSource>::Error>;
872
873    fn decrypted_pool_outputs_count<A>(d_tx: &DecryptedTransaction<Transaction, A>) -> usize;
874
875    fn with_decrypted_pool_memos<A>(
876        d_tx: &DecryptedTransaction<Transaction, A>,
877        f: impl FnMut(&MemoBytes),
878    );
879
880    fn try_output_recovery<P: consensus::Parameters>(
881        params: &P,
882        height: BlockHeight,
883        tx: &Transaction,
884        fvk: &Self::Fvk,
885    ) -> Option<(Note, Address, MemoBytes)>;
886
887    fn received_note_count(summary: &ScanSummary) -> usize;
888
889    #[cfg(feature = "pczt")]
890    fn add_proof_generation_keys(
891        pczt: pczt::Pczt,
892        usk: &UnifiedSpendingKey,
893    ) -> Result<pczt::Pczt, pczt::roles::updater::SaplingError>;
894
895    #[cfg(feature = "pczt")]
896    fn apply_signatures_to_pczt(
897        signer: &mut Signer,
898        usk: &UnifiedSpendingKey,
899    ) -> Result<(), pczt::roles::signer::Error>;
900}
901
902/// The boundaries of `interval` on the chain that `network` describes.
903fn anchor_grid<P: consensus::Parameters>(
904    network: &P,
905    interval: zcash_protocol::zip318::AnchorBucketInterval,
906) -> zcash_protocol::zip318::AnchorGrid {
907    zcash_protocol::zip318::AnchorGrid::new(
908        interval,
909        zcash_protocol::zip318::BlockSpacing::for_network(network),
910    )
911}
912
913/// Tests sending funds within the given shielded pool in a single transaction.
914///
915/// The test:
916/// - Adds funds to the wallet in a single note.
917/// - Checks that the wallet balances are correct.
918/// - Constructs a request to spend part of that balance to an external address in the
919///   same pool.
920/// - Builds the transaction.
921/// - Checks that the transaction was stored, and that the outputs are decryptable and
922///   have the expected details.
923pub fn send_single_step_proposed_transfer<T: ShieldedPoolTester>(
924    dsf: impl DataStoreFactory,
925    cache: impl TestCache,
926) {
927    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
928
929    // Add funds to the wallet in a single note
930    let (h, _, _) = st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60000));
931
932    let to_extsk = T::sk(&[0xf5; 32]);
933    let to: Address = T::sk_default_address(&to_extsk);
934    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
935        to.to_zcash_address(st.network()),
936        Zatoshis::const_from_u64(10000),
937    )])
938    .unwrap();
939
940    let fee_rule = StandardFeeRule::Zip317;
941
942    let change_memo = "Test change memo".parse::<Memo>().unwrap();
943    let change_strategy = standard::SingleOutputChangeStrategy::new(
944        fee_rule,
945        Some(change_memo.clone().into()),
946        T::SHIELDED_PROTOCOL,
947        DustOutputPolicy::default(),
948    );
949    let input_selector = GreedyInputSelector::new();
950
951    let account = st.get_account();
952    let proposal = st
953        .propose_transfer(
954            account.id(),
955            &input_selector,
956            &change_strategy,
957            request,
958            ConfirmationsPolicy::MIN,
959        )
960        .unwrap();
961
962    let sent_tx_id = st.create_proposed_expecting(&proposal, 1)[0];
963
964    // Verify that the sent transaction was stored and that we can decrypt the memos
965    let tx = st
966        .wallet()
967        .get_transaction(sent_tx_id)
968        .unwrap()
969        .expect("Created transaction was stored.");
970    let ufvks = [(account.id(), account.usk().to_unified_full_viewing_key())]
971        .into_iter()
972        .collect();
973    let d_tx = decrypt_transaction(st.network(), None, Some(h), &tx, &ufvks);
974    assert_eq!(T::decrypted_pool_outputs_count(&d_tx), 2);
975
976    let mut found_tx_change_memo = false;
977    let mut found_tx_empty_memo = false;
978    T::with_decrypted_pool_memos(&d_tx, |memo| {
979        if Memo::try_from(memo).unwrap() == change_memo {
980            found_tx_change_memo = true
981        }
982        if Memo::try_from(memo).unwrap() == Memo::Empty {
983            found_tx_empty_memo = true
984        }
985    });
986    assert!(found_tx_change_memo);
987    assert!(found_tx_empty_memo);
988
989    // Verify that the stored sent notes match what we're expecting
990    let sent_note_ids = st
991        .wallet()
992        .get_sent_note_ids(&sent_tx_id, T::SHIELDED_PROTOCOL)
993        .unwrap();
994    assert_eq!(sent_note_ids.len(), 2);
995
996    // The sent memo should be the empty memo for the sent output, and the
997    // change output's memo should be as specified.
998    let mut found_sent_change_memo = false;
999    let mut found_sent_empty_memo = false;
1000    for sent_note_id in sent_note_ids {
1001        match st
1002            .wallet()
1003            .get_memo(sent_note_id)
1004            .expect("Note id is valid")
1005            .as_ref()
1006        {
1007            Some(m) if m == &change_memo => {
1008                found_sent_change_memo = true;
1009            }
1010            Some(m) if m == &Memo::Empty => {
1011                found_sent_empty_memo = true;
1012            }
1013            Some(other) => panic!("Unexpected memo value: {other:?}"),
1014            None => panic!("Memo should not be stored as NULL"),
1015        }
1016    }
1017    assert!(found_sent_change_memo);
1018    assert!(found_sent_empty_memo);
1019
1020    // Check that querying for a nonexistent sent note returns None
1021    assert_matches!(
1022        st.wallet()
1023            .get_memo(NoteId::new(sent_tx_id, T::SHIELDED_PROTOCOL, 12345)),
1024        Ok(None)
1025    );
1026
1027    let tx_history = st.wallet().get_tx_history().unwrap();
1028    assert_eq!(tx_history.len(), 2);
1029    {
1030        let tx_0 = &tx_history[0];
1031        assert_eq!(tx_0.total_spent(), Zatoshis::const_from_u64(0));
1032        assert_eq!(tx_0.total_received(), Zatoshis::const_from_u64(60000));
1033    }
1034
1035    {
1036        let tx_1 = &tx_history[1];
1037        assert_eq!(tx_1.total_spent(), Zatoshis::const_from_u64(60000));
1038        assert_eq!(tx_1.total_received(), Zatoshis::const_from_u64(40000));
1039    }
1040
1041    let network = *st.network();
1042    assert_matches!(
1043        decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, None),
1044        Ok(_)
1045    );
1046}
1047
1048/// Builds a real transaction via the proposal/creation path, assembles it into a full
1049/// block, and verifies that [`decrypt_block`] followed by [`scan_block`] detects the
1050/// wallet output (the change note) that it contains.
1051///
1052/// [`decrypt_block`]: crate::scanning::full::decrypt_block
1053/// [`scan_block`]: crate::scanning::full::scan_block
1054pub fn scan_full_block_detects_outputs<T: ShieldedPoolTester>(
1055    dsf: impl DataStoreFactory,
1056    cache: impl TestCache,
1057) {
1058    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
1059
1060    // Add funds to the wallet in a single note.
1061    let (h, _, _) = st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60000));
1062
1063    // Propose and create a transfer to an external recipient. The resulting transaction
1064    // has two shielded outputs: the payment, and the change returned to the wallet.
1065    let to_extsk = T::sk(&[0xf5; 32]);
1066    let to: Address = T::sk_default_address(&to_extsk);
1067    let request = TransactionRequest::new(vec![Payment::without_memo(
1068        to.to_zcash_address(st.network()),
1069        Zatoshis::const_from_u64(10000),
1070    )])
1071    .unwrap();
1072
1073    let change_strategy =
1074        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
1075    let input_selector = GreedyInputSelector::new();
1076
1077    let account = st.get_account();
1078    let proposal = st
1079        .propose_transfer(
1080            account.id(),
1081            &input_selector,
1082            &change_strategy,
1083            request,
1084            ConfirmationsPolicy::MIN,
1085        )
1086        .unwrap();
1087
1088    let txids = st
1089        .create_proposed_transactions::<Infallible, _, Infallible, _>(
1090            account.usk(),
1091            OvkPolicy::Sender,
1092            &proposal,
1093        )
1094        .unwrap();
1095    assert_eq!(txids.len(), 1);
1096
1097    let tx = st
1098        .wallet()
1099        .get_transaction(*txids.first())
1100        .unwrap()
1101        .expect("the created transaction was stored");
1102
1103    // Build a `ScanningKeys` set for the wallet account. The account identifier used for
1104    // scanning is independent of the wallet database's account identifier.
1105    let ufvk = account.usk().to_unified_full_viewing_key();
1106    let scanning_keys = ScanningKeys::from_account_ufvks([(zip32::AccountId::ZERO, ufvk)]);
1107
1108    // Assemble a single-transaction block containing the created transaction. The block
1109    // is scanned in isolation, so we treat the note commitment trees as empty as of the
1110    // immediately preceding block.
1111    let network = *st.network();
1112    let header = BlockHeaderData {
1113        version: 4,
1114        prev_block: BlockHash([0; 32]),
1115        merkle_root: [0; 32],
1116        final_sapling_root: [0; 32],
1117        time: 0,
1118        bits: 0,
1119        nonce: [0; 32],
1120        solution: vec![],
1121    }
1122    .freeze()
1123    .unwrap();
1124    let block = Block::from_parts(header, NonEmpty::singleton(tx), h);
1125
1126    let prior_block_metadata = BlockMetadata::from_parts(
1127        h - 1,
1128        BlockHash([0; 32]),
1129        Some(0),
1130        #[cfg(feature = "orchard")]
1131        Some(0),
1132        #[cfg(feature = "orchard")]
1133        Some(0),
1134    );
1135
1136    // Phase 1: decrypt the block's shielded outputs.
1137    let (header, vtx) = decrypt_block(&network, block, &scanning_keys);
1138
1139    // Phase 2: scan the decrypted block.
1140    #[cfg(feature = "transparent-inputs")]
1141    let scanned = scan_block(
1142        &network,
1143        h,
1144        &header,
1145        vtx,
1146        &scanning_keys,
1147        &SpendIdentifiers::empty(),
1148        Some(&prior_block_metadata),
1149        |_addr| Ok::<_, Infallible>(None),
1150    )
1151    .expect("scanning the block succeeds");
1152    #[cfg(not(feature = "transparent-inputs"))]
1153    let scanned = scan_block::<_, _, _, Infallible>(
1154        &network,
1155        h,
1156        &header,
1157        vtx,
1158        &scanning_keys,
1159        &SpendIdentifiers::empty(),
1160        Some(&prior_block_metadata),
1161    )
1162    .expect("scanning the block succeeds");
1163
1164    // The wallet should have detected exactly the change output returned to its internal
1165    // address; the payment output was sent to a recipient outside the wallet.
1166    assert_eq!(scanned.transactions().len(), 1);
1167    let received_outputs: usize = scanned
1168        .transactions()
1169        .iter()
1170        .map(|wtx| {
1171            let n = wtx.sapling_outputs().len();
1172            #[cfg(feature = "orchard")]
1173            let n = n + wtx.orchard_outputs().len();
1174            n
1175        })
1176        .sum();
1177    assert_eq!(received_outputs, 1);
1178
1179    // The note commitment tree should have grown by exactly the two shielded outputs in
1180    // the block's single transaction (the payment and the change), starting from the
1181    // empty prior tree. The outputs all belong to the pool under test; the other pool (if
1182    // compiled in) sees no outputs.
1183    let total_commitments = scanned.sapling().commitments().len();
1184    #[cfg(feature = "orchard")]
1185    let total_commitments = total_commitments + scanned.orchard().commitments().len();
1186    assert_eq!(total_commitments, 2);
1187
1188    let total_final_tree_size = scanned.sapling().final_tree_size();
1189    #[cfg(feature = "orchard")]
1190    let total_final_tree_size = total_final_tree_size + scanned.orchard().final_tree_size();
1191    assert_eq!(total_final_tree_size, 2);
1192
1193    // The final note added in the block must be marked as a checkpoint at this block
1194    // height; this is what lets the wallet anchor witnesses to the block. Getting the
1195    // "last outputs in the block" boundary wrong is the most error-prone part of position
1196    // tracking, so we assert it explicitly.
1197    let last_retention = scanned.sapling().commitments().last().map(|(_, r)| *r);
1198    #[cfg(feature = "orchard")]
1199    let last_retention = scanned
1200        .orchard()
1201        .commitments()
1202        .last()
1203        .map(|(_, r)| *r)
1204        .or(last_retention);
1205    assert!(
1206        matches!(last_retention, Some(Retention::Checkpoint { id, .. }) if id == h),
1207        "final note commitment should be a checkpoint at height {h:?}, got {last_retention:?}",
1208    );
1209}
1210
1211#[derive(Clone, Copy, Debug, PartialEq)]
1212struct ConfirmationStep {
1213    i: u32,
1214    confirmation_requirement: u32,
1215    number_of_confirmations: u32,
1216    pending_balance: Zatoshis,
1217    spendable_balance: Zatoshis,
1218    total_balance: Zatoshis,
1219}
1220
1221/// An enumeration of mechanisms for generating transaction inputs for confirmations policy
1222/// testing.
1223#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1224pub enum InputTrust {
1225    /// Generate a wallet-internal output.
1226    Internal,
1227    /// Generate an output as if it was sent to the wallet by an untrusted counterparty.
1228    ExternalUntrusted,
1229    /// Generate an output as if it was sent to the wallet by a trusted counterparty.
1230    ExternalTrusted,
1231}
1232
1233/// Tests that inputs from a source can be spent according to the default
1234/// `ConfirmationsPolicy`.
1235///
1236/// The test:
1237/// - Adds funds to the wallet in a single note from an certain source.
1238/// - Checks that the wallet balances are correct after N confirmations, according to
1239///   the policy.
1240pub fn zip_315_confirmations_test_steps<T: ShieldedPoolTester>(
1241    dsf: impl DataStoreFactory,
1242    cache: impl TestCache,
1243    input_trust: InputTrust,
1244) {
1245    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
1246    let account = st.test_account().cloned().unwrap();
1247    let starting_balance = Zatoshis::const_from_u64(60_000);
1248
1249    // Add funds to the wallet in a single note, owned by the internal spending key,
1250    // which will have one confirmation.
1251    let confirmations_policy = ConfirmationsPolicy::default();
1252    let (address_type, min_confirmations) = match input_trust {
1253        InputTrust::Internal => (AddressType::Internal, confirmations_policy.trusted()),
1254        InputTrust::ExternalUntrusted => (
1255            AddressType::DefaultExternal,
1256            confirmations_policy.untrusted(),
1257        ),
1258        InputTrust::ExternalTrusted => {
1259            (AddressType::DefaultExternal, confirmations_policy.trusted())
1260        }
1261    };
1262    let min_confirmations = u32::from(min_confirmations);
1263
1264    let (_, r, _) = st.add_a_single_note_checking_balance(
1265        TestNoteConfig::from(starting_balance).with_address_type(address_type),
1266    );
1267    let txid = r.txids()[0];
1268
1269    // Mark the external input as explicitly trusted, if so requested
1270    let trusted = input_trust == InputTrust::ExternalTrusted;
1271    if trusted {
1272        st.wallet_mut().set_tx_trust(txid, true).unwrap();
1273    }
1274
1275    let add_confirmation = |i: u32| {
1276        let (h, _) = st.generate_empty_block();
1277        st.scan_cached_blocks(h, 1);
1278        let outputs = st
1279            .wallet()
1280            .get_received_outputs(txid, TargetHeight::from(h + 1), confirmations_policy)
1281            .unwrap();
1282        assert_eq!(outputs.len(), 1);
1283        assert_eq!(
1284            outputs[0].confirmations_until_spendable(),
1285            u32::from(if trusted {
1286                confirmations_policy.trusted()
1287            } else {
1288                confirmations_policy.untrusted()
1289            })
1290            .saturating_sub(i + 1)
1291        );
1292        ConfirmationStep {
1293            i,
1294            confirmation_requirement: min_confirmations,
1295            number_of_confirmations: 1 + i,
1296            pending_balance: st.get_pending_shielded_balance(account.id(), confirmations_policy),
1297            spendable_balance: st.get_spendable_balance(account.id(), confirmations_policy),
1298            total_balance: st.get_total_balance(account.id()),
1299        }
1300    };
1301
1302    // Generate N confirmations by mining blocks
1303    let steps = (1u32..min_confirmations)
1304        .map(add_confirmation)
1305        .collect::<Vec<_>>();
1306
1307    assert!(
1308        steps
1309            .iter()
1310            .filter(|step| step.number_of_confirmations < min_confirmations)
1311            .all(|step| step.spendable_balance == Zatoshis::ZERO),
1312        "spendable balance is equal to starting balance until we have sufficient confirmations"
1313    );
1314
1315    let to = T::random_address(st.rng_mut());
1316    // Now that the funds are spendable, propose a transaction
1317    let proposed = st.propose_standard_transfer::<Infallible>(
1318        account.id(),
1319        StandardFeeRule::Zip317,
1320        confirmations_policy,
1321        &to,
1322        Zatoshis::const_from_u64(10_000),
1323        None,
1324        None,
1325        T::SHIELDED_PROTOCOL,
1326    );
1327    assert!(
1328        proposed.is_ok(),
1329        "Could not spend funds by confirmation policy ({input_trust:?}): {proposed:#?}\n\
1330        steps: {steps:#?}",
1331    );
1332}
1333
1334/// Tests max spendable funds within the given shielded pool in a
1335/// single transaction.
1336///
1337/// The test:
1338/// - Adds funds to the wallet in two notes with different confirmation heights
1339/// - Checks that the wallet balances are correct.
1340/// - Constructs a request to spend the whole balance to an external address in the
1341///   same pool.
1342/// - Builds the transaction.
1343/// - Checks that the transaction was stored, and that the outputs are decryptable and
1344///   have the expected details.
1345pub fn spend_max_spendable_single_step_proposed_transfer<T: ShieldedPoolTester>(
1346    dsf: impl DataStoreFactory,
1347    cache: impl TestCache,
1348) {
1349    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
1350
1351    // Add funds to the wallet in two notes over 5 blocks
1352    let value = Zatoshis::const_from_u64(60000);
1353    let h = st
1354        .add_notes_checking_balance([Some(value), None, None, None, Some(value)])
1355        .block_height()
1356        .unwrap();
1357
1358    // Spendable balance matches total balance
1359    let account = st.test_account().cloned().unwrap();
1360    let confirmation_policy = ConfirmationsPolicy::new_symmetrical(
1361        NonZeroU32::new(2).expect("2 is not zero"),
1362        #[cfg(feature = "transparent-inputs")]
1363        false,
1364    );
1365    assert_eq!(
1366        st.get_spendable_balance(account.id(), confirmation_policy),
1367        value
1368    );
1369
1370    let to_extsk = T::sk(&[0xf5; 32]);
1371    let to: Address = T::sk_default_address(&to_extsk);
1372
1373    let fee_rule = StandardFeeRule::Zip317;
1374
1375    let send_max_memo = "Test Send Max memo".parse::<Memo>().unwrap();
1376
1377    let addy = to.to_zcash_address(st.network());
1378    let proposal = st
1379        .propose_send_max_transfer(
1380            account.id(),
1381            &fee_rule,
1382            addy,
1383            Some(MemoBytes::from(send_max_memo.clone())),
1384            MaxSpendMode::MaxSpendable,
1385            confirmation_policy,
1386        )
1387        .unwrap();
1388
1389    let sent_tx_id = st.create_proposed_expecting(&proposal, 1)[0];
1390
1391    // Verify that the sent transaction was stored and that we can decrypt the memos
1392    let tx = st
1393        .wallet()
1394        .get_transaction(sent_tx_id)
1395        .unwrap()
1396        .expect("Created transaction was stored.");
1397    let ufvks = [(account.id(), account.usk().to_unified_full_viewing_key())]
1398        .into_iter()
1399        .collect();
1400    let d_tx = decrypt_transaction(st.network(), None, Some(h), &tx, &ufvks);
1401    assert_eq!(T::decrypted_pool_outputs_count(&d_tx), 1);
1402
1403    let mut found_send_max_memo = false;
1404    let mut found_tx_empty_memo = false;
1405    T::with_decrypted_pool_memos(&d_tx, |memo| {
1406        if Memo::try_from(memo).unwrap() == send_max_memo {
1407            found_send_max_memo = true
1408        }
1409        if Memo::try_from(memo).unwrap() == Memo::Empty {
1410            found_tx_empty_memo = true
1411        }
1412    });
1413    assert!(found_send_max_memo);
1414    assert!(!found_tx_empty_memo); // there's no empty memo in this case
1415
1416    // Verify that the stored sent notes match what we're expecting
1417    let sent_note_ids = st
1418        .wallet()
1419        .get_sent_note_ids(&sent_tx_id, T::SHIELDED_PROTOCOL)
1420        .unwrap();
1421    assert_eq!(sent_note_ids.len(), 1);
1422
1423    // The sent memo should the specified memo for the sent output
1424    let mut found_sent_empty_memo = false;
1425    let mut found_sent_max_memo = false;
1426    for sent_note_id in sent_note_ids {
1427        match st
1428            .wallet()
1429            .get_memo(sent_note_id)
1430            .expect("Memo retrieval should succeed")
1431            .as_ref()
1432        {
1433            Some(m) if m == &Memo::Empty => {
1434                found_sent_empty_memo = true;
1435            }
1436            Some(m) if m == &send_max_memo => {
1437                found_sent_max_memo = true;
1438            }
1439            Some(other) => panic!("Unexpected memo value: {other:?}"),
1440            None => panic!("Memo should not be stored as NULL"),
1441        }
1442    }
1443
1444    assert!(found_sent_max_memo);
1445    assert!(!found_sent_empty_memo);
1446
1447    // Check that querying for a nonexistent sent note returns None
1448    assert_matches!(
1449        st.wallet()
1450            .get_memo(NoteId::new(sent_tx_id, T::SHIELDED_PROTOCOL, 12345)),
1451        Ok(None)
1452    );
1453
1454    let tx_history = st.wallet().get_tx_history().unwrap();
1455    assert_eq!(tx_history.len(), 3);
1456    {
1457        let tx_0 = &tx_history[0];
1458        assert_eq!(tx_0.total_spent(), Zatoshis::const_from_u64(0));
1459        assert_eq!(tx_0.total_received(), Zatoshis::const_from_u64(60000));
1460    }
1461    {
1462        let tx_1 = &tx_history[1];
1463        assert_eq!(tx_1.total_spent(), Zatoshis::const_from_u64(0));
1464        assert_eq!(tx_1.total_received(), Zatoshis::const_from_u64(60000));
1465    }
1466    {
1467        let tx_2 = &tx_history[2];
1468        assert_eq!(tx_2.total_spent(), Zatoshis::const_from_u64(60000));
1469        assert_eq!(tx_2.total_received(), Zatoshis::const_from_u64(0));
1470    }
1471
1472    let network = *st.network();
1473    assert_matches!(
1474        decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, None),
1475        Ok(_)
1476    );
1477}
1478
1479/// Tests sending every piece of spendable funds within the given shielded pool in a
1480/// single transaction.
1481///
1482/// The test:
1483/// - Adds funds to the wallet in a single note.
1484/// - Checks that the wallet balances are correct.
1485/// - Constructs a request to spend the whole balance to an external address in the
1486///   same pool.
1487/// - Builds the transaction.
1488/// - Checks that the transaction was stored, and that the outputs are decryptable and
1489///   have the expected details.
1490pub fn spend_everything_single_step_proposed_transfer<T: ShieldedPoolTester>(
1491    dsf: impl DataStoreFactory,
1492    cache: impl TestCache,
1493) {
1494    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
1495
1496    let account = st.test_account().cloned().unwrap();
1497
1498    // Add funds to the wallet in a single note
1499    let (h, _, _) = st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60000));
1500
1501    let to_extsk = T::sk(&[0xf5; 32]);
1502    let to: Address = T::sk_default_address(&to_extsk);
1503
1504    let fee_rule = StandardFeeRule::Zip317;
1505
1506    let send_max_memo = "Test Send Max memo".parse::<Memo>().unwrap();
1507
1508    let addy = to.to_zcash_address(st.network());
1509    let proposal = st
1510        .propose_send_max_transfer(
1511            account.id(),
1512            &fee_rule,
1513            addy,
1514            Some(MemoBytes::from(send_max_memo.clone())),
1515            MaxSpendMode::Everything,
1516            ConfirmationsPolicy::MIN,
1517        )
1518        .unwrap();
1519
1520    let sent_tx_id = st.create_proposed_expecting(&proposal, 1)[0];
1521
1522    // Verify that the sent transaction was stored and that we can decrypt the memos
1523    let tx = st
1524        .wallet()
1525        .get_transaction(sent_tx_id)
1526        .unwrap()
1527        .expect("Created transaction was stored.");
1528    let ufvks = [(account.id(), account.usk().to_unified_full_viewing_key())]
1529        .into_iter()
1530        .collect();
1531    let d_tx = decrypt_transaction(st.network(), None, Some(h), &tx, &ufvks);
1532    assert_eq!(T::decrypted_pool_outputs_count(&d_tx), 1);
1533
1534    let mut found_send_max_memo = false;
1535    let mut found_tx_empty_memo = false;
1536    T::with_decrypted_pool_memos(&d_tx, |memo| {
1537        if Memo::try_from(memo).unwrap() == send_max_memo {
1538            found_send_max_memo = true
1539        }
1540        if Memo::try_from(memo).unwrap() == Memo::Empty {
1541            found_tx_empty_memo = true
1542        }
1543    });
1544    assert!(found_send_max_memo);
1545    assert!(!found_tx_empty_memo); // there's no empty memo in this case
1546
1547    // Verify that the stored sent notes match what we're expecting
1548    let sent_note_ids = st
1549        .wallet()
1550        .get_sent_note_ids(&sent_tx_id, T::SHIELDED_PROTOCOL)
1551        .unwrap();
1552    assert_eq!(sent_note_ids.len(), 1);
1553
1554    // The sent memo should the specified memo for the sent output
1555    let mut found_sent_empty_memo = false;
1556    let mut found_sent_max_memo = false;
1557    for sent_note_id in sent_note_ids {
1558        match st
1559            .wallet()
1560            .get_memo(sent_note_id)
1561            .expect("Memo retrieval should succeed")
1562            .as_ref()
1563        {
1564            Some(m) if m == &Memo::Empty => {
1565                found_sent_empty_memo = true;
1566            }
1567            Some(m) if m == &send_max_memo => {
1568                found_sent_max_memo = true;
1569            }
1570            Some(other) => panic!("Unexpected memo value: {other:?}"),
1571            None => panic!("Memo should not be stored as NULL"),
1572        }
1573    }
1574
1575    assert!(found_sent_max_memo);
1576    assert!(!found_sent_empty_memo);
1577
1578    // Check that querying for a nonexistent sent note returns None
1579    assert_matches!(
1580        st.wallet()
1581            .get_memo(NoteId::new(sent_tx_id, T::SHIELDED_PROTOCOL, 12345)),
1582        Ok(None)
1583    );
1584
1585    let tx_history = st.wallet().get_tx_history().unwrap();
1586    assert_eq!(tx_history.len(), 2);
1587    {
1588        let tx_0 = &tx_history[0];
1589        assert_eq!(tx_0.total_spent(), Zatoshis::const_from_u64(0));
1590        assert_eq!(tx_0.total_received(), Zatoshis::const_from_u64(60000));
1591    }
1592
1593    {
1594        let tx_1 = &tx_history[1];
1595        assert_eq!(tx_1.total_spent(), Zatoshis::const_from_u64(60000));
1596        assert_eq!(tx_1.total_received(), Zatoshis::const_from_u64(0));
1597    }
1598
1599    let network = *st.network();
1600    assert_matches!(
1601        decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, None),
1602        Ok(_)
1603    );
1604}
1605
1606/// Tests that sending all the spendable funds within the given shielded pool in a
1607/// single transaction to a transparent address with a memo fails.
1608///
1609/// The test:
1610/// - Adds funds to the wallet in a single note.
1611/// - Checks that the wallet balances are correct.
1612/// - Tries to propose a send max transaction to a T-address with a memo
1613/// - Fails gracefully with Zip321Error.
1614#[cfg(feature = "transparent-inputs")]
1615pub fn fails_to_send_max_spendable_to_transparent_with_memo<T: ShieldedPoolTester>(
1616    dsf: impl DataStoreFactory,
1617    cache: impl TestCache,
1618) {
1619    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
1620
1621    // Add funds to the wallet in a single note
1622    st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60000));
1623
1624    let account = st.test_account().cloned().unwrap();
1625    let (default_addr, _) = account.usk().default_transparent_address();
1626
1627    let to: Address = Address::Transparent(default_addr);
1628
1629    let fee_rule = StandardFeeRule::Zip317;
1630
1631    let send_max_memo = "Test Send Max memo".parse::<Memo>().unwrap();
1632
1633    let addy = to.to_zcash_address(st.network());
1634    assert_matches!(
1635        st.propose_send_max_transfer(
1636            account.id(),
1637            &fee_rule,
1638            addy,
1639            Some(MemoBytes::from(send_max_memo.clone())),
1640            MaxSpendMode::Everything,
1641            ConfirmationsPolicy::MIN
1642        ),
1643        Err(data_api::error::Error::Payment(
1644            zip321::PaymentError::TransparentMemo
1645        ))
1646    );
1647}
1648
1649/// Tests that sending all the spendable funds within the given shielded pool to a
1650/// transparent (non-TEX) recipient succeeds.
1651///
1652/// The test:
1653/// - Adds funds to the wallet in a single note.
1654/// - Proposes a send-max transaction to a transparent address, without a memo.
1655/// - Verifies that the proposal consists of a single step paying the whole balance,
1656///   less the fee, to the transparent recipient.
1657/// - Builds the transaction.
1658#[cfg(feature = "transparent-inputs")]
1659pub fn send_max_spendable_to_transparent<T: ShieldedPoolTester>(
1660    dsf: impl DataStoreFactory,
1661    cache: impl TestCache,
1662) {
1663    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
1664
1665    // Add funds to the wallet in a single note
1666    let value = Zatoshis::const_from_u64(60000);
1667    st.add_a_single_note_checking_balance(value);
1668
1669    let account = st.test_account().cloned().unwrap();
1670    let to: Address = Address::Transparent(TransparentAddress::PublicKeyHash([0x7f; 20]));
1671
1672    let fee_rule = StandardFeeRule::Zip317;
1673
1674    // The proposed transaction carries one shielded spend (padded to two shielded
1675    // outputs) and one transparent output.
1676    let expected_fee = (marginal_fee_at_target(&st) * 3u64).unwrap();
1677    let expected_payment = (value - expected_fee).unwrap();
1678
1679    let addy = to.to_zcash_address(st.network());
1680    let proposal = st
1681        .propose_send_max_transfer(
1682            account.id(),
1683            &fee_rule,
1684            addy,
1685            None,
1686            MaxSpendMode::Everything,
1687            ConfirmationsPolicy::MIN,
1688        )
1689        .unwrap();
1690
1691    let steps: Vec<_> = proposal.steps().iter().cloned().collect();
1692    assert_eq!(steps.len(), 1);
1693    assert_eq!(steps[0].balance().fee_required(), expected_fee);
1694    assert_eq!(steps[0].balance().proposed_change(), []);
1695    assert_eq!(
1696        steps[0].payment_pools(),
1697        &std::collections::BTreeMap::from([(0, PoolType::TRANSPARENT)])
1698    );
1699    assert_matches!(
1700        steps[0].transaction_request().payments().get(&0),
1701        Some(payment) if payment.amount() == Some(expected_payment)
1702    );
1703
1704    st.create_proposed_expecting(&proposal, 1);
1705}
1706
1707/// Tests that a send-max proposal whose total required fee overflows the maximum
1708/// monetary amount fails with a balance error rather than panicking.
1709#[cfg(feature = "transparent-inputs")]
1710pub fn send_max_fee_overflow_is_an_error<T: ShieldedPoolTester>(
1711    dsf: impl DataStoreFactory,
1712    cache: impl TestCache,
1713) {
1714    /// A fee rule that requires the maximum monetary amount for every transaction.
1715    #[derive(Clone, Debug)]
1716    struct MaxMoneyFeeRule;
1717
1718    impl FeeRule for MaxMoneyFeeRule {
1719        type Error = Infallible;
1720
1721        fn fee_required<P: consensus::Parameters>(
1722            &self,
1723            _params: &P,
1724            _target_height: BlockHeight,
1725            _transparent_input_sizes: impl IntoIterator<Item = InputSize>,
1726            _transparent_output_sizes: impl IntoIterator<Item = usize>,
1727            _sapling_input_count: usize,
1728            _sapling_output_count: usize,
1729            _orchard_action_count: usize,
1730            _ironwood_action_count: usize,
1731        ) -> Result<Zatoshis, Self::Error> {
1732            Ok(Zatoshis::const_from_u64(MAX_MONEY))
1733        }
1734    }
1735
1736    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
1737
1738    // Add funds to the wallet in a single note
1739    st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60000));
1740
1741    let account = st.test_account().cloned().unwrap();
1742
1743    // A TEX recipient requires a second transaction, so the total required fee is the
1744    // sum of two per-transaction fees, which overflows the maximum monetary amount.
1745    let tex_addr = Address::Tex([0x4; 20]);
1746    let addy = tex_addr.to_zcash_address(st.network());
1747
1748    assert_matches!(
1749        st.propose_send_max_transfer(
1750            account.id(),
1751            &MaxMoneyFeeRule,
1752            addy,
1753            None,
1754            MaxSpendMode::Everything,
1755            ConfirmationsPolicy::MIN,
1756        ),
1757        Err(data_api::error::Error::NoteSelection(
1758            GreedyInputSelectorError::Balance(BalanceError::Overflow)
1759        ))
1760    );
1761}
1762
1763/// Tests that a send-max proposal spends notes from multiple shielded pools in a single
1764/// transaction when the wallet's funds are split across pools.
1765///
1766/// The test:
1767/// - Adds one note in each of the `P0` and `P1` pools.
1768/// - Proposes a send-max transaction to an external `P1` recipient, so that the value of
1769///   the `P0` note crosses pools.
1770/// - Verifies that the proposal consists of a single step spending both notes and paying
1771///   the whole balance, less the fee, to the recipient.
1772/// - Builds the transaction, mines it, and verifies that the wallet is left empty.
1773#[cfg(feature = "orchard")]
1774pub fn send_max_spends_inputs_across_pools<P0: ShieldedPoolTester, P1: ShieldedPoolTester>(
1775    ds_factory: impl DataStoreFactory,
1776    cache: impl TestCache,
1777) {
1778    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<P0>();
1779    let account = st.test_account().cloned().unwrap();
1780
1781    // Add one note in each of the P0 and P1 pools.
1782    let p0_fvk = P0::test_account_fvk(&st);
1783    let p1_fvk = P1::test_account_fvk(&st);
1784    let note_value = Zatoshis::const_from_u64(350000);
1785    st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
1786    st.generate_next_block(&p1_fvk, AddressType::DefaultExternal, note_value);
1787    st.scan_cached_blocks(account.birthday().height(), 2);
1788
1789    let total = (note_value * 2u64).unwrap();
1790    assert_eq!(
1791        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
1792        total
1793    );
1794
1795    let to: Address = P1::sk_default_address(&P1::sk(&[0xf5; 32]));
1796    let fee_rule = StandardFeeRule::Zip317;
1797
1798    // The proposed transaction spends one note in each pool and pays a single shielded
1799    // output; under ZIP 317, each of the two shielded bundles is padded to two logical
1800    // actions.
1801    let expected_fee = (marginal_fee_at_target(&st) * 4u64).unwrap();
1802    let expected_payment = (total - expected_fee).unwrap();
1803
1804    let addy = to.to_zcash_address(st.network());
1805    let proposal = st
1806        .propose_send_max_transfer(
1807            account.id(),
1808            &fee_rule,
1809            addy,
1810            None,
1811            MaxSpendMode::Everything,
1812            ConfirmationsPolicy::MIN,
1813        )
1814        .unwrap();
1815
1816    let steps: Vec<_> = proposal.steps().iter().cloned().collect();
1817    assert_eq!(steps.len(), 1);
1818    assert_eq!(steps[0].balance().fee_required(), expected_fee);
1819    assert_eq!(steps[0].balance().proposed_change(), []);
1820    assert_eq!(
1821        steps[0].payment_pools(),
1822        &BTreeMap::from([(0, PoolType::Shielded(P1::SHIELDED_PROTOCOL))])
1823    );
1824    assert_matches!(
1825        steps[0].transaction_request().payments().get(&0),
1826        Some(payment) if payment.amount() == Some(expected_payment)
1827    );
1828
1829    // The proposal spends both notes, one from each pool.
1830    let input_notes = steps[0]
1831        .shielded_inputs()
1832        .expect("the proposal has shielded inputs")
1833        .notes();
1834    assert_eq!(input_notes.len(), 2);
1835    let input_pools = input_notes
1836        .iter()
1837        .map(|n| n.note().pool())
1838        .collect::<BTreeSet<_>>();
1839    assert_eq!(
1840        input_pools,
1841        BTreeSet::from([P0::SHIELDED_PROTOCOL, P1::SHIELDED_PROTOCOL])
1842    );
1843
1844    let txids = st.create_proposed_expecting(&proposal, 1);
1845
1846    // Mine the transaction and verify that the entire balance has been spent.
1847    let (h, _) = st.generate_next_block_including(txids[0]);
1848    st.scan_cached_blocks(h, 1);
1849    assert_eq!(st.get_total_balance(account.id()), Zatoshis::ZERO);
1850}
1851
1852/// The value of the `P0` note of the across-pools dust shortfall scenario, which covers the
1853/// payment alone.
1854#[cfg(feature = "orchard")]
1855const DUST_SHORTFALL_P0_NOTE_VALUE: Zatoshis = Zatoshis::const_from_u64(60_000);
1856/// The payment of the across-pools dust shortfall scenario. The `P0` note alone would leave
1857/// change of 3000 zatoshis, below the dust threshold of one marginal fee, so the `P1` note is
1858/// drawn on as well: two bundles, each padded to two logical actions.
1859#[cfg(feature = "orchard")]
1860const DUST_SHORTFALL_PAYMENT: Zatoshis = Zatoshis::const_from_u64(47_000);
1861/// A `P1` note that covers its bundle's share of the two-bundle fee, so that both notes
1862/// together fund the payment.
1863#[cfg(feature = "orchard")]
1864const DUST_SHORTFALL_P1_NOTE_COVERING_FEE: Zatoshis = Zatoshis::const_from_u64(20_000);
1865/// A `P1` note that falls short of its bundle's share of the two-bundle fee, so that both
1866/// notes together fall 1000 zatoshis short of the payment plus that fee.
1867#[cfg(feature = "orchard")]
1868const DUST_SHORTFALL_P1_NOTE_BELOW_FEE: Zatoshis = Zatoshis::const_from_u64(6_000);
1869
1870/// Returns the ZIP 317 marginal fee in effect at the [`proposal_target_height`] of `st`.
1871fn marginal_fee_at_target<C: TestCache, D: WalletTest + WalletWrite, P: Parameters>(
1872    st: &TestState<C, D, P>,
1873) -> Zatoshis {
1874    marginal_fee(st.network(), proposal_target_height(st))
1875}
1876
1877/// Returns the ZIP 317 minimum conventional fee in effect at the [`proposal_target_height`] of
1878/// `st`.
1879fn minimum_fee_at_target<C: TestCache, D: WalletTest + WalletWrite, P: Parameters>(
1880    st: &TestState<C, D, P>,
1881) -> Zatoshis {
1882    minimum_fee(st.network(), proposal_target_height(st))
1883}
1884
1885/// Returns the target height the wallet of `st` assigns to a transaction proposed now.
1886fn proposal_target_height<C: TestCache, D: WalletTest + WalletWrite, P: Parameters>(
1887    st: &TestState<C, D, P>,
1888) -> BlockHeight {
1889    st.wallet()
1890        .get_target_and_anchor_heights(NonZeroU32::MIN)
1891        .expect("the wallet can be read")
1892        .expect("the wallet knows its chain tip")
1893        .0
1894        .into()
1895}
1896
1897/// The ZIP 317 fee of a transaction spending from two shielded pools, each bundle padded to
1898/// two logical actions.
1899#[cfg(feature = "orchard")]
1900fn two_bundle_fee<C: TestCache, D: WalletTest + WalletWrite, P: Parameters>(
1901    st: &TestState<C, D, P>,
1902) -> Zatoshis {
1903    const BUNDLES: u64 = 2;
1904    const PADDED_ACTIONS_PER_BUNDLE: u64 = 2;
1905    (marginal_fee_at_target(st) * (BUNDLES * PADDED_ACTIONS_PER_BUNDLE)).unwrap()
1906}
1907
1908/// The across-pools dust shortfall scenario: an account holding a `P0` note and a smaller `P1`
1909/// note, and a transfer to a `P0` recipient of an amount the `P0` note covers alone, but whose
1910/// change from that note alone would fall below the dust threshold.
1911#[cfg(feature = "orchard")]
1912struct DustShortfallScenario<P0: ShieldedPoolTester, Cache, Dsf: DataStoreFactory> {
1913    st: TestDsl<dsl::TestScenario<P0, Cache, Dsf>>,
1914    recipient: Address,
1915    amount: Zatoshis,
1916    /// The value of both notes.
1917    total: Zatoshis,
1918}
1919
1920/// Builds the across-pools dust shortfall scenario with a `P1` note of `p1_note_value`, both
1921/// notes scanned into the wallet.
1922#[cfg(feature = "orchard")]
1923fn dust_shortfall_across_pools<P0, P1, Cache, Dsf>(
1924    ds_factory: Dsf,
1925    cache: Cache,
1926    p1_note_value: Zatoshis,
1927) -> DustShortfallScenario<P0, Cache, Dsf>
1928where
1929    P0: ShieldedPoolTester,
1930    P1: ShieldedPoolTester,
1931    Cache: TestCache,
1932    Dsf: DataStoreFactory,
1933{
1934    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<P0>();
1935    let account = st.test_account().cloned().unwrap();
1936
1937    let p0_fvk = P0::test_account_fvk(&st);
1938    let p1_fvk = P1::test_account_fvk(&st);
1939    st.generate_next_block(
1940        &p0_fvk,
1941        AddressType::DefaultExternal,
1942        DUST_SHORTFALL_P0_NOTE_VALUE,
1943    );
1944    st.generate_next_block(&p1_fvk, AddressType::DefaultExternal, p1_note_value);
1945    st.scan_cached_blocks(account.birthday().height(), 2);
1946
1947    DustShortfallScenario {
1948        st,
1949        recipient: P0::sk_default_address(&P0::sk(&[0xf5; 32])),
1950        amount: DUST_SHORTFALL_PAYMENT,
1951        total: (DUST_SHORTFALL_P0_NOTE_VALUE + p1_note_value).unwrap(),
1952    }
1953}
1954
1955/// Tests that a transfer whose change from the preferred pool's note would be dust draws on
1956/// a note in another pool instead of failing.
1957///
1958/// The test:
1959/// - Builds the across-pools dust shortfall scenario with a `P1` note that covers the
1960///   two-bundle fee.
1961/// - Verifies that the proposal spends both notes, at the two-bundle fee, and that the
1962///   change is the remainder of both.
1963/// - Builds and mines the transaction, and verifies that the change is all that remains.
1964#[cfg(feature = "orchard")]
1965pub fn transfer_grows_across_pools_at_a_dust_shortfall<
1966    P0: ShieldedPoolTester,
1967    P1: ShieldedPoolTester,
1968>(
1969    ds_factory: impl DataStoreFactory,
1970    cache: impl TestCache,
1971) {
1972    let DustShortfallScenario {
1973        mut st,
1974        recipient,
1975        amount,
1976        total,
1977    } = dust_shortfall_across_pools::<P0, P1, _, _>(
1978        ds_factory,
1979        cache,
1980        DUST_SHORTFALL_P1_NOTE_COVERING_FEE,
1981    );
1982
1983    let expected_fee = two_bundle_fee(&st);
1984    let expected_change = (total - amount - expected_fee).unwrap();
1985
1986    let proposal = st.propose_transfer_to(&recipient, amount);
1987
1988    assert_eq!(proposal.steps().len(), 1);
1989    let step = &proposal.steps().head;
1990    assert_eq!(step.balance().fee_required(), expected_fee);
1991    assert_matches!(
1992        step.transaction_request().payments().get(&0),
1993        Some(payment) if payment.amount() == Some(amount)
1994    );
1995    let input_pools = step
1996        .shielded_inputs()
1997        .expect("the proposal has shielded inputs")
1998        .notes()
1999        .iter()
2000        .map(|n| n.note().pool())
2001        .collect::<BTreeSet<_>>();
2002    assert_eq!(
2003        input_pools,
2004        BTreeSet::from([P0::SHIELDED_PROTOCOL, P1::SHIELDED_PROTOCOL])
2005    );
2006    let change = step.balance().proposed_change();
2007    assert_eq!(change.len(), 1);
2008    assert_eq!(change[0].value(), expected_change);
2009
2010    let txids = st.create_proposed_expecting(&proposal, 1);
2011    let (h, _) = st.generate_next_block_including(txids[0]);
2012    st.scan_cached_blocks(h, 1);
2013    assert_eq!(st.get_total_balance(st.get_account().id()), expected_change);
2014}
2015
2016/// Tests that a transfer which draws on a second pool at a dust shortfall reports
2017/// `InsufficientFunds` over both pools when the second note cannot cover the two-bundle fee.
2018///
2019/// The test:
2020/// - Builds the across-pools dust shortfall scenario with a `P1` note too small for the
2021///   two-bundle fee.
2022/// - Verifies that the proposal fails with `InsufficientFunds`, requiring the amount plus
2023///   the two-bundle fee and reporting the value of both notes as available.
2024#[cfg(feature = "orchard")]
2025pub fn transfer_fails_across_pools_at_a_dust_shortfall<
2026    P0: ShieldedPoolTester,
2027    P1: ShieldedPoolTester,
2028>(
2029    ds_factory: impl DataStoreFactory,
2030    cache: impl TestCache,
2031) {
2032    let DustShortfallScenario {
2033        mut st,
2034        recipient,
2035        amount,
2036        total,
2037    } = dust_shortfall_across_pools::<P0, P1, _, _>(
2038        ds_factory,
2039        cache,
2040        DUST_SHORTFALL_P1_NOTE_BELOW_FEE,
2041    );
2042
2043    let required = (amount + two_bundle_fee(&st)).unwrap();
2044
2045    st.expect_insufficient_funds(&recipient, amount, total, required);
2046}
2047
2048/// Tests that proposing a send-max transfer to a TEX recipient fails with a meaningful
2049/// error when the `transparent-inputs` feature is not enabled.
2050#[cfg(not(feature = "transparent-inputs"))]
2051pub fn send_max_to_tex_fails_without_transparent_inputs<T: ShieldedPoolTester>(
2052    dsf: impl DataStoreFactory,
2053    cache: impl TestCache,
2054) {
2055    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
2056
2057    // Add funds to the wallet in a single note
2058    st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60000));
2059
2060    let account = st.test_account().cloned().unwrap();
2061    let tex_addr = Address::Tex([0x4; 20]);
2062    let fee_rule = StandardFeeRule::Zip317;
2063
2064    let addy = tex_addr.to_zcash_address(st.network());
2065    assert_matches!(
2066        st.propose_send_max_transfer(
2067            account.id(),
2068            &fee_rule,
2069            addy,
2070            None,
2071            MaxSpendMode::Everything,
2072            ConfirmationsPolicy::MIN,
2073        ),
2074        Err(data_api::error::Error::NoteSelection(
2075            GreedyInputSelectorError::UnsupportedTexAddress
2076        ))
2077    );
2078}
2079
2080/// Tests that a send-max proposal to a unified address having both Sapling and Orchard
2081/// receivers is delivered via the Sapling receiver when the `orchard` feature is not
2082/// enabled, rather than failing.
2083#[cfg(not(feature = "orchard"))]
2084pub fn send_max_delivers_via_sapling_when_orchard_is_unavailable<T: ShieldedPoolTester>(
2085    dsf: impl DataStoreFactory,
2086    cache: impl TestCache,
2087) {
2088    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
2089
2090    // Add funds to the wallet in a single note
2091    let value = Zatoshis::const_from_u64(60000);
2092    st.add_a_single_note_checking_balance(value);
2093
2094    let account = st.test_account().cloned().unwrap();
2095
2096    // Construct a unified address carrying both a Sapling receiver and an Orchard
2097    // receiver. Without the `orchard` feature, the Orchard receiver's contents are
2098    // not parsed, so arbitrary receiver bytes suffice.
2099    let sapling_receiver = match T::sk_default_address(&T::sk(&[0xf5; 32])) {
2100        Address::Sapling(addr) => addr.to_bytes(),
2101        _ => panic!("expected a Sapling address"),
2102    };
2103    let ua = unified::Address::try_from_items(
2104        Revision::R0,
2105        vec![
2106            Uitem::Data(Receiver::Sapling(sapling_receiver)),
2107            Uitem::Data(Receiver::Orchard([0xab; 43])),
2108        ],
2109    )
2110    .unwrap();
2111    let addy = ZcashAddress::try_from_encoded(&ua.encode(&st.network().network_type())).unwrap();
2112
2113    let fee_rule = StandardFeeRule::Zip317;
2114
2115    // The proposed transaction carries one Sapling spend and one requested Sapling
2116    // output (padded to two logical actions under ZIP 317).
2117    let expected_fee = minimum_fee_at_target(&st);
2118    let expected_payment = (value - expected_fee).unwrap();
2119
2120    let proposal = st
2121        .propose_send_max_transfer(
2122            account.id(),
2123            &fee_rule,
2124            addy,
2125            None,
2126            MaxSpendMode::Everything,
2127            ConfirmationsPolicy::MIN,
2128        )
2129        .unwrap();
2130
2131    let steps: Vec<_> = proposal.steps().iter().cloned().collect();
2132    assert_eq!(steps.len(), 1);
2133    assert_eq!(steps[0].balance().fee_required(), expected_fee);
2134    assert_eq!(
2135        steps[0].payment_pools(),
2136        &std::collections::BTreeMap::from([(0, PoolType::SAPLING)])
2137    );
2138    assert_matches!(
2139        steps[0].transaction_request().payments().get(&0),
2140        Some(payment) if payment.amount() == Some(expected_payment)
2141    );
2142
2143    st.create_proposed_expecting(&proposal, 1);
2144}
2145
2146/// Tests that a send-max proposal to a unified address whose only receiver cannot be
2147/// paid by this build (an Orchard-only address, without the `orchard` feature) fails
2148/// with `GreedyInputSelectorError::UnsupportedAddress`.
2149#[cfg(not(feature = "orchard"))]
2150pub fn send_max_to_orchard_only_ua_fails_without_orchard<T: ShieldedPoolTester>(
2151    dsf: impl DataStoreFactory,
2152    cache: impl TestCache,
2153) {
2154    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
2155
2156    // Add funds to the wallet in a single note
2157    st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60000));
2158
2159    let account = st.test_account().cloned().unwrap();
2160
2161    // Without the `orchard` feature, the Orchard receiver's contents are not parsed,
2162    // so arbitrary receiver bytes suffice.
2163    let ua = unified::Address::try_from_items(
2164        Revision::R0,
2165        vec![Uitem::Data(Receiver::Orchard([0xab; 43]))],
2166    )
2167    .unwrap();
2168    let addy = ZcashAddress::try_from_encoded(&ua.encode(&st.network().network_type())).unwrap();
2169
2170    let fee_rule = StandardFeeRule::Zip317;
2171
2172    assert_matches!(
2173        st.propose_send_max_transfer(
2174            account.id(),
2175            &fee_rule,
2176            addy,
2177            None,
2178            MaxSpendMode::Everything,
2179            ConfirmationsPolicy::MIN,
2180        ),
2181        Err(data_api::error::Error::NoteSelection(
2182            GreedyInputSelectorError::UnsupportedAddress(_)
2183        ))
2184    );
2185}
2186
2187/// Tests that a send-max proposal fails with `InsufficientFunds` when the entire wallet
2188/// balance would be consumed by fees, rather than proposing a transaction that delivers
2189/// nothing to the recipient.
2190pub fn send_max_fails_when_balance_is_consumed_by_fees<T: ShieldedPoolTester>(
2191    dsf: impl DataStoreFactory,
2192    cache: impl TestCache,
2193) {
2194    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
2195
2196    // Add funds equal to the exact fee of a send-max transaction spending a single note
2197    // to a same-pool recipient (two logical actions under ZIP 317).
2198    let account = st.test_account().cloned().unwrap();
2199    let value = minimum_fee(st.network(), account.birthday().height() + 1);
2200    st.add_a_single_note_checking_balance(value);
2201
2202    let to: Address = T::sk_default_address(&T::sk(&[0xf5; 32]));
2203    let fee_rule = StandardFeeRule::Zip317;
2204
2205    let addy = to.to_zcash_address(st.network());
2206    assert_matches!(
2207        st.propose_send_max_transfer(
2208            account.id(),
2209            &fee_rule,
2210            addy,
2211            None,
2212            MaxSpendMode::Everything,
2213            ConfirmationsPolicy::MIN,
2214        ),
2215        Err(data_api::error::Error::InsufficientFunds { available, required })
2216            if available == value && required > value
2217    );
2218}
2219
2220/// Tests that attempting to send all the spendable funds within the given shielded pool in a
2221/// single transaction fail if there are funds that are not yet confirmed.
2222///
2223/// The test:
2224/// - Adds funds to the wallet in a single note.
2225/// - Checks that the wallet balances are correct.
2226/// - Mine empty blocks
2227/// - Add more funds
2228/// - Attempts to construct a request to spend the whole balance to an external address in the
2229///   same pool.
2230/// - catches failure
2231/// - verifies the failure is the one expected
2232pub fn spend_everything_proposal_fails_when_unconfirmed_funds_present<T: ShieldedPoolTester>(
2233    dsf: impl DataStoreFactory,
2234    cache: impl TestCache,
2235) {
2236    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
2237    st.add_notes_checking_balance([
2238        Some(Zatoshis::const_from_u64(60000)),
2239        None,
2240        None,
2241        Some(Zatoshis::const_from_u64(123456)),
2242    ]);
2243
2244    // Spendable balance doesn't match total balance
2245    let account = st.test_account().cloned().unwrap();
2246    let total_balance = st.get_total_balance(account.id());
2247    let spendable_balance = st.get_spendable_balance(
2248        account.id(),
2249        ConfirmationsPolicy::new_symmetrical_unchecked(
2250            2,
2251            #[cfg(feature = "transparent-inputs")]
2252            true,
2253        ),
2254    );
2255    assert_ne!(total_balance, spendable_balance);
2256
2257    let to_extsk = T::sk(&[0xf5; 32]);
2258    let to: Address = T::sk_default_address(&to_extsk);
2259
2260    let fee_rule = StandardFeeRule::Zip317;
2261
2262    let send_max_memo = "Test Send Max memo".parse::<Memo>().unwrap();
2263
2264    let addy = to.to_zcash_address(st.network());
2265    assert_matches!(
2266        st.propose_send_max_transfer(
2267            account.id(),
2268            &fee_rule,
2269            addy,
2270            Some(MemoBytes::from(send_max_memo.clone())),
2271            MaxSpendMode::Everything,
2272            ConfirmationsPolicy::new_symmetrical_unchecked(
2273                2,
2274                #[cfg(feature = "transparent-inputs")]
2275                true
2276            )
2277        ),
2278        Err(data_api::error::Error::DataSource(_))
2279    );
2280}
2281
2282/// Tests that attempting to send `MaxSpendable` funds within the given shielded pool in a
2283/// single transaction succeeds if there are funds that are not yet confirmed.
2284///
2285/// The test:
2286/// - Adds funds to the wallet in a single note.
2287/// - Checks that the wallet balances are correct.
2288/// - Mine empty blocks
2289/// - Add more funds
2290/// - Attempts to construct a request to spend the whole balance to an external address in the
2291///   same pool.
2292/// - succeeds at doing so
2293pub fn send_max_spendable_proposal_succeeds_when_unconfirmed_funds_present<
2294    T: ShieldedPoolTester,
2295>(
2296    dsf: impl DataStoreFactory,
2297    cache: impl TestCache,
2298) {
2299    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
2300    let h = st
2301        .add_notes_checking_balance([
2302            Some(Zatoshis::const_from_u64(60000)),
2303            None,
2304            None,
2305            Some(Zatoshis::const_from_u64(123456)),
2306        ])
2307        .block_height()
2308        .unwrap();
2309
2310    // Spendable balance doesn't match total balance
2311    let account = st.test_account().cloned().unwrap();
2312    let total_balance = st.get_total_balance(account.id());
2313    let spendable_balance = st.get_spendable_balance(
2314        account.id(),
2315        ConfirmationsPolicy::new_symmetrical_unchecked(
2316            2,
2317            #[cfg(feature = "transparent-inputs")]
2318            true,
2319        ),
2320    );
2321    assert_ne!(total_balance, spendable_balance);
2322
2323    let to_extsk = T::sk(&[0xf5; 32]);
2324    let to: Address = T::sk_default_address(&to_extsk);
2325
2326    let fee_rule = StandardFeeRule::Zip317;
2327
2328    let send_max_memo = "Test Send Max memo".parse::<Memo>().unwrap();
2329
2330    let addy = to.to_zcash_address(st.network());
2331    let proposal = st
2332        .propose_send_max_transfer(
2333            account.id(),
2334            &fee_rule,
2335            addy,
2336            Some(MemoBytes::from(send_max_memo.clone())),
2337            MaxSpendMode::MaxSpendable,
2338            ConfirmationsPolicy::new_symmetrical_unchecked(
2339                2,
2340                #[cfg(feature = "transparent-inputs")]
2341                true,
2342            ),
2343        )
2344        .unwrap();
2345
2346    let sent_tx_id = st.create_proposed_expecting(&proposal, 1)[0];
2347
2348    // Verify that the sent transaction was stored and that we can decrypt the memos
2349    let tx = st
2350        .wallet()
2351        .get_transaction(sent_tx_id)
2352        .unwrap()
2353        .expect("Created transaction was stored.");
2354    let ufvks = [(account.id(), account.usk().to_unified_full_viewing_key())]
2355        .into_iter()
2356        .collect();
2357    let d_tx = decrypt_transaction(st.network(), None, Some(h), &tx, &ufvks);
2358    assert_eq!(T::decrypted_pool_outputs_count(&d_tx), 1);
2359
2360    let mut found_send_max_memo = false;
2361    let mut found_tx_empty_memo = false;
2362    T::with_decrypted_pool_memos(&d_tx, |memo| {
2363        if Memo::try_from(memo).unwrap() == send_max_memo {
2364            found_send_max_memo = true
2365        }
2366        if Memo::try_from(memo).unwrap() == Memo::Empty {
2367            found_tx_empty_memo = true
2368        }
2369    });
2370    assert!(found_send_max_memo);
2371    assert!(!found_tx_empty_memo); // there's no empty memo in this case
2372
2373    // Verify that the stored sent notes match what we're expecting
2374    let sent_note_ids = st
2375        .wallet()
2376        .get_sent_note_ids(&sent_tx_id, T::SHIELDED_PROTOCOL)
2377        .unwrap();
2378    assert_eq!(sent_note_ids.len(), 1);
2379
2380    // The sent memo should the specified memo for the sent output
2381    let mut found_sent_empty_memo = false;
2382    let mut found_sent_max_memo = false;
2383    for sent_note_id in sent_note_ids {
2384        match st
2385            .wallet()
2386            .get_memo(sent_note_id)
2387            .expect("Memo retrieval should succeed")
2388            .as_ref()
2389        {
2390            Some(m) if m == &Memo::Empty => {
2391                found_sent_empty_memo = true;
2392            }
2393            Some(m) if m == &send_max_memo => {
2394                found_sent_max_memo = true;
2395            }
2396            Some(other) => panic!("Unexpected memo value: {other:?}"),
2397            None => panic!("Memo should not be stored as NULL"),
2398        }
2399    }
2400
2401    assert!(found_sent_max_memo);
2402    assert!(!found_sent_empty_memo);
2403
2404    // Check that querying for a nonexistent sent note returns None
2405    assert_matches!(
2406        st.wallet()
2407            .get_memo(NoteId::new(sent_tx_id, T::SHIELDED_PROTOCOL, 12345)),
2408        Ok(None)
2409    );
2410
2411    let tx_history = st.wallet().get_tx_history().unwrap();
2412    assert_eq!(tx_history.len(), 2);
2413    {
2414        let tx_0 = &tx_history[0];
2415        assert_eq!(tx_0.total_spent(), Zatoshis::const_from_u64(0));
2416        assert_eq!(tx_0.total_received(), Zatoshis::const_from_u64(60000));
2417    }
2418
2419    {
2420        let tx_1 = &tx_history[1];
2421        assert_eq!(tx_1.total_spent(), Zatoshis::const_from_u64(60000));
2422        assert_eq!(tx_1.total_received(), Zatoshis::const_from_u64(0));
2423    }
2424
2425    let network = *st.network();
2426    assert_matches!(
2427        decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, None),
2428        Ok(_)
2429    );
2430}
2431
2432/// This test attempts to send the max spendable funds to a TEX address recipient
2433/// checks that the transactions were stored and that the amounts involved are correct
2434#[cfg(feature = "transparent-inputs")]
2435pub fn spend_everything_multi_step_single_note_proposed_transfer<T: ShieldedPoolTester, Dsf>(
2436    ds_factory: Dsf,
2437    cache: impl TestCache,
2438) where
2439    Dsf: DataStoreFactory,
2440    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
2441{
2442    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache)
2443        .map(|builder| builder.with_gap_limits(GapLimits::new(10, 5, 3)))
2444        .build::<T>();
2445
2446    let account = st.test_account().cloned().unwrap();
2447    let account_id = account.id();
2448
2449    let value = Zatoshis::const_from_u64(100000);
2450
2451    // Add funds to the wallet.
2452    st.add_a_single_note_checking_balance(value);
2453    let initial_balance = value;
2454    assert_eq!(
2455        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
2456        initial_balance
2457    );
2458
2459    let expected_step0_fee = (marginal_fee_at_target(&st) * 3u64).unwrap();
2460    let expected_step1_fee = minimum_fee_at_target(&st);
2461    let expected_ephemeral_spend = (value - expected_step0_fee - expected_step1_fee).unwrap();
2462    let expected_ephemeral_balance = (value - expected_step0_fee).unwrap();
2463    let expected_step0_change = (value - expected_step0_fee).unwrap();
2464
2465    let total_sent = (expected_step0_fee + expected_step1_fee + expected_ephemeral_spend).unwrap();
2466
2467    // check that the napkin math is Ok. Total value send should be the whole
2468    // value of the wallet
2469    assert_eq!(total_sent, value);
2470
2471    // Generate a ZIP 320 proposal, sending to an external TEX address.
2472    let tex_addr = Address::Tex([0x4; 20]);
2473
2474    // TODO: Do we want to allow shielded change memos in ephemeral transfers?
2475    //let change_memo = Memo::from_str("change").expect("valid memo").encode();
2476    let fee_rule = StandardFeeRule::Zip317;
2477
2478    // We use `st.propose_standard_transfer` here in order to also test round-trip
2479    // serialization of the proposal.
2480    let addy = tex_addr.to_zcash_address(st.network());
2481    let proposal = st
2482        .propose_send_max_transfer(
2483            account_id,
2484            &fee_rule,
2485            addy,
2486            None,
2487            MaxSpendMode::Everything,
2488            ConfirmationsPolicy::MIN,
2489        )
2490        .unwrap();
2491
2492    let steps: Vec<_> = proposal.steps().iter().cloned().collect();
2493    assert_eq!(steps.len(), 2);
2494
2495    assert_eq!(steps[0].balance().fee_required(), expected_step0_fee);
2496    assert_eq!(steps[1].balance().fee_required(), expected_step1_fee);
2497    assert_eq!(
2498        steps[0].balance().proposed_change(),
2499        [
2500            // TODO: Do we want to allow shielded change memos in ephemeral transfers?
2501            //ChangeValue::shielded(
2502            //    T::SHIELDED_PROTOCOL,
2503            //    expected_step0_change,
2504            //    Some(change_memo)
2505            //),
2506            ChangeValue::ephemeral_transparent(
2507                (total_sent - expected_step0_fee).expect("value is non-zero")
2508            ),
2509        ]
2510    );
2511    assert_eq!(steps[1].balance().proposed_change(), []);
2512
2513    let txids = st.create_proposed_expecting(&proposal, 2);
2514
2515    // Mine the created transactions.
2516    for txid in txids.iter() {
2517        let (h, _) = st.generate_next_block_including(*txid);
2518        st.scan_cached_blocks(h, 1);
2519    }
2520
2521    // Check that there are sent outputs with the correct values.
2522    let confirmed_sent: Vec<Vec<_>> = txids
2523        .iter()
2524        .map(|sent_txid| st.wallet().get_sent_outputs(sent_txid).unwrap())
2525        .collect();
2526
2527    // Verify that a status request has been generated for the second transaction of
2528    // the ZIP 320 pair.
2529    let tx_data_requests = st.wallet().transaction_data_requests().unwrap();
2530    assert!(tx_data_requests.contains(&TransactionDataRequest::GetStatus(*txids.last())));
2531
2532    assert!(expected_step0_change > expected_ephemeral_spend);
2533    assert_eq!(confirmed_sent.len(), 2);
2534    assert_eq!(confirmed_sent[0].len(), 1);
2535    assert_eq!(confirmed_sent[0][0].value, expected_step0_change);
2536    let OutputOfSentTx {
2537        value: ephemeral_v, ..
2538    } = confirmed_sent[0][0].clone();
2539    assert_eq!(ephemeral_v, expected_ephemeral_balance);
2540
2541    assert_eq!(confirmed_sent[1].len(), 1);
2542    assert_matches!(
2543            &confirmed_sent[1][0],
2544            OutputOfSentTx { value: sent_v, external_recipient: sent_to_addr, ephemeral_address: None }
2545            if sent_v == &expected_ephemeral_spend && sent_to_addr == &Some(tex_addr));
2546
2547    // Check that the transaction history matches what we expect.
2548    let tx_history = st.wallet().get_tx_history().unwrap();
2549
2550    let tx_0 = tx_history
2551        .iter()
2552        .find(|tx| tx.txid() == *txids.first())
2553        .unwrap();
2554    let tx_1 = tx_history
2555        .iter()
2556        .find(|tx| tx.txid() == *txids.last())
2557        .unwrap();
2558
2559    assert_eq!(tx_0.account_id(), &account_id);
2560    assert!(!tx_0.expired_unmined());
2561    assert_eq!(tx_0.has_change(), expected_step0_change.is_zero());
2562    assert!(!tx_0.is_shielding());
2563    assert_eq!(
2564        tx_0.account_value_delta(),
2565        -ZatBalance::from(expected_step0_fee),
2566    );
2567
2568    assert_eq!(tx_1.account_id(), &account_id);
2569    assert!(!tx_1.expired_unmined());
2570    assert!(!tx_1.has_change());
2571    assert!(!tx_0.is_shielding());
2572    assert_eq!(
2573        tx_1.account_value_delta(),
2574        -ZatBalance::from(expected_ephemeral_balance),
2575    );
2576
2577    let ending_balance = st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN);
2578    assert_eq!(initial_balance - total_sent, ending_balance.into());
2579}
2580
2581/// This test attempts to send the max spendable funds to a TEX address recipient
2582/// checks that the transactions were stored and that the amounts involved are correct
2583#[cfg(feature = "transparent-inputs")]
2584pub fn spend_everything_multi_step_many_notes_proposed_transfer<T: ShieldedPoolTester, Dsf>(
2585    ds_factory: Dsf,
2586    cache: impl TestCache,
2587) where
2588    Dsf: DataStoreFactory,
2589    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
2590{
2591    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache)
2592        .map(|builder| builder.with_gap_limits(GapLimits::new(10, 5, 3)))
2593        .build::<T>();
2594
2595    let number_of_notes = 3u64;
2596    let note_value = Zatoshis::const_from_u64(100000);
2597    let value = (note_value * number_of_notes).unwrap();
2598
2599    // Add funds to the wallet.
2600    for _ in 0..number_of_notes {
2601        st.add_a_single_note_checking_balance(note_value);
2602    }
2603
2604    let initial_balance = value;
2605    let account = st.test_account().cloned().unwrap();
2606    let account_id = account.id();
2607    assert_eq!(
2608        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
2609        initial_balance
2610    );
2611
2612    let expected_step0_fee = (marginal_fee_at_target(&st) * 4u64).unwrap();
2613    let expected_step1_fee = minimum_fee_at_target(&st);
2614    let expected_ephemeral_spend = (value - expected_step0_fee - expected_step1_fee).unwrap();
2615    let expected_ephemeral_balance = (value - expected_step0_fee).unwrap();
2616    let expected_step0_change = (value - expected_step0_fee).unwrap();
2617
2618    let total_sent = (expected_step0_fee + expected_step1_fee + expected_ephemeral_spend).unwrap();
2619
2620    // check that the napkin math is Ok. Total value send should be the whole
2621    // value of the wallet
2622    assert_eq!(total_sent, value);
2623
2624    // Generate a ZIP 320 proposal, sending to an external TEX address.
2625    let tex_addr = Address::Tex([0x4; 20]);
2626    let fee_rule = StandardFeeRule::Zip317;
2627
2628    // We use `st.propose_standard_transfer` here in order to also test round-trip
2629    // serialization of the proposal.
2630    let addy = tex_addr.to_zcash_address(st.network());
2631    let proposal = st
2632        .propose_send_max_transfer(
2633            account_id,
2634            &fee_rule,
2635            addy,
2636            None,
2637            MaxSpendMode::Everything,
2638            ConfirmationsPolicy::MIN,
2639        )
2640        .unwrap();
2641
2642    let steps: Vec<_> = proposal.steps().iter().cloned().collect();
2643    assert_eq!(steps.len(), 2);
2644
2645    assert_eq!(steps[0].balance().fee_required(), expected_step0_fee);
2646    assert_eq!(steps[1].balance().fee_required(), expected_step1_fee);
2647    assert_eq!(
2648        steps[0].balance().proposed_change(),
2649        [ChangeValue::ephemeral_transparent(
2650            (total_sent - expected_step0_fee).expect("value is non-zero")
2651        ),]
2652    );
2653    assert_eq!(steps[1].balance().proposed_change(), []);
2654
2655    let txids = st.create_proposed_expecting(&proposal, 2);
2656
2657    // Mine the created transactions.
2658    for txid in txids.iter() {
2659        let (h, _) = st.generate_next_block_including(*txid);
2660        st.scan_cached_blocks(h, 1);
2661    }
2662
2663    // Check that there are sent outputs with the correct values.
2664    let confirmed_sent: Vec<Vec<_>> = txids
2665        .iter()
2666        .map(|sent_txid| st.wallet().get_sent_outputs(sent_txid).unwrap())
2667        .collect();
2668
2669    // Verify that a status request has been generated for the second transaction of
2670    // the ZIP 320 pair.
2671    let tx_data_requests = st.wallet().transaction_data_requests().unwrap();
2672    assert!(tx_data_requests.contains(&TransactionDataRequest::GetStatus(*txids.last())));
2673
2674    assert!(expected_step0_change > expected_ephemeral_spend);
2675    assert_eq!(confirmed_sent.len(), 2);
2676    assert_eq!(confirmed_sent[0].len(), 1);
2677    assert_eq!(confirmed_sent[0][0].value, expected_step0_change);
2678    let OutputOfSentTx {
2679        value: ephemeral_v, ..
2680    } = confirmed_sent[0][0].clone();
2681    assert_eq!(ephemeral_v, expected_ephemeral_balance);
2682
2683    assert_eq!(confirmed_sent[1].len(), 1);
2684    assert_matches!(
2685            &confirmed_sent[1][0],
2686            OutputOfSentTx { value: sent_v, external_recipient: sent_to_addr, ephemeral_address: None }
2687            if sent_v == &expected_ephemeral_spend && sent_to_addr == &Some(tex_addr));
2688
2689    // Check that the transaction history matches what we expect.
2690    let tx_history = st.wallet().get_tx_history().unwrap();
2691
2692    let tx_0 = tx_history
2693        .iter()
2694        .find(|tx| tx.txid() == *txids.first())
2695        .unwrap();
2696    let tx_1 = tx_history
2697        .iter()
2698        .find(|tx| tx.txid() == *txids.last())
2699        .unwrap();
2700
2701    assert_eq!(tx_0.account_id(), &account_id);
2702    assert!(!tx_0.expired_unmined());
2703    assert_eq!(tx_0.has_change(), expected_step0_change.is_zero());
2704    assert!(!tx_0.is_shielding());
2705    assert_eq!(
2706        tx_0.account_value_delta(),
2707        -ZatBalance::from(expected_step0_fee),
2708    );
2709
2710    assert_eq!(tx_1.account_id(), &account_id);
2711    assert!(!tx_1.expired_unmined());
2712    assert!(!tx_1.has_change());
2713    assert!(!tx_0.is_shielding());
2714    assert_eq!(
2715        tx_1.account_value_delta(),
2716        -ZatBalance::from(expected_ephemeral_balance),
2717    );
2718
2719    let ending_balance = st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN);
2720    assert_eq!(initial_balance - total_sent, ending_balance.into());
2721}
2722
2723/// This test attempts to send the max spendable funds to a TEX address recipient.
2724/// The wallet contains many notes denominated with the marginal fee value.
2725/// Checks that the transactions were stored and that the amounts involved are correct
2726#[cfg(feature = "transparent-inputs")]
2727pub fn spend_everything_multi_step_with_marginal_notes_proposed_transfer<
2728    T: ShieldedPoolTester,
2729    Dsf,
2730>(
2731    ds_factory: Dsf,
2732    cache: impl TestCache,
2733) where
2734    Dsf: DataStoreFactory,
2735    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
2736{
2737    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache)
2738        .map(|builder| builder.with_gap_limits(GapLimits::new(10, 5, 3)))
2739        .build::<T>();
2740
2741    let number_of_notes = 10u64;
2742    let note_value = Zatoshis::const_from_u64(100000);
2743    let non_marginal_notes_value =
2744        (note_value * number_of_notes).expect("sum of notes should not fail.");
2745
2746    for _ in 0..number_of_notes {
2747        st.add_a_single_note_checking_balance(note_value);
2748        let marginal_fee = marginal_fee_at_target(&st);
2749        st.add_a_single_note_checking_balance(marginal_fee);
2750    }
2751
2752    let account = st.test_account().cloned().unwrap();
2753    let account_id = account.id();
2754    assert_eq!(
2755        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
2756        non_marginal_notes_value
2757    );
2758
2759    let expected_step0_fee = (marginal_fee_at_target(&st) * (number_of_notes + 1)).unwrap();
2760    let expected_step1_fee = minimum_fee_at_target(&st);
2761    let expected_ephemeral_spend =
2762        (non_marginal_notes_value - expected_step0_fee - expected_step1_fee).unwrap();
2763    let expected_ephemeral_balance = (non_marginal_notes_value - expected_step0_fee).unwrap();
2764    let expected_step0_change = (non_marginal_notes_value - expected_step0_fee).unwrap();
2765
2766    let total_sent = (expected_step0_fee + expected_step1_fee + expected_ephemeral_spend).unwrap();
2767
2768    // check that the napkin math is Ok. Total value send should be the whole
2769    // value of the wallet
2770    assert_eq!(total_sent, non_marginal_notes_value);
2771
2772    // Generate a ZIP 320 proposal, sending to an external TEX address.
2773    let tex_addr = Address::Tex([0x4; 20]);
2774
2775    let fee_rule = StandardFeeRule::Zip317;
2776
2777    // We use `st.propose_standard_transfer` here in order to also test round-trip
2778    // serialization of the proposal.
2779    let addy = tex_addr.to_zcash_address(st.network());
2780    let proposal = st
2781        .propose_send_max_transfer(
2782            account_id,
2783            &fee_rule,
2784            addy,
2785            None,
2786            MaxSpendMode::Everything,
2787            ConfirmationsPolicy::MIN,
2788        )
2789        .unwrap();
2790
2791    let steps: Vec<_> = proposal.steps().iter().cloned().collect();
2792    assert_eq!(steps.len(), 2);
2793
2794    assert_eq!(
2795        steps[0].shielded_inputs().unwrap().notes().len() as u64,
2796        number_of_notes
2797    );
2798    assert_eq!(steps[0].balance().fee_required(), expected_step0_fee);
2799    assert_eq!(steps[1].balance().fee_required(), expected_step1_fee);
2800    assert_eq!(
2801        steps[0].balance().proposed_change(),
2802        [ChangeValue::ephemeral_transparent(
2803            (total_sent - expected_step0_fee).expect("value is non-zero")
2804        ),]
2805    );
2806    assert_eq!(steps[1].balance().proposed_change(), []);
2807
2808    let txids = st.create_proposed_expecting(&proposal, 2);
2809
2810    // Mine the created transactions.
2811    for txid in txids.iter() {
2812        let (h, _) = st.generate_next_block_including(*txid);
2813        st.scan_cached_blocks(h, 1);
2814    }
2815
2816    // Check that there are sent outputs with the correct values.
2817    let confirmed_sent: Vec<Vec<_>> = txids
2818        .iter()
2819        .map(|sent_txid| st.wallet().get_sent_outputs(sent_txid).unwrap())
2820        .collect();
2821
2822    // Verify that a status request has been generated for the second transaction of
2823    // the ZIP 320 pair.
2824    let tx_data_requests = st.wallet().transaction_data_requests().unwrap();
2825    assert!(tx_data_requests.contains(&TransactionDataRequest::GetStatus(*txids.last())));
2826
2827    assert!(expected_step0_change > expected_ephemeral_spend);
2828    assert_eq!(confirmed_sent.len(), 2);
2829    assert_eq!(confirmed_sent[0].len(), 1);
2830    assert_eq!(confirmed_sent[0][0].value, expected_step0_change);
2831    let OutputOfSentTx {
2832        value: ephemeral_v, ..
2833    } = confirmed_sent[0][0].clone();
2834    assert_eq!(ephemeral_v, expected_ephemeral_balance);
2835
2836    assert_eq!(confirmed_sent[1].len(), 1);
2837    assert_matches!(
2838            &confirmed_sent[1][0],
2839            OutputOfSentTx { value: sent_v, external_recipient: sent_to_addr, ephemeral_address: None }
2840            if sent_v == &expected_ephemeral_spend && sent_to_addr == &Some(tex_addr));
2841
2842    // Check that the transaction history matches what we expect.
2843    let tx_history = st.wallet().get_tx_history().unwrap();
2844
2845    let tx_0 = tx_history
2846        .iter()
2847        .find(|tx| tx.txid() == *txids.first())
2848        .unwrap();
2849    let tx_1 = tx_history
2850        .iter()
2851        .find(|tx| tx.txid() == *txids.last())
2852        .unwrap();
2853
2854    assert_eq!(tx_0.account_id(), &account_id);
2855    assert!(!tx_0.expired_unmined());
2856    assert_eq!(tx_0.has_change(), expected_step0_change.is_zero());
2857    assert!(!tx_0.is_shielding());
2858    assert_eq!(
2859        tx_0.account_value_delta(),
2860        -ZatBalance::from(expected_step0_fee),
2861    );
2862
2863    assert_eq!(tx_1.account_id(), &account_id);
2864    assert!(!tx_1.expired_unmined());
2865    assert!(!tx_1.has_change());
2866    assert!(!tx_0.is_shielding());
2867    assert_eq!(
2868        tx_1.account_value_delta(),
2869        -ZatBalance::from(expected_ephemeral_balance),
2870    );
2871
2872    let ending_balance = st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN);
2873    assert_eq!(ending_balance, Zatoshis::ZERO); // ending balance should be zero
2874}
2875
2876/// Tests that the `InsufficientFunds` error of a transfer permitted to spend the account's
2877/// transparent outputs reports the value of those outputs as available, alongside the notes.
2878///
2879/// The test:
2880/// - Adds a shielded note and a transparent UTXO to the account.
2881/// - Proposes a transfer exceeding their combined value, permitting transparent spends.
2882/// - Verifies that `available` is the sum of the note and the UTXO, and that `required` is
2883///   the payment plus the fee for spending both.
2884#[cfg(feature = "transparent-inputs")]
2885pub fn insufficient_funds_counts_transparent_inputs<T: ShieldedPoolTester>(
2886    dsf: impl DataStoreFactory,
2887    cache: impl TestCache,
2888) {
2889    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
2890
2891    let note_value = Zatoshis::const_from_u64(50_000);
2892    let (h, _, _) = st.add_a_single_note_checking_balance(note_value);
2893
2894    let account = st.test_account().cloned().unwrap();
2895    let uaddr = st
2896        .wallet()
2897        .get_last_generated_address_matching(account.id(), UnifiedAddressRequest::AllAvailableKeys)
2898        .unwrap()
2899        .unwrap();
2900    let taddr = uaddr.transparent().unwrap();
2901
2902    let utxo_value = Zatoshis::const_from_u64(30_000);
2903    let utxo = WalletTransparentOutput::from_parts(
2904        OutPoint::fake(),
2905        TxOut::new(utxo_value, taddr.script().into()),
2906        Some(h),
2907        Some(account.id()),
2908        Some(TransparentKeyScope::EXTERNAL),
2909        None,
2910    )
2911    .unwrap();
2912    st.wallet_mut()
2913        .put_received_transparent_utxo(&utxo)
2914        .unwrap();
2915
2916    let to: Address = T::sk_default_address(&T::sk(&[0xf5; 32]));
2917    let amount = Zatoshis::const_from_u64(100_000);
2918    let request = TransactionRequest::new(vec![Payment::without_memo(
2919        to.to_zcash_address(st.network()),
2920        amount,
2921    )])
2922    .unwrap();
2923
2924    let input_selector = GreedyInputSelector::new();
2925    let change_strategy =
2926        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
2927
2928    // The transaction would spend the transparent input and the note, paying the recipient
2929    // and a change output in the note's pool: one transparent logical action plus two
2930    // shielded ones.
2931    let expected_required = (amount + (marginal_fee_at_target(&st) * 3u64).unwrap()).unwrap();
2932    let expected_available = (note_value + utxo_value).unwrap();
2933
2934    assert_matches!(
2935        st.propose_transfer_with_policy(
2936            account.id(),
2937            &input_selector,
2938            &change_strategy,
2939            request,
2940            ConfirmationsPolicy::MIN,
2941            &SpendPolicy::default().with_transparent(TransparentSpendPolicy::any_account_addr()),
2942        ),
2943        Err(Error::InsufficientFunds { available, required })
2944            if available == expected_available && required == expected_required
2945    );
2946}
2947
2948pub fn send_with_multiple_change_outputs<T: ShieldedPoolTester>(
2949    dsf: impl DataStoreFactory,
2950    cache: impl TestCache,
2951) {
2952    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
2953
2954    // Add funds to the wallet in a single note
2955    let value = Zatoshis::const_from_u64(650_0000);
2956    let (h, _, _) = st.add_a_single_note_checking_balance(value);
2957
2958    let to_extsk = T::sk(&[0xf5; 32]);
2959    let to: Address = T::sk_default_address(&to_extsk);
2960    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
2961        to.to_zcash_address(st.network()),
2962        Zatoshis::const_from_u64(100_0000),
2963    )])
2964    .unwrap();
2965
2966    let input_selector = GreedyInputSelector::new();
2967    let change_memo = "Test change memo".parse::<Memo>().unwrap();
2968    let change_strategy = fees::zip317::MultiOutputChangeStrategy::new(
2969        Zip317FeeRule::standard(),
2970        Some(change_memo.clone().into()),
2971        T::SHIELDED_PROTOCOL,
2972        DustOutputPolicy::default(),
2973        SplitPolicy::with_min_output_value(
2974            NonZeroUsize::new(2).unwrap(),
2975            Zatoshis::const_from_u64(100_0000),
2976        ),
2977    );
2978
2979    let account = st.test_account().cloned().unwrap();
2980    let proposal = st
2981        .propose_transfer(
2982            account.id(),
2983            &input_selector,
2984            &change_strategy,
2985            request.clone(),
2986            ConfirmationsPolicy::MIN,
2987        )
2988        .unwrap();
2989
2990    let step = &proposal.steps().head;
2991    assert_eq!(step.balance().proposed_change().len(), 2);
2992
2993    let create_proposed_result = st.create_proposed_transactions::<Infallible, _, Infallible, _>(
2994        account.usk(),
2995        OvkPolicy::Sender,
2996        &proposal,
2997    );
2998    assert_matches!(&create_proposed_result, Ok(txids) if txids.len() == 1);
2999
3000    let sent_tx_id = create_proposed_result.unwrap()[0];
3001
3002    // Verify that the sent transaction was stored and that we can decrypt the memos
3003    let tx = st
3004        .wallet()
3005        .get_transaction(sent_tx_id)
3006        .unwrap()
3007        .expect("Created transaction was stored.");
3008    let ufvks = [(account.id(), account.usk().to_unified_full_viewing_key())]
3009        .into_iter()
3010        .collect();
3011    let d_tx = decrypt_transaction(st.network(), None, Some(h), &tx, &ufvks);
3012    assert_eq!(T::decrypted_pool_outputs_count(&d_tx), 3);
3013
3014    let mut found_tx_change_memo = false;
3015    let mut found_tx_empty_memo = false;
3016    T::with_decrypted_pool_memos(&d_tx, |memo| {
3017        if Memo::try_from(memo).unwrap() == change_memo {
3018            found_tx_change_memo = true
3019        }
3020        if Memo::try_from(memo).unwrap() == Memo::Empty {
3021            found_tx_empty_memo = true
3022        }
3023    });
3024    assert!(found_tx_change_memo);
3025    assert!(found_tx_empty_memo);
3026
3027    // Verify that the stored sent notes match what we're expecting
3028    let sent_note_ids = st
3029        .wallet()
3030        .get_sent_note_ids(&sent_tx_id, T::SHIELDED_PROTOCOL)
3031        .unwrap();
3032    assert_eq!(sent_note_ids.len(), 3);
3033
3034    // The sent memo should be the empty memo for the sent output, and each
3035    // change output's memo should be as specified.
3036    let mut change_memo_count = 0;
3037    let mut found_sent_empty_memo = false;
3038    for sent_note_id in sent_note_ids {
3039        match st
3040            .wallet()
3041            .get_memo(sent_note_id)
3042            .expect("Note id is valid")
3043            .as_ref()
3044        {
3045            Some(m) if m == &change_memo => {
3046                change_memo_count += 1;
3047            }
3048            Some(m) if m == &Memo::Empty => {
3049                found_sent_empty_memo = true;
3050            }
3051            Some(other) => panic!("Unexpected memo value: {other:?}"),
3052            None => panic!("Memo should not be stored as NULL"),
3053        }
3054    }
3055    assert_eq!(change_memo_count, 2);
3056    assert!(found_sent_empty_memo);
3057
3058    let tx_history = st.wallet().get_tx_history().unwrap();
3059    assert_eq!(tx_history.len(), 2);
3060    {
3061        let tx_0 = &tx_history[0];
3062        assert_eq!(tx_0.total_spent(), Zatoshis::const_from_u64(0));
3063        assert_eq!(tx_0.total_received(), Zatoshis::const_from_u64(650_0000));
3064    }
3065
3066    {
3067        let tx_1 = &tx_history[1];
3068        assert_eq!(tx_1.total_spent(), Zatoshis::const_from_u64(650_0000));
3069        assert_eq!(tx_1.total_received(), Zatoshis::const_from_u64(548_5000));
3070        assert_eq!(tx_1.fee_paid(), Some(Zatoshis::const_from_u64(15000)));
3071    }
3072
3073    let network = *st.network();
3074    assert_matches!(
3075        decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, None),
3076        Ok(_)
3077    );
3078
3079    let (h, _) = st.generate_next_block_including(sent_tx_id);
3080    st.scan_cached_blocks(h, 1);
3081
3082    // Now, create another proposal with more outputs requested. We have two change notes;
3083    // we'll spend one of them, and then we'll generate 7 splits.
3084    let change_strategy = fees::zip317::MultiOutputChangeStrategy::new(
3085        Zip317FeeRule::standard(),
3086        Some(change_memo.into()),
3087        T::SHIELDED_PROTOCOL,
3088        DustOutputPolicy::default(),
3089        SplitPolicy::with_min_output_value(
3090            NonZeroUsize::new(8).unwrap(),
3091            Zatoshis::const_from_u64(10_0000),
3092        ),
3093    );
3094
3095    let proposal = st
3096        .propose_transfer(
3097            account.id(),
3098            &input_selector,
3099            &change_strategy,
3100            request,
3101            ConfirmationsPolicy::MIN,
3102        )
3103        .unwrap();
3104
3105    let step = &proposal.steps().head;
3106    assert_eq!(step.balance().proposed_change().len(), 7);
3107}
3108
3109#[cfg(feature = "transparent-inputs")]
3110pub fn send_multi_step_proposed_transfer<T: ShieldedPoolTester, Dsf>(
3111    ds_factory: Dsf,
3112    cache: impl TestCache,
3113    is_reached_gap_limit: impl Fn(&<Dsf::DataStore as WalletRead>::Error, Dsf::AccountId, u32) -> bool,
3114) where
3115    Dsf: DataStoreFactory,
3116{
3117    let gap_limits = GapLimits::new(10, 5, 3);
3118    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache)
3119        .map(|builder| builder.with_gap_limits(gap_limits))
3120        .build::<T>();
3121
3122    let account = st.test_account().cloned().unwrap();
3123    let account_id = account.id();
3124    let dfvk = T::test_account_fvk(&st);
3125    let tex_addr = Address::Tex([0x4; 20]);
3126
3127    let add_funds = |st: &mut TestState<_, Dsf::DataStore, _>, value| {
3128        let (h, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
3129        st.scan_cached_blocks(h, 1);
3130
3131        assert_eq!(
3132            st.wallet()
3133                .block_max_scanned()
3134                .unwrap()
3135                .unwrap()
3136                .block_height(),
3137            h
3138        );
3139        h
3140    };
3141
3142    let value = Zatoshis::const_from_u64(100000);
3143    let transfer_amount = Zatoshis::const_from_u64(50000);
3144
3145    let run_test = |st: &mut TestState<_, Dsf::DataStore, _>, expected_index, prior_balance| {
3146        // Add funds to the wallet.
3147        add_funds(st, value);
3148        let initial_balance: Option<Zatoshis> = prior_balance + value;
3149        assert_eq!(
3150            st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
3151            initial_balance.unwrap()
3152        );
3153
3154        let expected_step0_fee = (marginal_fee_at_target(st) * 3u64).unwrap();
3155        let expected_step1_fee = minimum_fee_at_target(st);
3156        let expected_ephemeral = (transfer_amount + expected_step1_fee).unwrap();
3157        let expected_step0_change =
3158            (initial_balance - expected_ephemeral - expected_step0_fee).expect("sufficient funds");
3159        assert!(expected_step0_change.is_positive());
3160
3161        let total_sent = (expected_step0_fee + expected_step1_fee + transfer_amount).unwrap();
3162
3163        // Generate a ZIP 320 proposal, sending to another wallet's default transparent address
3164        // expressed as a TEX address.
3165        let change_memo = Some(Memo::from_str("change").expect("valid memo").encode());
3166
3167        // We use `st.propose_standard_transfer` here in order to also test round-trip
3168        // serialization of the proposal.
3169        let proposal = st
3170            .propose_standard_transfer::<Infallible>(
3171                account_id,
3172                StandardFeeRule::Zip317,
3173                ConfirmationsPolicy::MIN,
3174                &tex_addr,
3175                transfer_amount,
3176                None,
3177                change_memo.clone(),
3178                T::SHIELDED_PROTOCOL,
3179            )
3180            .unwrap();
3181
3182        let steps: Vec<_> = proposal.steps().iter().cloned().collect();
3183        assert_eq!(steps.len(), 2);
3184
3185        assert_eq!(steps[0].balance().fee_required(), expected_step0_fee);
3186        assert_eq!(steps[1].balance().fee_required(), expected_step1_fee);
3187        assert_eq!(
3188            steps[0].balance().proposed_change(),
3189            [
3190                ChangeValue::shielded(T::SHIELDED_PROTOCOL, expected_step0_change, change_memo),
3191                ChangeValue::ephemeral_transparent(expected_ephemeral),
3192            ]
3193        );
3194        assert_eq!(steps[1].balance().proposed_change(), []);
3195
3196        // There should be no ephemeral addresses exposed at the current chain height
3197        let exposed_at_tip = st
3198            .wallet()
3199            .get_ephemeral_transparent_receivers(account.account().id(), 1, false)
3200            .unwrap();
3201        assert_eq!(exposed_at_tip.len(), 0);
3202
3203        let create_proposed_result = st
3204            .create_proposed_transactions::<Infallible, _, Infallible, _>(
3205                account.usk(),
3206                OvkPolicy::Sender,
3207                &proposal,
3208            );
3209        assert_matches!(&create_proposed_result, Ok(txids) if txids.len() == 2);
3210        let txids = create_proposed_result.unwrap();
3211
3212        // After creation, there should be a new ephemeral address exposed.
3213        let exposed_at_tip = st
3214            .wallet()
3215            .get_ephemeral_transparent_receivers(account.account().id(), 1, false)
3216            .unwrap();
3217        assert_eq!(exposed_at_tip.len(), 1);
3218        let cur_height = st.wallet().chain_height().unwrap().unwrap();
3219        assert_matches!(
3220            exposed_at_tip.values().next().map(|m0| m0.exposure()),
3221            Some(Exposure::Exposed { at_height, .. }) if at_height == cur_height
3222        );
3223
3224        // There should be no unused transparent receivers in this range
3225        let exposed_at_tip = st
3226            .wallet()
3227            .get_ephemeral_transparent_receivers(account.account().id(), 1, true)
3228            .unwrap();
3229        assert!(exposed_at_tip.is_empty());
3230
3231        // Mine the created transactions.
3232        for txid in txids.iter() {
3233            let (h, _) = st.generate_next_block_including(*txid);
3234            st.scan_cached_blocks(h, 1);
3235        }
3236
3237        // Check that there are sent outputs with the correct values.
3238        let confirmed_sent: Vec<Vec<_>> = txids
3239            .iter()
3240            .map(|sent_txid| st.wallet().get_sent_outputs(sent_txid).unwrap())
3241            .collect();
3242
3243        // Verify that a status request has been generated for the second transaction of
3244        // the ZIP 320 pair.
3245        let tx_data_requests = st.wallet().transaction_data_requests().unwrap();
3246        assert!(tx_data_requests.contains(&TransactionDataRequest::GetStatus(*txids.last())));
3247
3248        assert!(expected_step0_change < expected_ephemeral);
3249        assert_eq!(confirmed_sent.len(), 2);
3250        assert_eq!(confirmed_sent[0].len(), 2);
3251        assert_eq!(confirmed_sent[0][0].value, expected_step0_change);
3252        let OutputOfSentTx {
3253            value: ephemeral_v,
3254            external_recipient: to_addr,
3255            ephemeral_address,
3256        } = confirmed_sent[0][1].clone();
3257        assert_eq!(ephemeral_v, expected_ephemeral);
3258        assert!(to_addr.is_some());
3259        assert_eq!(
3260            ephemeral_address,
3261            to_addr.map(|addr| (
3262                addr,
3263                NonHardenedChildIndex::const_from_index(expected_index)
3264            )),
3265        );
3266
3267        assert_eq!(confirmed_sent[1].len(), 1);
3268        assert_matches!(
3269            &confirmed_sent[1][0],
3270            OutputOfSentTx { value: sent_v, external_recipient: sent_to_addr, ephemeral_address: None }
3271            if sent_v == &transfer_amount && sent_to_addr.as_ref() == Some(&tex_addr));
3272
3273        // Check that the transaction history matches what we expect.
3274        let tx_history = st.wallet().get_tx_history().unwrap();
3275
3276        let tx_0 = tx_history
3277            .iter()
3278            .find(|tx| tx.txid() == *txids.first())
3279            .unwrap();
3280        let tx_1 = tx_history
3281            .iter()
3282            .find(|tx| tx.txid() == *txids.last())
3283            .unwrap();
3284
3285        assert_eq!(tx_0.account_id(), &account_id);
3286        assert!(!tx_0.expired_unmined());
3287        assert_eq!(tx_0.has_change(), expected_step0_change.is_positive());
3288        assert!(!tx_0.is_shielding());
3289        assert_eq!(
3290            tx_0.account_value_delta(),
3291            -ZatBalance::from(expected_step0_fee),
3292        );
3293
3294        assert_eq!(tx_1.account_id(), &account_id);
3295        assert!(!tx_1.expired_unmined());
3296        assert!(!tx_1.has_change());
3297        assert!(!tx_0.is_shielding());
3298        assert_eq!(
3299            tx_1.account_value_delta(),
3300            -ZatBalance::from(expected_ephemeral),
3301        );
3302
3303        let ending_balance = st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN);
3304        assert_eq!(initial_balance - total_sent, ending_balance.into());
3305
3306        (ephemeral_address.unwrap().0, txids, ending_balance)
3307    };
3308
3309    // Each transfer should use a different ephemeral address.
3310    let (ephemeral0, _, bal_0) = run_test(&mut st, 0, Zatoshis::ZERO);
3311    let (ephemeral1, _, _) = run_test(&mut st, 1, bal_0);
3312    assert_ne!(ephemeral0, ephemeral1);
3313
3314    add_funds(&mut st, value);
3315
3316    assert_matches!(
3317        ephemeral0,
3318        Address::Transparent(TransparentAddress::PublicKeyHash(_))
3319    );
3320
3321    // Simulate another wallet sending to an ephemeral address with an index
3322    // within the current gap limit.
3323    let known_addrs = st
3324        .wallet()
3325        .get_known_ephemeral_addresses(account_id, None)
3326        .unwrap();
3327    assert_eq!(
3328        known_addrs.len(),
3329        usize::try_from(gap_limits.ephemeral() + 2).unwrap()
3330    );
3331
3332    // Check that the addresses are all distinct.
3333    let known_set: HashSet<_> = known_addrs.iter().map(|(addr, _)| addr).collect();
3334    assert_eq!(known_set.len(), known_addrs.len());
3335    // Check that the metadata is as expected.
3336    for (i, (_, meta)) in known_addrs.iter().enumerate() {
3337        assert_eq!(
3338            meta.source(),
3339            &TransparentAddressSource::Derived {
3340                scope: TransparentKeyScope::EPHEMERAL,
3341                address_index: NonHardenedChildIndex::from_index(i.try_into().unwrap()).unwrap(),
3342            }
3343        );
3344    }
3345
3346    let (colliding_addr, _) = &known_addrs[usize::try_from(gap_limits.ephemeral() - 1).unwrap()];
3347    let utxo_value = (value - minimum_fee_at_target(&st)).unwrap();
3348    let to = Address::from(*colliding_addr);
3349    let proposal = st.propose_transfer_to(&to, utxo_value);
3350
3351    // Create the transaction. This will cause the the gap start to move & a new
3352    // `gap_limits.ephemeral()` of addresses to be created.
3353    let txids = st
3354        .create_proposed_transactions::<Infallible, _, Infallible, _>(
3355            account.usk(),
3356            OvkPolicy::Sender,
3357            &proposal,
3358        )
3359        .unwrap();
3360
3361    // Mine the transaction & update its status to advance the gap. We have to manually update the
3362    // status because scanning will not detect the transparent outputs.
3363    let (h, _) = st.generate_next_block_including(txids.head);
3364    st.scan_cached_blocks(h, 1);
3365    st.wallet_mut()
3366        .set_transaction_status(txids.head, TransactionStatus::Mined(h))
3367        .unwrap();
3368
3369    // At this point the start of the gap should be at index `gap_limits.ephemeral()` and the new
3370    // size of the known address set should be `gap_limits.ephemeral() * 2`.
3371    let new_known_addrs = st
3372        .wallet()
3373        .get_known_ephemeral_addresses(account_id, None)
3374        .unwrap();
3375    assert_eq!(
3376        new_known_addrs.len(),
3377        usize::try_from(gap_limits.ephemeral() * 2).unwrap()
3378    );
3379
3380    // check that known_addrs is a prefix of new_known_addrs; we have already checked their
3381    // lengths.
3382    assert!(
3383        new_known_addrs
3384            .iter()
3385            .map(|a| a.0)
3386            .zip(known_addrs.iter().map(|a| a.0))
3387            .all(|(a, b)| a == b),
3388        "new_known_addrs must have known_addrs as its prefix"
3389    );
3390
3391    let reservation_should_succeed = |st: &mut TestState<_, Dsf::DataStore, _>, n: u32| {
3392        let reserved = st
3393            .wallet_mut()
3394            .reserve_next_n_ephemeral_addresses(account_id, n.try_into().unwrap())
3395            .unwrap();
3396        assert_eq!(reserved.len(), usize::try_from(n).unwrap());
3397        reserved
3398    };
3399    let reservation_should_fail =
3400        |st: &mut TestState<_, Dsf::DataStore, _>, n: u32, expected_bad_index| {
3401            assert_matches!(st
3402            .wallet_mut()
3403            .reserve_next_n_ephemeral_addresses(account_id, n.try_into().unwrap()),
3404            Err(e) if is_reached_gap_limit(&e, account_id, expected_bad_index));
3405        };
3406
3407    assert_matches!(
3408        known_addrs[usize::try_from(gap_limits.ephemeral()).unwrap()]
3409            .1
3410            .exposure(),
3411        Exposure::Unknown
3412    );
3413
3414    let next_reserved = reservation_should_succeed(&mut st, 1);
3415
3416    // By reserving the address, its exposure has transitioned from "unknown" to "exposed".
3417    let gap_position = 0;
3418    let expected = &known_addrs[usize::try_from(gap_limits.ephemeral()).unwrap()];
3419    let actual = &next_reserved[usize::try_from(gap_position).unwrap()];
3420    assert_eq!(actual.0, expected.0);
3421    assert_eq!(actual.1.source(), expected.1.source());
3422    assert_eq!(expected.1.exposure(), Exposure::Unknown);
3423    assert_eq!(
3424        actual.1.exposure(),
3425        Exposure::Exposed {
3426            at_height: st.latest_block_height.unwrap(),
3427            gap_metadata: crate::wallet::GapMetadata::InGap {
3428                gap_position,
3429                gap_limit: gap_limits.ephemeral(),
3430            }
3431        }
3432    );
3433
3434    // The range of address indices that are safe to reserve now is
3435    // 0..(gap_limits.ephemeral() * 2 - 1)`, and we have already reserved or used
3436    // `gap_limits.ephemeral() + 1`, addresses, so trying to reserve another
3437    // `gap_limits.ephemeral()` should fail.
3438    reservation_should_fail(&mut st, gap_limits.ephemeral(), gap_limits.ephemeral() * 2);
3439    reservation_should_succeed(&mut st, gap_limits.ephemeral() - 1);
3440    // Now we've reserved everything we can, we can't reserve one more
3441    reservation_should_fail(&mut st, 1, gap_limits.ephemeral() * 2);
3442}
3443
3444/// Tests spending all funds within the given shielded pool in a single transaction.
3445///
3446/// The test:
3447/// - Adds funds to the wallet in a single note.
3448/// - Checks that the wallet balances are correct.
3449/// - Constructs a request to spend all of that balance to an external address in the
3450///   same pool.
3451/// - Builds the transaction.
3452/// - Checks that the transaction was stored, and that the outputs are decryptable and
3453///   have the expected details.
3454pub fn spend_all_funds_single_step_proposed_transfer<T: ShieldedPoolTester>(
3455    dsf: impl DataStoreFactory,
3456    cache: impl TestCache,
3457) {
3458    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
3459
3460    // Add funds to the wallet in a single note
3461    let value = Zatoshis::const_from_u64(60000);
3462    let (h, _, _) = st.add_a_single_note_checking_balance(value);
3463
3464    let spend_amount = Zatoshis::const_from_u64(50000);
3465    let to_extsk = T::sk(&[0xf5; 32]);
3466    let to: Address = T::sk_default_address(&to_extsk);
3467    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
3468        to.to_zcash_address(st.network()),
3469        spend_amount,
3470    )])
3471    .unwrap();
3472
3473    let fee_rule = StandardFeeRule::Zip317;
3474
3475    let change_memo = "Test change memo".parse::<Memo>().unwrap();
3476    let change_strategy = standard::SingleOutputChangeStrategy::new(
3477        fee_rule,
3478        Some(change_memo.clone().into()),
3479        T::SHIELDED_PROTOCOL,
3480        DustOutputPolicy::default(),
3481    );
3482    let input_selector = GreedyInputSelector::new();
3483
3484    let account = st.test_account().cloned().unwrap();
3485    let proposal = st
3486        .propose_transfer(
3487            account.id(),
3488            &input_selector,
3489            &change_strategy,
3490            request,
3491            ConfirmationsPolicy::MIN,
3492        )
3493        .unwrap();
3494
3495    let sent_tx_id = st.create_proposed_expecting(&proposal, 1)[0];
3496
3497    // Verify that the sent transaction was stored and that we can decrypt the memos
3498    let tx = st
3499        .wallet()
3500        .get_transaction(sent_tx_id)
3501        .unwrap()
3502        .expect("Created transaction was stored.");
3503    let ufvks = [(account.id(), account.usk().to_unified_full_viewing_key())]
3504        .into_iter()
3505        .collect();
3506    let d_tx = decrypt_transaction(st.network(), None, Some(h), &tx, &ufvks);
3507    assert_eq!(T::decrypted_pool_outputs_count(&d_tx), 2);
3508
3509    let mut found_tx_change_memo = false;
3510    let mut found_tx_empty_memo = false;
3511    T::with_decrypted_pool_memos(&d_tx, |memo| {
3512        if Memo::try_from(memo).unwrap() == change_memo {
3513            found_tx_change_memo = true
3514        }
3515        if Memo::try_from(memo).unwrap() == Memo::Empty {
3516            found_tx_empty_memo = true
3517        }
3518    });
3519    assert!(found_tx_change_memo);
3520    assert!(found_tx_empty_memo);
3521
3522    // Verify that the stored sent notes match what we're expecting
3523    let sent_note_ids = st
3524        .wallet()
3525        .get_sent_note_ids(&sent_tx_id, T::SHIELDED_PROTOCOL)
3526        .unwrap();
3527    assert_eq!(sent_note_ids.len(), 2);
3528
3529    // The sent memo should be the empty memo for the sent output, and the
3530    // change output's memo should be as specified.
3531    let mut found_sent_change_memo = false;
3532    let mut found_sent_empty_memo = false;
3533    for sent_note_id in sent_note_ids {
3534        match st
3535            .wallet()
3536            .get_memo(sent_note_id)
3537            .expect("Note id is valid")
3538            .as_ref()
3539        {
3540            Some(m) if m == &change_memo => {
3541                found_sent_change_memo = true;
3542            }
3543            Some(m) if m == &Memo::Empty => {
3544                found_sent_empty_memo = true;
3545            }
3546            Some(other) => panic!("Unexpected memo value: {other:?}"),
3547            None => panic!("Memo should not be stored as NULL"),
3548        }
3549    }
3550    assert!(found_sent_change_memo);
3551    assert!(found_sent_empty_memo);
3552
3553    // Check that querying for a nonexistent sent note returns None
3554    assert_matches!(
3555        st.wallet()
3556            .get_memo(NoteId::new(sent_tx_id, T::SHIELDED_PROTOCOL, 12345)),
3557        Ok(None)
3558    );
3559
3560    let tx_history = st.wallet().get_tx_history().unwrap();
3561    assert_eq!(tx_history.len(), 2);
3562    {
3563        let tx_0 = &tx_history[0];
3564        assert_eq!(tx_0.total_spent(), Zatoshis::const_from_u64(0));
3565        assert_eq!(tx_0.total_received(), Zatoshis::const_from_u64(60000));
3566    }
3567
3568    {
3569        let tx_1 = &tx_history[1];
3570        assert_eq!(tx_1.total_spent(), Zatoshis::const_from_u64(60000));
3571        assert_eq!(tx_1.total_received(), Zatoshis::ZERO);
3572    }
3573
3574    let network = *st.network();
3575    assert_matches!(
3576        decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, None),
3577        Ok(_)
3578    );
3579}
3580/// Test attempts to sweep a wallet into a TEX address
3581///
3582/// 1. funds wallet with 100000 Zatoshis
3583/// 2. sets that spend amount will be 75000 Zatoshi
3584/// 3. proposes a transaction to a TEX address spending 75000 Zatoshi
3585/// 4. attempts to perform the proposal
3586/// 5. proposes the transaction
3587/// 6. "mines" the transaction.
3588/// 7. checks that all funds have been spent by the two involved transactions
3589///
3590/// Desired effects:
3591/// - all funds are spent
3592/// - Fees are the least possible: in this case 15000 for tr0 and 10000 Zats for tr1
3593#[cfg(feature = "transparent-inputs")]
3594pub fn spend_all_funds_multi_step_proposed_transfer<T: ShieldedPoolTester, Dsf>(
3595    ds_factory: Dsf,
3596    cache: impl TestCache,
3597) where
3598    Dsf: DataStoreFactory,
3599    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
3600{
3601    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache)
3602        .map(|builder| builder.with_gap_limits(GapLimits::new(10, 5, 3)))
3603        .build::<T>();
3604
3605    let account = st.test_account().cloned().unwrap();
3606    let account_id = account.id();
3607    let dfvk = T::test_account_fvk(&st);
3608
3609    let value = Zatoshis::const_from_u64(100000);
3610    let transfer_amount = Zatoshis::const_from_u64(75000);
3611
3612    // Add funds to the wallet.
3613    let (h, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
3614    st.scan_cached_blocks(h, 1);
3615
3616    let initial_balance = value;
3617    assert_eq!(
3618        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
3619        initial_balance
3620    );
3621
3622    let expected_step0_fee = (marginal_fee_at_target(&st) * 3u64).unwrap();
3623    let expected_step1_fee = minimum_fee_at_target(&st);
3624    let expected_ephemeral = (transfer_amount + expected_step1_fee).unwrap();
3625    let expected_step0_change =
3626        (initial_balance - expected_ephemeral - expected_step0_fee).expect("sufficient funds");
3627    assert!(expected_step0_change.is_zero());
3628
3629    let total_sent = (expected_step0_fee + expected_step1_fee + transfer_amount).unwrap();
3630
3631    // Generate a ZIP 320 proposal, sending to an external TEX address.
3632    let tex_addr = Address::Tex([0x4; 20]);
3633
3634    let change_memo: Option<MemoBytes> = None;
3635    // `propose_transfer_to` proposes a standard transfer, so this also tests
3636    // round-trip serialization of the proposal.
3637    let proposal = st.propose_transfer_to(&tex_addr, transfer_amount);
3638
3639    let steps: Vec<_> = proposal.steps().iter().cloned().collect();
3640    assert_eq!(steps.len(), 2);
3641
3642    assert_eq!(steps[0].balance().fee_required(), expected_step0_fee);
3643    assert_eq!(steps[1].balance().fee_required(), expected_step1_fee);
3644    assert_eq!(
3645        steps[0].balance().proposed_change(),
3646        [
3647            ChangeValue::shielded(T::SHIELDED_PROTOCOL, expected_step0_change, change_memo),
3648            ChangeValue::ephemeral_transparent(expected_ephemeral),
3649        ]
3650    );
3651    assert_eq!(steps[1].balance().proposed_change(), []);
3652
3653    let txids = st.create_proposed_expecting(&proposal, 2);
3654
3655    // Mine the created transactions.
3656    for txid in txids.iter() {
3657        let (h, _) = st.generate_next_block_including(*txid);
3658        st.scan_cached_blocks(h, 1);
3659    }
3660
3661    // Check that there are sent outputs with the correct values.
3662    let confirmed_sent: Vec<Vec<_>> = txids
3663        .iter()
3664        .map(|sent_txid| st.wallet().get_sent_outputs(sent_txid).unwrap())
3665        .collect();
3666
3667    // Verify that a status request has been generated for the second transaction of
3668    // the ZIP 320 pair.
3669    let tx_data_requests = st.wallet().transaction_data_requests().unwrap();
3670    assert!(tx_data_requests.contains(&TransactionDataRequest::GetStatus(*txids.last())));
3671
3672    assert!(expected_step0_change < expected_ephemeral);
3673    assert_eq!(confirmed_sent.len(), 2);
3674    assert_eq!(confirmed_sent[0].len(), 2);
3675    assert_eq!(confirmed_sent[0][0].value, expected_step0_change);
3676    let OutputOfSentTx {
3677        value: ephemeral_v,
3678        external_recipient: to_addr,
3679        ephemeral_address: _,
3680    } = confirmed_sent[0][1].clone();
3681    assert_eq!(ephemeral_v, expected_ephemeral);
3682    assert!(to_addr.is_some());
3683
3684    assert_eq!(confirmed_sent[1].len(), 1);
3685    assert_matches!(
3686            &confirmed_sent[1][0],
3687            OutputOfSentTx { value: sent_v, external_recipient: sent_to_addr, ephemeral_address: None }
3688            if sent_v == &transfer_amount && sent_to_addr == &Some(tex_addr));
3689
3690    // Check that the transaction history matches what we expect.
3691    let tx_history = st.wallet().get_tx_history().unwrap();
3692
3693    let tx_0 = tx_history
3694        .iter()
3695        .find(|tx| tx.txid() == *txids.first())
3696        .unwrap();
3697    let tx_1 = tx_history
3698        .iter()
3699        .find(|tx| tx.txid() == *txids.last())
3700        .unwrap();
3701
3702    assert_eq!(tx_0.account_id(), &account_id);
3703    assert!(!tx_0.expired_unmined());
3704    assert_eq!(tx_0.has_change(), expected_step0_change.is_zero());
3705    assert!(!tx_0.is_shielding());
3706    assert_eq!(
3707        tx_0.account_value_delta(),
3708        -ZatBalance::from(expected_step0_fee),
3709    );
3710
3711    assert_eq!(tx_1.account_id(), &account_id);
3712    assert!(!tx_1.expired_unmined());
3713    assert!(!tx_1.has_change());
3714    assert!(!tx_0.is_shielding());
3715    assert_eq!(
3716        tx_1.account_value_delta(),
3717        -ZatBalance::from(expected_ephemeral),
3718    );
3719
3720    let ending_balance = st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN);
3721    assert_eq!(initial_balance - total_sent, ending_balance.into());
3722}
3723
3724#[cfg(feature = "transparent-inputs")]
3725pub fn proposal_fails_if_not_all_ephemeral_outputs_consumed<T: ShieldedPoolTester, Dsf>(
3726    ds_factory: Dsf,
3727    cache: impl TestCache,
3728) where
3729    Dsf: DataStoreFactory,
3730{
3731    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
3732
3733    let account = st.test_account().cloned().unwrap();
3734    let account_id = account.id();
3735    let dfvk = T::test_account_fvk(&st);
3736
3737    let add_funds = |st: &mut TestState<_, Dsf::DataStore, _>, value| {
3738        let (h, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
3739        st.scan_cached_blocks(h, 1);
3740
3741        assert_eq!(
3742            st.wallet()
3743                .block_max_scanned()
3744                .unwrap()
3745                .unwrap()
3746                .block_height(),
3747            h
3748        );
3749        assert_eq!(
3750            st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
3751            value
3752        );
3753    };
3754
3755    let value = Zatoshis::const_from_u64(100000);
3756    let transfer_amount = Zatoshis::const_from_u64(50000);
3757
3758    // Add funds to the wallet.
3759    add_funds(&mut st, value);
3760
3761    // Generate a ZIP 320 proposal, sending to an external TEX address.
3762    let tex_addr = Address::Tex([0x4; 20]);
3763    let proposal = st.propose_transfer_to(&tex_addr, transfer_amount);
3764
3765    // This is somewhat redundant with `send_multi_step_proposed_transfer`,
3766    // but tests the case with no change memo and ensures we haven't messed
3767    // up the test setup.
3768    let create_proposed_result = st.create_proposed_transactions::<Infallible, _, Infallible, _>(
3769        account.usk(),
3770        OvkPolicy::Sender,
3771        &proposal,
3772    );
3773    assert_matches!(create_proposed_result, Ok(_));
3774
3775    // Frobnicate the proposal to make it invalid because it does not consume
3776    // the ephemeral output, by truncating it to the first step.
3777    let frobbed_proposal = Proposal::multi_step(
3778        *proposal.fee_rule(),
3779        proposal.min_target_height(),
3780        proposal.confirmations_policy(),
3781        NonEmpty::singleton(proposal.steps().first().clone()),
3782    )
3783    .unwrap();
3784
3785    let create_proposed_result = st.create_proposed_transactions::<Infallible, _, Infallible, _>(
3786        account.usk(),
3787        OvkPolicy::Sender,
3788        &frobbed_proposal,
3789    );
3790    assert_matches!(
3791        create_proposed_result,
3792        Err(Error::Proposal(ProposalError::EphemeralOutputLeftUnspent(so)))
3793        if so == StepOutput::new(0, StepOutputIndex::Change(1))
3794    );
3795}
3796
3797pub fn create_to_address_fails_on_incorrect_usk<T: ShieldedPoolTester, Dsf: DataStoreFactory>(
3798    ds_factory: Dsf,
3799) {
3800    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, ()).build::<T>();
3801    let dfvk = T::test_account_fvk(&st);
3802    let to = T::fvk_default_address(&dfvk);
3803
3804    // Create a USK that doesn't exist in the wallet
3805    let acct1 = zip32::AccountId::try_from(1).unwrap();
3806    let usk1 = UnifiedSpendingKey::from_seed(st.network(), &[1u8; 32], acct1).unwrap();
3807
3808    let input_selector = GreedyInputSelector::<Dsf::DataStore>::new();
3809    let change_strategy =
3810        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
3811
3812    let req = TransactionRequest::new(vec![Payment::without_memo(
3813        to.to_zcash_address(st.network()),
3814        Zatoshis::const_from_u64(1),
3815    )])
3816    .unwrap();
3817
3818    // Attempting to spend with a USK that is not in the wallet results in an error
3819    assert_matches!(
3820        st.spend(
3821            &input_selector,
3822            &change_strategy,
3823            &usk1,
3824            req,
3825            OvkPolicy::Sender,
3826            ConfirmationsPolicy::MIN,
3827        ),
3828        Err(data_api::error::Error::KeyNotRecognized)
3829    );
3830}
3831
3832pub fn proposal_fails_with_no_blocks<T: ShieldedPoolTester, Dsf>(ds_factory: Dsf)
3833where
3834    Dsf: DataStoreFactory,
3835    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
3836{
3837    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, ()).build::<T>();
3838
3839    let account_id = st.test_account().unwrap().id();
3840    let dfvk = T::test_account_fvk(&st);
3841    let to = T::fvk_default_address(&dfvk);
3842
3843    // Wallet summary is not yet available
3844    assert_eq!(st.get_wallet_summary(ConfirmationsPolicy::MIN), None);
3845
3846    // We cannot do anything if we aren't synchronised
3847    assert_matches!(
3848        st.propose_standard_transfer::<Infallible>(
3849            account_id,
3850            StandardFeeRule::Zip317,
3851            ConfirmationsPolicy::MIN,
3852            &to,
3853            Zatoshis::const_from_u64(1),
3854            None,
3855            None,
3856            T::SHIELDED_PROTOCOL,
3857        ),
3858        Err(data_api::error::Error::ScanRequired)
3859    );
3860}
3861
3862pub fn spend_fails_on_unverified_notes<T: ShieldedPoolTester>(
3863    ds_factory: impl DataStoreFactory,
3864    cache: impl TestCache,
3865) {
3866    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
3867
3868    let account = st.test_account().cloned().unwrap();
3869    let account_id = account.id();
3870    let dfvk = T::test_account_fvk(&st);
3871
3872    // Add funds to the wallet in a single note
3873    let value = Zatoshis::const_from_u64(50000);
3874    st.add_a_single_note_checking_balance(value);
3875
3876    // Value is considered pending at 10 confirmations.
3877    assert_eq!(
3878        st.get_pending_shielded_balance(account_id, ConfirmationsPolicy::default()),
3879        value
3880    );
3881    assert_eq!(
3882        st.get_spendable_balance(account_id, ConfirmationsPolicy::default()),
3883        Zatoshis::ZERO
3884    );
3885
3886    // If none of the wallet's accounts have a recover-until height, then there
3887    // is no recovery phase for the wallet, and therefore the denominator in the
3888    // resulting ratio (the number of notes in the recovery range) is zero.
3889    let no_recovery = Some(Ratio::new(0, 0));
3890
3891    // Wallet is fully scanned
3892    let summary = st.get_wallet_summary(ConfirmationsPolicy::MIN);
3893    assert_eq!(
3894        summary.as_ref().and_then(|s| s.progress().recovery()),
3895        no_recovery,
3896    );
3897    assert_eq!(summary.map(|s| s.progress().scan()), Some(Ratio::new(1, 1)));
3898
3899    // Add more funds to the wallet in a second note
3900    let (h2, _, _) = st.add_a_single_note_checking_balance(value);
3901
3902    // Verified balance does not include the second note
3903    let total = (value + value).unwrap();
3904    assert_eq!(
3905        st.get_spendable_balance(
3906            account_id,
3907            ConfirmationsPolicy::new_symmetrical_unchecked(
3908                2,
3909                #[cfg(feature = "transparent-inputs")]
3910                false
3911            )
3912        ),
3913        value
3914    );
3915    assert_eq!(
3916        st.get_pending_shielded_balance(
3917            account_id,
3918            ConfirmationsPolicy::new_symmetrical_unchecked(
3919                2,
3920                #[cfg(feature = "transparent-inputs")]
3921                false
3922            )
3923        ),
3924        value
3925    );
3926    assert_eq!(st.get_total_balance(account_id), total);
3927
3928    // Wallet is still fully scanned
3929    let summary = st.get_wallet_summary(ConfirmationsPolicy::MIN);
3930    assert_eq!(
3931        summary.as_ref().and_then(|s| s.progress().recovery()),
3932        no_recovery
3933    );
3934    assert_eq!(summary.map(|s| s.progress().scan()), Some(Ratio::new(2, 2)));
3935
3936    // Spend fails because there are insufficient verified notes
3937    let extsk2 = T::sk(&[0xf5; 32]);
3938    let to = T::sk_default_address(&extsk2);
3939    st.expect_insufficient_funds_with(
3940        &to,
3941        Zatoshis::const_from_u64(70000),
3942        ConfirmationsPolicy::new_symmetrical_unchecked(
3943            2,
3944            #[cfg(feature = "transparent-inputs")]
3945            false,
3946        ),
3947        Zatoshis::const_from_u64(50000),
3948        Zatoshis::const_from_u64(80000),
3949    );
3950
3951    // Mine blocks SAPLING_ACTIVATION_HEIGHT + 2 to 9 until just before the second
3952    // note is verified
3953    for _ in 2..10 {
3954        st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
3955    }
3956    st.scan_cached_blocks(h2 + 1, 8);
3957
3958    // Total balance is value * number of blocks scanned (10).
3959    assert_eq!(st.get_total_balance(account_id), (value * 10u64).unwrap());
3960
3961    // Spend still fails
3962    st.expect_insufficient_funds_with(
3963        &to,
3964        Zatoshis::const_from_u64(70000),
3965        ConfirmationsPolicy::default(),
3966        Zatoshis::const_from_u64(50000),
3967        Zatoshis::const_from_u64(80000),
3968    );
3969
3970    // Mine block 11 so that the second note becomes verified
3971    let (h11, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
3972    st.scan_cached_blocks(h11, 1);
3973
3974    // Total balance is value * number of blocks scanned (11).
3975    assert_eq!(st.get_total_balance(account_id), (value * 11u64).unwrap());
3976    // Spendable balance at 10 confirmations is value * 2.
3977    assert_eq!(
3978        st.get_spendable_balance(account_id, ConfirmationsPolicy::default()),
3979        (value * 2u64).unwrap()
3980    );
3981    assert_eq!(
3982        st.get_pending_shielded_balance(account_id, ConfirmationsPolicy::default()),
3983        (value * 9u64).unwrap()
3984    );
3985
3986    // Should now be able to generate a proposal
3987    let amount_sent = Zatoshis::from_u64(70000).unwrap();
3988    let proposal = st
3989        .propose_standard_transfer::<Infallible>(
3990            account_id,
3991            StandardFeeRule::Zip317,
3992            ConfirmationsPolicy::default(),
3993            &to,
3994            amount_sent,
3995            None,
3996            None,
3997            T::SHIELDED_PROTOCOL,
3998        )
3999        .unwrap();
4000
4001    // Executing the proposal should succeed
4002    let txid = st
4003        .create_proposed_transactions::<Infallible, _, Infallible, _>(
4004            account.usk(),
4005            OvkPolicy::Sender,
4006            &proposal,
4007        )
4008        .unwrap()[0];
4009
4010    let (h, _) = st.generate_next_block_including(txid);
4011    st.scan_cached_blocks(h, 1);
4012
4013    // TODO: send to an account so that we can check its balance.
4014    assert_eq!(
4015        st.get_total_balance(account_id),
4016        ((value * 11u64).unwrap() - (amount_sent + Zatoshis::from_u64(10000).unwrap()).unwrap())
4017            .unwrap()
4018    );
4019}
4020
4021pub fn ovk_policy_prevents_recovery_from_chain<T: ShieldedPoolTester, Dsf>(
4022    ds_factory: Dsf,
4023    cache: impl TestCache,
4024) where
4025    Dsf: DataStoreFactory,
4026{
4027    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
4028
4029    let account = st.test_account().cloned().unwrap();
4030    let account_id = account.id();
4031    let dfvk = T::test_account_fvk(&st);
4032
4033    // Add funds to the wallet in a single note
4034    let value = Zatoshis::const_from_u64(50000);
4035    let (h1, _, _) = st.add_a_single_note_checking_balance(value);
4036
4037    let extsk2 = T::sk(&[0xf5; 32]);
4038    let addr2 = T::sk_default_address(&extsk2);
4039
4040    let fee_rule = StandardFeeRule::Zip317;
4041
4042    #[allow(clippy::type_complexity)]
4043    let send_and_recover_with_policy = |st: &mut TestState<_, Dsf::DataStore, _>,
4044                                        ovk_policy|
4045     -> Result<
4046        Option<(Note, Address, MemoBytes)>,
4047        TransferErrT<
4048            Dsf::DataStore,
4049            GreedyInputSelector<Dsf::DataStore>,
4050            SingleOutputChangeStrategy<Dsf::DataStore>,
4051        >,
4052    > {
4053        let proposal = st.propose_standard_transfer(
4054            account_id,
4055            fee_rule,
4056            ConfirmationsPolicy::MIN,
4057            &addr2,
4058            Zatoshis::const_from_u64(15000),
4059            None,
4060            None,
4061            T::SHIELDED_PROTOCOL,
4062        )?;
4063
4064        // Executing the proposal should succeed
4065        let txid = st.create_proposed_transactions(account.usk(), ovk_policy, &proposal)?[0];
4066
4067        // Fetch the transaction from the database
4068        let tx = st
4069            .wallet()
4070            .get_transaction(txid)
4071            .map_err(Error::DataSource)?
4072            .unwrap();
4073
4074        Ok(T::try_output_recovery(st.network(), h1, &tx, &dfvk))
4075    };
4076
4077    // Send some of the funds to another address, keeping history.
4078    // The recipient output is decryptable by the sender.
4079    assert_matches!(
4080        send_and_recover_with_policy(&mut st, OvkPolicy::Sender),
4081        Ok(Some((_, recovered_to, _))) if recovered_to == addr2
4082    );
4083
4084    // Mine blocks SAPLING_ACTIVATION_HEIGHT + 1 to 42 (that don't send us funds)
4085    // so that the first transaction expires
4086    for i in 1..=42 {
4087        st.generate_next_block(
4088            &T::sk_to_fvk(&T::sk(&[i as u8; 32])),
4089            AddressType::DefaultExternal,
4090            value,
4091        );
4092    }
4093    st.scan_cached_blocks(h1 + 1, 42);
4094
4095    // Send the funds again, discarding history.
4096    // Neither transaction output is decryptable by the sender.
4097    assert_matches!(
4098        send_and_recover_with_policy(&mut st, OvkPolicy::Discard),
4099        Ok(None)
4100    );
4101}
4102
4103pub fn spend_succeeds_to_t_addr_zero_change<T: ShieldedPoolTester>(
4104    ds_factory: impl DataStoreFactory,
4105    cache: impl TestCache,
4106) {
4107    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
4108
4109    // Add funds to the wallet in a single note
4110    let value = Zatoshis::const_from_u64(70000);
4111    st.add_a_single_note_checking_balance(value);
4112
4113    // TODO: generate_next_block_from_tx does not currently support transparent outputs.
4114    let to = TransparentAddress::PublicKeyHash([7; 20]).into();
4115    let account = st.test_account().cloned().unwrap();
4116    let amount_sent = Zatoshis::const_from_u64(50000);
4117    let proposal = st.propose_transfer_to(&to, amount_sent);
4118
4119    // Executing the proposal should succeed
4120    assert_matches!(
4121        st.create_proposed_transactions::<Infallible, _, Infallible, _>(account.usk(), OvkPolicy::Sender, &proposal),
4122        Ok(txids) if txids.len() == 1
4123    );
4124}
4125
4126pub fn change_note_spends_succeed<T: ShieldedPoolTester>(
4127    ds_factory: impl DataStoreFactory,
4128    cache: impl TestCache,
4129) {
4130    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
4131
4132    // Add funds to the wallet in a single note owned by the internal spending key
4133    let value = Zatoshis::const_from_u64(70000);
4134    st.add_a_single_note_checking_balance(
4135        TestNoteConfig::from(value).with_address_type(AddressType::Internal),
4136    );
4137
4138    // Value is considered pending at 10 confirmations.
4139    let account = st.test_account().cloned().unwrap();
4140    let account_id = account.id();
4141    assert_eq!(
4142        st.get_pending_shielded_balance(account_id, ConfirmationsPolicy::default()),
4143        value
4144    );
4145    assert_eq!(
4146        st.get_spendable_balance(account_id, ConfirmationsPolicy::default()),
4147        Zatoshis::ZERO
4148    );
4149
4150    let change_note_scope = st
4151        .wallet()
4152        .get_notes(T::SHIELDED_PROTOCOL)
4153        .unwrap()
4154        .iter()
4155        .find_map(|note| (note.note().value() == value).then_some(note.spending_key_scope()));
4156    assert_matches!(change_note_scope, Some(Scope::Internal));
4157
4158    // TODO: generate_next_block_from_tx does not currently support transparent outputs.
4159    let to = TransparentAddress::PublicKeyHash([7; 20]).into();
4160    let amount_sent = Zatoshis::const_from_u64(50000);
4161    let proposal = st.propose_transfer_to(&to, amount_sent);
4162
4163    // Executing the proposal should succeed
4164    assert_matches!(
4165        st.create_proposed_transactions::<Infallible, _, Infallible, _>(account.usk(), OvkPolicy::Sender, &proposal),
4166        Ok(txids) if txids.len() == 1
4167    );
4168}
4169
4170pub fn account_deletion<T: ShieldedPoolTester, DSF>(ds_factory: DSF, cache: impl TestCache)
4171where
4172    DSF: DataStoreFactory,
4173    <DSF as DataStoreFactory>::DataStore: Reset,
4174{
4175    let mut st = TestBuilder::new()
4176        .with_data_store_factory(ds_factory)
4177        .with_block_cache(cache)
4178        .build();
4179
4180    // Add two accounts to the wallet.
4181    let seed = Secret::new([0u8; 32].to_vec());
4182    let birthday = AccountBirthday::from_sapling_activation(st.network(), BlockHash([0; 32]));
4183    let (account1, usk) = st
4184        .wallet_mut()
4185        .create_account("account1", &seed, &birthday, None)
4186        .unwrap();
4187    let dfvk = T::sk_to_fvk(T::usk_to_sk(&usk));
4188
4189    let (account2, usk2) = st
4190        .wallet_mut()
4191        .create_account("account2", &seed, &birthday, None)
4192        .unwrap();
4193    let dfvk2 = T::sk_to_fvk(T::usk_to_sk(&usk2));
4194
4195    // Add funds to the account 0 in a single note
4196    let value = Zatoshis::from_u64(100000).unwrap();
4197    let (h, b0_result, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
4198    st.scan_cached_blocks(h, 1);
4199    let txid0 = *b0_result
4200        .txids()
4201        .first()
4202        .expect("A transaction was created.");
4203
4204    // Spendable balance matches total balance
4205    assert_eq!(st.get_total_balance(account1), value);
4206    assert_eq!(
4207        st.get_spendable_balance(account1, ConfirmationsPolicy::MIN),
4208        value
4209    );
4210    assert_eq!(st.get_total_balance(account2), Zatoshis::ZERO);
4211
4212    let bal_2 = Zatoshis::from_u64(50000).unwrap();
4213    let addr2 = T::fvk_default_address(&dfvk2);
4214    let req = TransactionRequest::new(vec![
4215        // payment to an account 2
4216        Payment::without_memo(addr2.to_zcash_address(st.network()), bal_2),
4217    ])
4218    .unwrap();
4219
4220    let change_strategy =
4221        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
4222    let input_selector = GreedyInputSelector::new();
4223
4224    let txid1 = st
4225        .spend(
4226            &input_selector,
4227            &change_strategy,
4228            &usk,
4229            req,
4230            OvkPolicy::Sender,
4231            ConfirmationsPolicy::MIN,
4232        )
4233        .unwrap()[0];
4234
4235    let bal_1 = (value - (bal_2 + minimum_fee_at_target(&st)).unwrap()).unwrap();
4236    assert_eq!(st.get_total_balance(account1), bal_1);
4237
4238    let (h, _) = st.generate_next_block_including(txid1);
4239    st.scan_cached_blocks(h, 1);
4240
4241    assert_eq!(st.get_total_balance(account2), bal_2);
4242    assert_eq!(st.get_total_balance(account1), bal_1);
4243
4244    // txid0 should exist; we haven't enhanced it so we'll have the mined height, but not the raw
4245    // transaction data.
4246    assert_matches!(st.wallet_mut().get_tx_height(txid0), Ok(Some(_)));
4247
4248    // delete account 1
4249    assert_matches!(st.wallet_mut().delete_account(account1), Ok(_));
4250
4251    // txid0 should no longer exist in the wallet at all, because it only involved account1
4252    assert_matches!(st.wallet_mut().get_tx_height(txid0), Ok(None));
4253
4254    // txid1 should exist in the wallet, as it involves account 2
4255    assert_matches!(st.wallet_mut().get_transaction(txid1), Ok(Some(_)));
4256
4257    let summary = st
4258        .wallet()
4259        .get_wallet_summary(ConfirmationsPolicy::MIN)
4260        .unwrap()
4261        .unwrap();
4262    assert!(summary.account_balances().get(&account1).is_none());
4263    assert_eq!(
4264        summary.account_balances().get(&account2).unwrap().total(),
4265        bal_2
4266    );
4267    assert_eq!(
4268        summary
4269            .account_balances()
4270            .get(&account2)
4271            .unwrap()
4272            .spendable_value(),
4273        bal_2
4274    );
4275
4276    // Create a third account
4277    let (account3, usk3) = st
4278        .wallet_mut()
4279        .create_account("account3", &seed, &birthday, None)
4280        .unwrap();
4281    let dfvk3 = T::sk_to_fvk(T::usk_to_sk(&usk3));
4282
4283    // Creating a new account with the original birthday forces a rescan.
4284    st.scan_cached_blocks(birthday.height(), 2);
4285
4286    let bal_3 = Zatoshis::from_u64(20000).unwrap();
4287    let addr3 = T::fvk_default_address(&dfvk3);
4288    let req = TransactionRequest::new(vec![
4289        // payment to an account 3
4290        Payment::without_memo(addr3.to_zcash_address(st.network()), bal_3),
4291    ])
4292    .unwrap();
4293
4294    let txid2 = st
4295        .spend(
4296            &input_selector,
4297            &change_strategy,
4298            &usk2,
4299            req,
4300            OvkPolicy::Sender,
4301            ConfirmationsPolicy::MIN,
4302        )
4303        .unwrap()[0];
4304
4305    let bal_2_final = (bal_2 - (bal_3 + minimum_fee_at_target(&st)).unwrap()).unwrap();
4306    assert_eq!(st.get_total_balance(account2), bal_2_final);
4307
4308    let (h, _) = st.generate_next_block_including(txid2);
4309    st.scan_cached_blocks(h, 1);
4310
4311    assert_eq!(st.get_total_balance(account2), bal_2_final);
4312    assert_eq!(st.get_total_balance(account3), bal_3);
4313
4314    // txid2 should exist; we haven't enhanced it so we'll have the mined height, but not the raw
4315    // transaction data.
4316    assert_matches!(st.wallet_mut().get_tx_height(txid2), Ok(Some(_)));
4317
4318    // delete account 3
4319    assert_matches!(st.wallet_mut().delete_account(account3), Ok(_));
4320
4321    // txid2 should still exist in the wallet, as it involves account 2
4322    assert_matches!(st.wallet_mut().get_transaction(txid2), Ok(Some(_)));
4323
4324    let summary = st
4325        .wallet()
4326        .get_wallet_summary(ConfirmationsPolicy::default())
4327        .unwrap()
4328        .unwrap();
4329    assert!(summary.account_balances().get(&account3).is_none());
4330    assert_eq!(
4331        summary.account_balances().get(&account2).unwrap().total(),
4332        bal_2_final
4333    );
4334}
4335
4336/// Regression test for a bug in which [`WalletWrite::delete_account`] failed with a
4337/// `rusqlite::Error::InvalidParameterName(":address")` panic when the account being
4338/// deleted was referenced by a `sent_notes` row via its `to_account_id` column.
4339///
4340/// The triggering state is reached when a transaction is sent from one account in the
4341/// wallet to an address belonging to a second account in the same wallet, and the
4342/// transaction is then decrypted via [`decrypt_and_store_transaction`] so that the
4343/// cross-account transfer is recorded with a non-null `to_account_id` and a received
4344/// output that has an associated address. Deleting the recipient account then exercises
4345/// the `sent_notes` update path inside `delete_account`.
4346///
4347/// [`WalletWrite::delete_account`]: crate::data_api::WalletWrite::delete_account
4348pub fn account_deletion_with_internal_transfer<T: ShieldedPoolTester, DSF>(
4349    ds_factory: DSF,
4350    cache: impl TestCache,
4351) where
4352    DSF: DataStoreFactory,
4353    <DSF as DataStoreFactory>::DataStore: Reset,
4354{
4355    let mut st = TestBuilder::new()
4356        .with_data_store_factory(ds_factory)
4357        .with_block_cache(cache)
4358        .build();
4359
4360    // Add two accounts to the wallet, derived from the same seed.
4361    let seed = Secret::new([0u8; 32].to_vec());
4362    let birthday = AccountBirthday::from_sapling_activation(st.network(), BlockHash([0; 32]));
4363    let (account1, usk1) = st
4364        .wallet_mut()
4365        .create_account("account1", &seed, &birthday, None)
4366        .unwrap();
4367    let dfvk1 = T::sk_to_fvk(T::usk_to_sk(&usk1));
4368
4369    let (account2, usk2) = st
4370        .wallet_mut()
4371        .create_account("account2", &seed, &birthday, None)
4372        .unwrap();
4373    let dfvk2 = T::sk_to_fvk(T::usk_to_sk(&usk2));
4374
4375    // Add funds to account 1 in a single note.
4376    let value = Zatoshis::from_u64(100000).unwrap();
4377    let (h, _, _) = st.generate_next_block(&dfvk1, AddressType::DefaultExternal, value);
4378    st.scan_cached_blocks(h, 1);
4379
4380    assert_eq!(st.get_total_balance(account1), value);
4381    assert_eq!(st.get_total_balance(account2), Zatoshis::ZERO);
4382
4383    // Send funds from account 1 to an address belonging to account 2.
4384    let bal_2 = Zatoshis::from_u64(50000).unwrap();
4385    let addr2 = T::fvk_default_address(&dfvk2);
4386    let req = TransactionRequest::new(vec![Payment::without_memo(
4387        addr2.to_zcash_address(st.network()),
4388        bal_2,
4389    )])
4390    .unwrap();
4391
4392    let change_strategy =
4393        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
4394    let input_selector = GreedyInputSelector::new();
4395
4396    let txid = st
4397        .spend(
4398            &input_selector,
4399            &change_strategy,
4400            &usk1,
4401            req,
4402            OvkPolicy::Sender,
4403            ConfirmationsPolicy::MIN,
4404        )
4405        .unwrap()[0];
4406
4407    let (h, _) = st.generate_next_block_including(txid);
4408    st.scan_cached_blocks(h, 1);
4409
4410    assert_eq!(st.get_total_balance(account2), bal_2);
4411
4412    // Decrypt and store the transaction. Because the wallet owns the funding inputs
4413    // (account 1) and the output is received by account 2, this records the send as an
4414    // internal cross-account transfer, setting `sent_notes.to_account_id` to account 2
4415    // and associating the received output with account 2's address. This is the state
4416    // that triggers the `delete_account` bug.
4417    let tx = st.wallet().get_transaction(txid).unwrap().unwrap();
4418    let params = *st.network();
4419    decrypt_and_store_transaction(&params, st.wallet_mut(), &tx, Some(h)).unwrap();
4420
4421    // Deleting account 2, the recipient of the internal transfer, must succeed. Prior to
4422    // the fix this failed with `rusqlite::Error::InvalidParameterName(":address")` because
4423    // the `sent_notes` update statement bound the wrong parameter name.
4424    assert_matches!(st.wallet_mut().delete_account(account2), Ok(_));
4425
4426    // account 1 should still exist and retain its change balance.
4427    let summary = st
4428        .wallet()
4429        .get_wallet_summary(ConfirmationsPolicy::MIN)
4430        .unwrap()
4431        .unwrap();
4432    assert!(summary.account_balances().get(&account2).is_none());
4433    assert!(summary.account_balances().contains_key(&account1));
4434}
4435
4436/// Verifies that [`WalletWrite::set_account_name`] replaces the name of the given account,
4437/// leaves the names of other accounts unchanged, and permits two accounts to share a name.
4438///
4439/// [`WalletWrite::set_account_name`]: crate::data_api::WalletWrite::set_account_name
4440pub fn account_rename<T: ShieldedPoolTester, DSF>(ds_factory: DSF, cache: impl TestCache)
4441where
4442    DSF: DataStoreFactory,
4443    <DSF as DataStoreFactory>::DataStore: Reset,
4444{
4445    /// The initial name of the first account.
4446    const ACCOUNT1_NAME: &str = "account1";
4447    /// The initial name of the second account.
4448    const ACCOUNT2_NAME: &str = "account2";
4449    /// The name that both accounts are renamed to.
4450    const RENAMED_NAME: &str = "renamed";
4451
4452    let mut st = TestBuilder::new()
4453        .with_data_store_factory(ds_factory)
4454        .with_block_cache(cache)
4455        .build();
4456
4457    // Add two accounts to the wallet, derived from the same seed.
4458    let seed = Secret::new([0u8; 32].to_vec());
4459    let birthday = AccountBirthday::from_sapling_activation(st.network(), BlockHash([0; 32]));
4460    let (account1, _) = st
4461        .wallet_mut()
4462        .create_account(ACCOUNT1_NAME, &seed, &birthday, None)
4463        .unwrap();
4464    let (account2, _) = st
4465        .wallet_mut()
4466        .create_account(ACCOUNT2_NAME, &seed, &birthday, None)
4467        .unwrap();
4468
4469    // Renaming account 1 changes only its name.
4470    assert_matches!(
4471        st.wallet_mut().set_account_name(account1, RENAMED_NAME),
4472        Ok(())
4473    );
4474    let renamed1 = st.wallet().get_account(account1).unwrap().unwrap();
4475    let untouched2 = st.wallet().get_account(account2).unwrap().unwrap();
4476    assert_eq!(renamed1.name(), Some(RENAMED_NAME));
4477    assert_eq!(untouched2.name(), Some(ACCOUNT2_NAME));
4478
4479    // Account names are not required to be unique.
4480    assert_matches!(
4481        st.wallet_mut().set_account_name(account2, RENAMED_NAME),
4482        Ok(())
4483    );
4484    let renamed1 = st.wallet().get_account(account1).unwrap().unwrap();
4485    let renamed2 = st.wallet().get_account(account2).unwrap().unwrap();
4486    assert_eq!(renamed1.name(), Some(RENAMED_NAME));
4487    assert_eq!(renamed2.name(), Some(RENAMED_NAME));
4488}
4489
4490pub fn external_address_change_spends_detected_in_restore_from_seed<T: ShieldedPoolTester, Dsf>(
4491    ds_factory: Dsf,
4492    cache: impl TestCache,
4493) where
4494    Dsf: DataStoreFactory,
4495    <Dsf as DataStoreFactory>::DataStore: Reset,
4496{
4497    let mut st = TestBuilder::new()
4498        .with_data_store_factory(ds_factory)
4499        .with_block_cache(cache)
4500        .build();
4501
4502    // Add two accounts to the wallet.
4503    let seed = Secret::new([0u8; 32].to_vec());
4504    let birthday = AccountBirthday::from_sapling_activation(st.network(), BlockHash([0; 32]));
4505    let (account1, usk) = st
4506        .wallet_mut()
4507        .create_account("account1", &seed, &birthday, None)
4508        .unwrap();
4509    let dfvk = T::sk_to_fvk(T::usk_to_sk(&usk));
4510
4511    let (account2, usk2) = st
4512        .wallet_mut()
4513        .create_account("account2", &seed, &birthday, None)
4514        .unwrap();
4515    let dfvk2 = T::sk_to_fvk(T::usk_to_sk(&usk2));
4516
4517    // Add funds to the wallet in a single note
4518    let value = Zatoshis::from_u64(100000).unwrap();
4519    let (h, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
4520    st.scan_cached_blocks(h, 1);
4521
4522    // Spendable balance matches total balance
4523    assert_eq!(st.get_total_balance(account1), value);
4524    assert_eq!(
4525        st.get_spendable_balance(account1, ConfirmationsPolicy::MIN),
4526        value
4527    );
4528    assert_eq!(st.get_total_balance(account2), Zatoshis::ZERO);
4529
4530    let amount_sent = Zatoshis::from_u64(20000).unwrap();
4531    let amount_legacy_change = Zatoshis::from_u64(30000).unwrap();
4532    let addr = T::fvk_default_address(&dfvk);
4533    let addr2 = T::fvk_default_address(&dfvk2);
4534    let req = TransactionRequest::new(vec![
4535        // payment to an external recipient
4536        Payment::without_memo(addr2.to_zcash_address(st.network()), amount_sent),
4537        // payment back to the originating wallet, simulating legacy change
4538        Payment::without_memo(addr.to_zcash_address(st.network()), amount_legacy_change),
4539    ])
4540    .unwrap();
4541
4542    let change_strategy =
4543        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
4544    let input_selector = GreedyInputSelector::new();
4545
4546    let txid = st
4547        .spend(
4548            &input_selector,
4549            &change_strategy,
4550            &usk,
4551            req,
4552            OvkPolicy::Sender,
4553            ConfirmationsPolicy::MIN,
4554        )
4555        .unwrap()[0];
4556
4557    let amount_left = (value
4558        - (amount_sent + minimum_fee_at_target(&st) + marginal_fee_at_target(&st)).unwrap())
4559    .unwrap();
4560    let pending_change = (amount_left - amount_legacy_change).unwrap();
4561
4562    // The "legacy change" is not counted by get_pending_change().
4563    assert_eq!(
4564        st.get_pending_change(account1, ConfirmationsPolicy::MIN),
4565        pending_change
4566    );
4567    // We spent the only note so we only have pending change.
4568    assert_eq!(st.get_total_balance(account1), pending_change);
4569
4570    let (h, _) = st.generate_next_block_including(txid);
4571    st.scan_cached_blocks(h, 1);
4572
4573    assert_eq!(st.get_total_balance(account2), amount_sent,);
4574    assert_eq!(st.get_total_balance(account1), amount_left);
4575
4576    st.reset();
4577
4578    // Account creation and DFVK derivation should be deterministic.
4579    let (account1, restored_usk) = st
4580        .wallet_mut()
4581        .create_account("account1_restored", &seed, &birthday, None)
4582        .unwrap();
4583    assert!(T::fvks_equal(
4584        &T::sk_to_fvk(T::usk_to_sk(&restored_usk)),
4585        &dfvk,
4586    ));
4587
4588    let (account2, restored_usk2) = st
4589        .wallet_mut()
4590        .create_account("account2_restored", &seed, &birthday, None)
4591        .unwrap();
4592    assert!(T::fvks_equal(
4593        &T::sk_to_fvk(T::usk_to_sk(&restored_usk2)),
4594        &dfvk2,
4595    ));
4596
4597    st.scan_cached_blocks(st.sapling_activation_height(), 2);
4598
4599    assert_eq!(st.get_total_balance(account2), amount_sent);
4600    assert_eq!(st.get_total_balance(account1), amount_left);
4601}
4602
4603#[allow(dead_code)]
4604pub fn zip317_spend<T: ShieldedPoolTester, Dsf: DataStoreFactory>(
4605    ds_factory: Dsf,
4606    cache: impl TestCache,
4607) {
4608    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
4609
4610    let account = st.test_account().cloned().unwrap();
4611    let account_id = account.id();
4612    let dfvk = T::test_account_fvk(&st);
4613
4614    // Add funds to the wallet
4615    st.add_notes_checking_balance([Some(Zatoshis::const_from_u64(50000))]);
4616
4617    // Add 10 uneconomic (dust) notes to the wallet
4618    for _ in 1..=10 {
4619        st.add_notes_checking_balance([Some(Zatoshis::const_from_u64(1000))]);
4620    }
4621
4622    // Spendable balance matches total balance
4623    let total = Zatoshis::const_from_u64(60000);
4624    assert_eq!(st.get_total_balance(account_id), total);
4625    assert_eq!(
4626        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
4627        total
4628    );
4629
4630    let input_selector = GreedyInputSelector::<Dsf::DataStore>::new();
4631    let change_strategy =
4632        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
4633
4634    // This first request will fail due to insufficient non-dust funds
4635    let req = TransactionRequest::new(vec![Payment::without_memo(
4636        T::fvk_default_address(&dfvk).to_zcash_address(st.network()),
4637        Zatoshis::const_from_u64(50000),
4638    )])
4639    .unwrap();
4640
4641    assert_matches!(
4642        st.spend(
4643            &input_selector,
4644            &change_strategy,
4645            account.usk(),
4646            req,
4647            OvkPolicy::Sender,
4648            ConfirmationsPolicy::MIN,
4649        ),
4650        Err(Error::InsufficientFunds { available, required })
4651            if available == Zatoshis::const_from_u64(51000)
4652            && required == Zatoshis::const_from_u64(60000)
4653    );
4654
4655    // This request will succeed, spending a single dust input to pay the 10000
4656    // ZAT fee in addition to the 41000 ZAT output to the recipient
4657    let req = TransactionRequest::new(vec![Payment::without_memo(
4658        T::fvk_default_address(&dfvk).to_zcash_address(st.network()),
4659        Zatoshis::const_from_u64(41000),
4660    )])
4661    .unwrap();
4662
4663    let txid = st
4664        .spend(
4665            &input_selector,
4666            &change_strategy,
4667            account.usk(),
4668            req,
4669            OvkPolicy::Sender,
4670            ConfirmationsPolicy::MIN,
4671        )
4672        .unwrap()[0];
4673
4674    let (h, _) = st.generate_next_block_including(txid);
4675    st.scan_cached_blocks(h, 1);
4676
4677    // TODO: send to an account so that we can check its balance.
4678    // We sent back to the same account so the amount_sent should be included
4679    // in the total balance.
4680    assert_eq!(
4681        st.get_total_balance(account_id),
4682        (total - Zatoshis::const_from_u64(10000)).unwrap()
4683    );
4684}
4685
4686#[cfg(feature = "transparent-inputs")]
4687pub fn shield_transparent<T: ShieldedPoolTester, Dsf>(ds_factory: Dsf, cache: impl TestCache)
4688where
4689    Dsf: DataStoreFactory,
4690    <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
4691{
4692    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
4693
4694    let account = st.test_account().cloned().unwrap();
4695    let dfvk = T::test_account_fvk(&st);
4696
4697    let uaddr = st
4698        .wallet()
4699        .get_last_generated_address_matching(account.id(), UnifiedAddressRequest::AllAvailableKeys)
4700        .unwrap()
4701        .unwrap();
4702    let taddr = uaddr.transparent().unwrap();
4703
4704    // Ensure that the wallet has at least one block
4705    let (h, _, _) = st.generate_next_block(
4706        &dfvk,
4707        AddressType::Internal,
4708        Zatoshis::const_from_u64(50000),
4709    );
4710    st.scan_cached_blocks(h, 1);
4711
4712    let spent_outpoint = OutPoint::fake();
4713    let utxo = WalletTransparentOutput::from_parts(
4714        spent_outpoint.clone(),
4715        TxOut::new(Zatoshis::const_from_u64(100000), taddr.script().into()),
4716        Some(h),
4717        Some(account.id()),
4718        Some(TransparentKeyScope::EXTERNAL),
4719        None,
4720    )
4721    .unwrap();
4722
4723    let res0 = st.wallet_mut().put_received_transparent_utxo(&utxo);
4724    assert_matches!(res0, Ok(_));
4725
4726    let input_selector = GreedyInputSelector::new();
4727    let change_strategy =
4728        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
4729
4730    let txids = st
4731        .shield_transparent_funds(
4732            &input_selector,
4733            &change_strategy,
4734            Zatoshis::from_u64(10000).unwrap(),
4735            account.usk(),
4736            &[*taddr],
4737            account.id(),
4738            ConfirmationsPolicy::MIN,
4739        )
4740        .unwrap();
4741    assert_eq!(txids.len(), 1);
4742    let shielding_txid = *txids.first();
4743
4744    assert!(
4745        !st.wallet()
4746            .transaction_data_requests()
4747            .unwrap()
4748            .contains(&TransactionDataRequest::GetStatus(shielding_txid)),
4749        "a wallet-owned shielded output makes the transaction observable by scanning",
4750    );
4751
4752    let tx_summary = st.get_tx_from_history(shielding_txid).unwrap().unwrap();
4753    assert_eq!(tx_summary.spent_note_count(), 1);
4754    assert!(tx_summary.has_change());
4755    assert_eq!(tx_summary.received_note_count(), 0);
4756    assert_eq!(tx_summary.sent_note_count(), 0);
4757    assert!(tx_summary.is_shielding());
4758
4759    // Generate and scan the block including the transaction
4760    let (h, _) = st.generate_next_block_including(shielding_txid);
4761    let scan_result = st.scan_cached_blocks(h, 1);
4762
4763    // Ensure that the transaction metadata is still correct after the update produced by scanning.
4764    let tx_summary = st.get_tx_from_history(shielding_txid).unwrap().unwrap();
4765    assert_eq!(tx_summary.spent_note_count(), 1);
4766    assert!(tx_summary.has_change());
4767    assert_eq!(tx_summary.received_note_count(), 0);
4768    assert_eq!(tx_summary.sent_note_count(), 0);
4769    assert!(tx_summary.is_shielding());
4770
4771    // Verify that a transaction enhancement request for the transaction containing the spent
4772    // outpoint does not yet exist.
4773    let requests = st.wallet().transaction_data_requests().unwrap();
4774    assert!(
4775        !requests.iter().any(|req| req
4776            == &TransactionDataRequest::Enhancement(TxId::from_bytes(*spent_outpoint.hash())))
4777    );
4778
4779    // Use `decrypt_and_store_transaction` for the side effect of creating enhancement requests for
4780    // the transparent inputs of the transaction.
4781    let tx = st
4782        .wallet()
4783        .get_transaction(*txids.first())
4784        .unwrap()
4785        .unwrap();
4786    let params = *st.network();
4787    decrypt_and_store_transaction(&params, st.wallet_mut(), &tx, Some(h)).unwrap();
4788
4789    // Verify that a transaction enhancement request for the received transaction was created
4790    let requests = st.wallet().transaction_data_requests().unwrap();
4791    assert!(
4792        requests.iter().any(|req| req
4793            == &TransactionDataRequest::Enhancement(TxId::from_bytes(*spent_outpoint.hash())))
4794    );
4795
4796    // Now advance the chain by the pre-NU7 default expiry delta; even though a record for the transaction that created
4797    // `spent_outpoint` exists in the wallet database, the transaction can't be enhanced because
4798    // the outpoint was fake. Advancing the chain will cause the request for enhancement to expire.
4799    for _ in 0..BLOSSOM_DEFAULT_TX_EXPIRY_DELTA {
4800        st.generate_next_block(
4801            &dfvk,
4802            AddressType::DefaultExternal,
4803            Zatoshis::const_from_u64(10000),
4804        );
4805    }
4806    st.scan_cached_blocks(
4807        scan_result.scanned_range().end,
4808        usize::try_from(BLOSSOM_DEFAULT_TX_EXPIRY_DELTA).unwrap(),
4809    );
4810
4811    // Simulate the situation where the enhancement request results in `TxidNotRecognized`
4812    st.wallet_mut()
4813        .set_transaction_status(
4814            TxId::from_bytes(*spent_outpoint.hash()),
4815            data_api::TransactionStatus::TxidNotRecognized,
4816        )
4817        .unwrap();
4818
4819    // Verify that the transaction enhancement request for the invalid txid has been deleted.
4820    let requests = st.wallet().transaction_data_requests().unwrap();
4821    assert!(
4822        !requests.iter().any(|req| req
4823            == &TransactionDataRequest::Enhancement(TxId::from_bytes(*spent_outpoint.hash())))
4824    );
4825}
4826
4827// FIXME: This requires fixes to the test framework.
4828#[allow(dead_code)]
4829pub fn birthday_in_anchor_shard<T: ShieldedPoolTester>(
4830    ds_factory: impl DataStoreFactory,
4831    cache: impl TestCache,
4832) {
4833    // Set up the following situation:
4834    //
4835    //        |<------ 500 ------->|<--- 10 --->|<--- 10 --->|
4836    // last_shard_start   wallet_birthday  received_tx  anchor_height
4837    //
4838    // We set the Sapling and Orchard frontiers at the birthday block initial state to 1234
4839    // notes beyond the end of the first shard.
4840    let frontier_tree_size: u32 = (0x1 << 16) + 1234;
4841    let mut st = TestBuilder::new()
4842        .with_data_store_factory(ds_factory)
4843        .with_block_cache(cache)
4844        .with_initial_chain_state(|rng, network| {
4845            let birthday_height = network.activation_height(NetworkUpgrade::Nu5).unwrap() + 1000;
4846
4847            // Construct a fake chain state for the end of the block with the given
4848            // birthday_offset from the Nu5 birthday.
4849            let (prior_sapling_roots, sapling_initial_tree) =
4850                Frontier::random_with_prior_subtree_roots(
4851                    rng,
4852                    frontier_tree_size.into(),
4853                    NonZeroU8::new(16).unwrap(),
4854                );
4855            // There will only be one prior root
4856            let prior_sapling_roots = prior_sapling_roots
4857                .into_iter()
4858                .map(|root| CommitmentTreeRoot::from_parts(birthday_height - 500, root))
4859                .collect::<Vec<_>>();
4860
4861            #[cfg(feature = "orchard")]
4862            let (prior_orchard_roots, orchard_initial_tree) =
4863                Frontier::random_with_prior_subtree_roots(
4864                    rng,
4865                    frontier_tree_size.into(),
4866                    NonZeroU8::new(16).unwrap(),
4867                );
4868            // There will only be one prior root
4869            #[cfg(feature = "orchard")]
4870            let prior_orchard_roots = prior_orchard_roots
4871                .into_iter()
4872                .map(|root| CommitmentTreeRoot::from_parts(birthday_height - 500, root))
4873                .collect::<Vec<_>>();
4874
4875            // Ironwood is not active at these test heights, so its tree is empty.
4876            #[cfg(feature = "orchard")]
4877            let ironwood_initial_tree = Frontier::empty();
4878
4879            InitialChainState {
4880                chain_state: ChainState::new(
4881                    birthday_height - 1,
4882                    BlockHash([5; 32]),
4883                    sapling_initial_tree,
4884                    #[cfg(feature = "orchard")]
4885                    orchard_initial_tree,
4886                    #[cfg(feature = "orchard")]
4887                    ironwood_initial_tree,
4888                ),
4889                prior_sapling_roots,
4890                #[cfg(feature = "orchard")]
4891                prior_orchard_roots,
4892            }
4893        })
4894        .with_account_having_current_birthday()
4895        .build();
4896
4897    // Generate 9 blocks that have no value for us, starting at the birthday height.
4898    let not_our_value = Zatoshis::const_from_u64(10000);
4899    let not_our_key = T::random_fvk(st.rng_mut());
4900    let (initial_height, _, _) =
4901        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
4902    for _ in 1..9 {
4903        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
4904    }
4905
4906    // Now, generate a block that belongs to our wallet
4907    let (received_tx_height, _, _) = st.generate_next_block(
4908        &T::test_account_fvk(&st),
4909        AddressType::DefaultExternal,
4910        Zatoshis::const_from_u64(500000),
4911    );
4912
4913    // Generate some more blocks to get above our anchor height
4914    for _ in 0..15 {
4915        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
4916    }
4917
4918    // Scan a block range that includes our received note, but skips some blocks we need to
4919    // make it spendable.
4920    st.scan_cached_blocks(initial_height + 5, 20);
4921
4922    // Verify that the received note is not considered spendable
4923    let account = st.test_account().unwrap();
4924    let account_id = account.id();
4925    let spendable = T::select_spendable_notes(
4926        &st,
4927        account_id,
4928        TargetValue::AtLeast(Zatoshis::const_from_u64(300000)),
4929        TargetHeight::from(received_tx_height + 10),
4930        ConfirmationsPolicy::default(),
4931        &[],
4932    )
4933    .unwrap();
4934
4935    assert_eq!(spendable.len(), 0);
4936
4937    // Scan the blocks we skipped
4938    st.scan_cached_blocks(initial_height, 5);
4939
4940    // Verify that the received note is now considered spendable
4941    let spendable = T::select_spendable_notes(
4942        &st,
4943        account_id,
4944        TargetValue::AtLeast(Zatoshis::const_from_u64(300000)),
4945        TargetHeight::from(received_tx_height + 10),
4946        ConfirmationsPolicy::default(),
4947        &[],
4948    )
4949    .unwrap();
4950
4951    assert_eq!(spendable.len(), 1);
4952}
4953
4954/// A gap in scanned coverage directly below the policy depth withholds the anchor: the wallet
4955/// cannot know that its latest checkpoint carries the tree state at that depth. Scanning the
4956/// gap restores the anchor without any new checkpoint, since the gap's blocks add no
4957/// commitments.
4958pub fn checkpoint_gaps<T: ShieldedPoolTester, Dsf: DataStoreFactory>(
4959    ds_factory: Dsf,
4960    cache: impl TestCache,
4961) {
4962    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
4963
4964    st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(500000));
4965
4966    let account = st.test_account().cloned().unwrap();
4967    let birthday = account.birthday().height();
4968    let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
4969    let not_our_value = Zatoshis::const_from_u64(10000);
4970
4971    // Nine empty blocks, then a block carrying a foreign output. Scanning only the last leaves
4972    // the wallet with checkpoints at `birthday` and `birthday + 10` and no scanned coverage in
4973    // between.
4974    const GAP_BLOCKS: u32 = 9;
4975    for _ in 0..GAP_BLOCKS {
4976        st.generate_empty_block();
4977    }
4978    let (checkpoint_above_gap, _, _) =
4979        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
4980    assert_eq!(checkpoint_above_gap, birthday + GAP_BLOCKS + 1);
4981    st.scan_cached_blocks(checkpoint_above_gap, 1);
4982
4983    let selection_policy = ConfirmationsPolicy::new_unchecked(
4984        1,
4985        5,
4986        #[cfg(feature = "transparent-inputs")]
4987        false,
4988    );
4989    let spend_policy = ConfirmationsPolicy::new_symmetrical_unchecked(
4990        5,
4991        #[cfg(feature = "transparent-inputs")]
4992        false,
4993    );
4994    let input_selector = GreedyInputSelector::<Dsf::DataStore>::new();
4995    let change_strategy =
4996        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
4997    let to = T::fvk_default_address(&not_our_key).to_zcash_address(st.network());
4998    let request = || {
4999        TransactionRequest::new(vec![Payment::without_memo(
5000            to.clone(),
5001            Zatoshis::const_from_u64(10000),
5002        )])
5003        .unwrap()
5004    };
5005
5006    // The policy depth lies inside the gap: there is no anchor, so nothing is selectable and
5007    // a spend is refused rather than built against the older checkpoint.
5008    let spendable = T::select_spendable_notes(
5009        &st,
5010        account.id(),
5011        TargetValue::AtLeast(Zatoshis::const_from_u64(300000)),
5012        TargetHeight::from(birthday + 5),
5013        selection_policy,
5014        &[],
5015    )
5016    .unwrap();
5017    assert!(
5018        spendable.is_empty(),
5019        "the policy depth lies in the unscanned gap, so there is no anchor"
5020    );
5021    assert_matches!(
5022        st.spend(
5023            &input_selector,
5024            &change_strategy,
5025            account.usk(),
5026            request(),
5027            OvkPolicy::Sender,
5028            spend_policy,
5029        ),
5030        Err(Error::ScanRequired)
5031    );
5032
5033    // Scanning the gap restores the anchor: the checkpoint at `birthday` carries the tree
5034    // state at every height through `birthday + 9`.
5035    st.scan_cached_blocks(birthday + 1, GAP_BLOCKS as usize);
5036
5037    let spendable = T::select_spendable_notes(
5038        &st,
5039        account.id(),
5040        TargetValue::AtLeast(Zatoshis::const_from_u64(300000)),
5041        TargetHeight::from(birthday + 5),
5042        selection_policy,
5043        &[],
5044    )
5045    .unwrap();
5046    assert_eq!(spendable.len(), 1);
5047    assert_matches!(
5048        st.spend(
5049            &input_selector,
5050            &change_strategy,
5051            account.usk(),
5052            request(),
5053            OvkPolicy::Sender,
5054            spend_policy,
5055        ),
5056        Ok(_)
5057    );
5058}
5059
5060/// Reads, from any pool's note commitment tree, whether a witness for `note_position` as of
5061/// `anchor_height` is still constructible, the set of surviving checkpoint heights, and the set
5062/// of retained-anchor heights.
5063#[allow(clippy::type_complexity)]
5064fn tree_anchor_state<S, const DEPTH: u8, const SHARD_HEIGHT: u8>(
5065    tree: &mut ShardTree<S, DEPTH, SHARD_HEIGHT>,
5066    note_position: Position,
5067    anchor_height: BlockHeight,
5068) -> Result<(bool, BTreeSet<BlockHeight>, BTreeSet<BlockHeight>), ShardTreeError<S::Error>>
5069where
5070    S: ShardStore<CheckpointId = BlockHeight>,
5071    S::H: Hashable + Clone + PartialEq,
5072{
5073    let witness_computable = tree
5074        .witness_at_checkpoint_id(note_position, &anchor_height)?
5075        .is_some();
5076    let retained = tree
5077        .store()
5078        .retained_checkpoints()
5079        .map_err(ShardTreeError::Storage)?;
5080    let checkpoint_count = tree
5081        .store()
5082        .checkpoint_count()
5083        .map_err(ShardTreeError::Storage)?;
5084    let mut survivors = BTreeSet::new();
5085    tree.store()
5086        .for_each_checkpoint(checkpoint_count, |cid, _| {
5087            survivors.insert(*cid);
5088            Ok(())
5089        })
5090        .map_err(ShardTreeError::Storage)?;
5091    Ok((witness_computable, survivors, retained))
5092}
5093
5094/// A wallet-level test for note-commitment-tree *anchor retention*: once NU6.3 (Ironwood) is
5095/// active, checkpoints on the anchor-retention interval are retained as durable anchors, exempt
5096/// from the ordinary `PRUNING_DEPTH`-checkpoint pruning budget, so that their roots and the
5097/// witnesses anchored to them remain computable even after they age far behind the chain tip.
5098///
5099/// The interval is supplied by the caller (the pruning depth is read from
5100/// `crate::data_api::ll::wallet`, so this test tracks whatever value the implementation defines).
5101/// Passing a short interval keeps the test cheap: the scan must reach a boundary more than
5102/// `PRUNING_DEPTH` checkpoints behind the tip, which at the ZIP 318 interval means generating
5103/// several hundred blocks.
5104///
5105/// The test:
5106/// - Activates NU6.3 from the Sapling activation height, so anchor retention is live and its
5107///   floor equals the account birthday.
5108/// - Receives a single note early, capturing its note-commitment-tree position.
5109/// - Scans forward in a single batch until an interval-aligned anchor has aged *more than
5110///   `PRUNING_DEPTH` checkpoints* behind the chain tip — so it would have been pruned to enforce
5111///   the checkpoint budget had it not been retained.
5112/// - Proves survival behaviorally: a witness for the received note *as of that buried anchor* is
5113///   still constructible (it would be `None` if the anchor checkpoint had been pruned).
5114/// - Confirms the anchors did not consume the pruning budget: the ordinary checkpoint immediately
5115///   above the buried anchor *was* pruned, exactly the interval-aligned anchors at/above the floor
5116///   are retained, and the full `PRUNING_DEPTH` window of checkpoints at the chain tip survives.
5117pub fn anchor_checkpoints_retained_across_deep_scan<
5118    T: ShieldedPoolTester,
5119    Dsf: DataStoreFactory,
5120>(
5121    ds_factory: Dsf,
5122    cache: impl TestCache,
5123    interval: AnchorRetentionInterval,
5124) {
5125    let interval_blocks = interval.block_count().get();
5126
5127    // A network on which NU6.3 (Ironwood) is active from the Sapling activation height, so anchor
5128    // retention is live with its floor at the account birthday.
5129    let activation = BlockHeight::from_u32(100_000);
5130    let ironwood_active_network = LocalNetwork {
5131        nu6: Some(activation),
5132        nu6_1: Some(activation),
5133        nu6_2: Some(activation),
5134        nu6_3: Some(activation),
5135        ..TestBuilder::<(), ()>::DEFAULT_NETWORK
5136    };
5137
5138    let mut st = TestDsl::from(
5139        TestBuilder::new()
5140            .with_network(ironwood_active_network)
5141            .with_data_store_factory(ds_factory)
5142            .with_block_cache(cache)
5143            .with_anchor_retention_interval(interval)
5144            .with_account_from_sapling_activation(BlockHash([0; 32])),
5145    )
5146    .build::<T>();
5147
5148    // Receive a single note; its position is captured after it is deeply confirmed, below.
5149    let (received_height, _, _) =
5150        st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(500_000));
5151    let received = u32::from(received_height);
5152    let floor = u32::from(activation);
5153
5154    // The first interval-aligned anchor height at or above the retention floor and strictly above
5155    // the received note, so the note's position precedes the anchor's checkpoint.
5156    let mut anchor = u32::from(
5157        anchor_grid(st.network(), interval).boundary_at_or_above(BlockHeight::from(floor)),
5158    );
5159    while anchor <= received {
5160        anchor += interval_blocks;
5161    }
5162
5163    // Scan forward in a single batch so the anchor ages more than `PRUNING_DEPTH` checkpoints
5164    // behind the tip: without retention it would be pruned to enforce the checkpoint budget.
5165    let tip = anchor + PRUNING_DEPTH + 10;
5166
5167    // Fillers pay a non-wallet key, so each block still adds a commitment (and thus a checkpoint)
5168    // without changing the received note's position or the wallet's spendable set.
5169    let not_our_fvk = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
5170    let filler_count = tip - received;
5171    for _ in 0..filler_count {
5172        st.generate_next_block(
5173            &not_our_fvk,
5174            AddressType::DefaultExternal,
5175            Zatoshis::const_from_u64(10_000),
5176        );
5177    }
5178    st.scan_cached_blocks(received_height + 1, filler_count as usize);
5179
5180    // Capture the received note's commitment-tree position now that it is deeply confirmed.
5181    let account_id = st.get_account().id();
5182    let spendable = T::select_spendable_notes(
5183        &st,
5184        account_id,
5185        TargetValue::AtLeast(Zatoshis::const_from_u64(1)),
5186        TargetHeight::from(BlockHeight::from(tip + 1)),
5187        ConfirmationsPolicy::MIN,
5188        &[],
5189    )
5190    .unwrap();
5191    let note_position = spendable
5192        .first()
5193        .expect("the received note is spendable")
5194        .note_commitment_tree_position();
5195
5196    let anchor_height = BlockHeight::from(anchor);
5197    let (witness_computable, survivors, retained) = match T::SHIELDED_PROTOCOL {
5198        ShieldedPool::Sapling => st
5199            .wallet_mut()
5200            .with_sapling_tree_mut(|tree| tree_anchor_state(tree, note_position, anchor_height))
5201            .unwrap(),
5202        #[cfg(feature = "orchard")]
5203        ShieldedPool::Orchard => st
5204            .wallet_mut()
5205            .with_orchard_tree_mut(|tree| tree_anchor_state(tree, note_position, anchor_height))
5206            .unwrap(),
5207        other => {
5208            unreachable!("anchor retention test covers only Sapling and Orchard, got {other:?}")
5209        }
5210    };
5211
5212    // The witness for the received note, anchored at the buried anchor, must still be computable —
5213    // impossible if that checkpoint had been pruned.
5214    assert!(
5215        witness_computable,
5216        "a witness for the received note as of the retained anchor at height {anchor} \
5217         must still be constructible",
5218    );
5219
5220    // Exactly the interval-aligned checkpoints at or above the retention floor are retained.
5221    let expected_anchors: BTreeSet<BlockHeight> = (floor..=tip)
5222        .map(BlockHeight::from)
5223        .filter(|h| anchor_grid(st.network(), interval).is_boundary(*h))
5224        .collect();
5225    assert_eq!(
5226        retained, expected_anchors,
5227        "only the interval-aligned anchors at/above the NU6.3 floor should be retained",
5228    );
5229
5230    // The buried anchor survives, but the ordinary checkpoint immediately above it was pruned — so
5231    // its survival is due to retention, not to pruning having failed to run.
5232    assert!(
5233        survivors.contains(&anchor_height),
5234        "the buried anchor checkpoint must survive",
5235    );
5236    assert!(
5237        !survivors.contains(&BlockHeight::from(anchor + 1)),
5238        "the ordinary checkpoint just above the buried anchor must have been pruned",
5239    );
5240
5241    // The anchors did not consume the pruning budget: the full `PRUNING_DEPTH` window of
5242    // checkpoints at the chain tip is still retained.
5243    for h in (tip - PRUNING_DEPTH + 1)..=tip {
5244        assert!(
5245            survivors.contains(&BlockHeight::from(h)),
5246            "checkpoint at tip-window height {h} must be retained",
5247        );
5248    }
5249}
5250
5251/// A grid boundary that lands on a block containing no note commitments in ANY pool must still be
5252/// checkpointed and retained. Scanning checkpoints a block only at its last note commitment, so
5253/// such a block produces no checkpoint of its own in any tree and the cross-pool ensure step has
5254/// nothing to copy; unless the retained heights are ensured explicitly, the retained grid gains a
5255/// permanent hole there — on mainnet a sizeable fraction of blocks carry no shielded outputs —
5256/// and a ZIP 318 crossing anchored to the hole can never be proved.
5257///
5258/// The scan must cover the boundaries in a SINGLE batch: scanning block-by-block masks the gap,
5259/// because every batch checkpoints its starting frontier, so each height gets a checkpoint as the
5260/// next block's batch begins.
5261#[cfg(feature = "orchard")]
5262pub fn empty_boundary_blocks_are_checkpointed_and_retained<
5263    T: ShieldedPoolTester,
5264    Dsf: DataStoreFactory,
5265>(
5266    ds_factory: Dsf,
5267    cache: impl TestCache,
5268    interval: AnchorRetentionInterval,
5269) {
5270    let interval_blocks = interval.block_count().get();
5271
5272    // A network on which NU6.3 (Ironwood) is active from the Sapling activation height, so anchor
5273    // retention is live with its floor at the account birthday.
5274    let activation = BlockHeight::from_u32(100_000);
5275    let ironwood_active_network = LocalNetwork {
5276        nu6: Some(activation),
5277        nu6_1: Some(activation),
5278        nu6_2: Some(activation),
5279        nu6_3: Some(activation),
5280        ..TestBuilder::<(), ()>::DEFAULT_NETWORK
5281    };
5282
5283    let mut st = TestDsl::from(
5284        TestBuilder::new()
5285            .with_network(ironwood_active_network)
5286            .with_data_store_factory(ds_factory)
5287            .with_block_cache(cache)
5288            .with_anchor_retention_interval(interval)
5289            .with_account_from_sapling_activation(BlockHash([0; 32])),
5290    )
5291    .build::<T>();
5292
5293    // Receive a single note; its position is captured after the batch scan, below.
5294    let (received_height, _, _) =
5295        st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(500_000));
5296    let received = u32::from(received_height);
5297
5298    // The first two boundaries strictly above the received note, plus slack so neither boundary
5299    // is the final block of the batch.
5300    let first_boundary = {
5301        let mut b = u32::from(anchor_grid(st.network(), interval).boundary_at_or_above(activation));
5302        while b <= received {
5303            b += interval_blocks;
5304        }
5305        b
5306    };
5307    let boundaries = [first_boundary, first_boundary + interval_blocks];
5308    let tip = boundaries[1] + 2;
5309
5310    // Fillers pay a non-wallet key so that ordinary blocks each carry a commitment, but every
5311    // BOUNDARY block is generated empty: no note commitments in any pool, and so no checkpoint
5312    // of its own.
5313    let not_our_fvk = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
5314    for height in (received + 1)..=tip {
5315        let generated =
5316            if anchor_grid(st.network(), interval).is_boundary(BlockHeight::from_u32(height)) {
5317                st.generate_empty_block().0
5318            } else {
5319                st.generate_next_block(
5320                    &not_our_fvk,
5321                    AddressType::DefaultExternal,
5322                    Zatoshis::const_from_u64(10_000),
5323                )
5324                .0
5325            };
5326        assert_eq!(u32::from(generated), height, "cache height must track");
5327    }
5328    // One batch, covering both boundaries.
5329    st.scan_cached_blocks(received_height + 1, (tip - received) as usize);
5330
5331    // Capture the received note's commitment-tree position.
5332    let account_id = st.get_account().id();
5333    let spendable = T::select_spendable_notes(
5334        &st,
5335        account_id,
5336        TargetValue::AtLeast(Zatoshis::const_from_u64(1)),
5337        TargetHeight::from(BlockHeight::from_u32(tip + 1)),
5338        ConfirmationsPolicy::MIN,
5339        &[],
5340    )
5341    .unwrap();
5342    let note_position = spendable
5343        .first()
5344        .expect("the received note is spendable")
5345        .note_commitment_tree_position();
5346
5347    for boundary in boundaries {
5348        let anchor_height = BlockHeight::from_u32(boundary);
5349        let (witness_computable, survivors, retained) = match T::SHIELDED_PROTOCOL {
5350            ShieldedPool::Sapling => st
5351                .wallet_mut()
5352                .with_sapling_tree_mut(|tree| tree_anchor_state(tree, note_position, anchor_height))
5353                .unwrap(),
5354            ShieldedPool::Orchard => st
5355                .wallet_mut()
5356                .with_orchard_tree_mut(|tree| tree_anchor_state(tree, note_position, anchor_height))
5357                .unwrap(),
5358            other => {
5359                unreachable!("this test covers only Sapling and Orchard, got {other:?}")
5360            }
5361        };
5362
5363        assert!(
5364            survivors.contains(&anchor_height),
5365            "the empty boundary block at height {boundary} must be checkpointed",
5366        );
5367        assert!(
5368            retained.contains(&anchor_height),
5369            "the checkpoint at the empty boundary height {boundary} must be retained",
5370        );
5371        // The checkpoint must be USABLE as an anchor: it commits to the tree state as of the last
5372        // note commitment at or before the boundary, so the received note has a witness there.
5373        assert!(
5374            witness_computable,
5375            "a witness for the received note as of the empty boundary at height {boundary} \
5376             must be constructible",
5377        );
5378    }
5379
5380    // The pool-crossing destination tree gains the same retained checkpoints even though it holds
5381    // no commitments at all, keeping the cross-pool checkpoint sets consistent.
5382    let ironwood_retained = st
5383        .wallet_mut()
5384        .with_ironwood_tree_mut(|tree| {
5385            tree.store()
5386                .retained_checkpoints()
5387                .map_err(ShardTreeError::Storage)
5388        })
5389        .unwrap()
5390        .expect("the data store maintains an Ironwood tree");
5391    for boundary in boundaries {
5392        assert!(
5393            ironwood_retained.contains(&BlockHeight::from_u32(boundary)),
5394            "the Ironwood tree must retain the empty boundary at height {boundary}",
5395        );
5396    }
5397}
5398
5399/// The order in which [`retained_boundaries_below_window_are_usable_anchors`] scans the batch
5400/// that holds the anchor-retention boundaries.
5401#[cfg(feature = "orchard")]
5402#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5403pub enum BoundaryScanOrder {
5404    /// The wallet learns of a distant chain tip, then scans the batch that holds the boundaries.
5405    /// The boundaries lie below the checkpoint window.
5406    Forward,
5407    /// The wallet scans the checkpoint window at the chain tip first, which fills the checkpoint
5408    /// budget, and then scans the older batch that holds the boundaries.
5409    TipFirst,
5410}
5411
5412/// Whether a tree holds a checkpoint at an anchor height, retains it, and can compute a note's
5413/// witness at it.
5414#[cfg(feature = "orchard")]
5415#[derive(Debug, PartialEq, Eq)]
5416struct RetainedAnchorState {
5417    checkpointed: bool,
5418    retained: bool,
5419    witness_computable: bool,
5420}
5421
5422/// Returns the [`RetainedAnchorState`] of `tree` at `anchor_height` for the note at
5423/// `note_position`. A witness that the tree cannot compute, for any reason, counts as not
5424/// computable.
5425#[cfg(feature = "orchard")]
5426fn retained_anchor_state<S, const DEPTH: u8, const SHARD_HEIGHT: u8>(
5427    tree: &mut ShardTree<S, DEPTH, SHARD_HEIGHT>,
5428    note_position: Position,
5429    anchor_height: BlockHeight,
5430) -> Result<RetainedAnchorState, ShardTreeError<S::Error>>
5431where
5432    S: ShardStore<CheckpointId = BlockHeight>,
5433    S::H: Hashable + Clone + PartialEq,
5434{
5435    let checkpointed = tree
5436        .store()
5437        .get_checkpoint(&anchor_height)
5438        .map_err(ShardTreeError::Storage)?
5439        .is_some();
5440    let retained = tree
5441        .store()
5442        .retained_checkpoints()
5443        .map_err(ShardTreeError::Storage)?
5444        .contains(&anchor_height);
5445    let witness_computable = matches!(
5446        tree.witness_at_checkpoint_id(note_position, &anchor_height),
5447        Ok(Some(_))
5448    );
5449    Ok(RetainedAnchorState {
5450        checkpointed,
5451        retained,
5452        witness_computable,
5453    })
5454}
5455
5456/// Returns, for each retained checkpoint of `tree`, whether the tree can compute its root.
5457#[cfg(feature = "orchard")]
5458fn retained_checkpoint_roots<S, const DEPTH: u8, const SHARD_HEIGHT: u8>(
5459    tree: &mut ShardTree<S, DEPTH, SHARD_HEIGHT>,
5460) -> Result<BTreeMap<BlockHeight, bool>, ShardTreeError<S::Error>>
5461where
5462    S: ShardStore<CheckpointId = BlockHeight>,
5463    S::H: Hashable + Clone + PartialEq,
5464{
5465    let retained = tree
5466        .store()
5467        .retained_checkpoints()
5468        .map_err(ShardTreeError::Storage)?;
5469    let mut roots = BTreeMap::new();
5470    for height in retained {
5471        let computable = matches!(tree.root_at_checkpoint_id(&height), Ok(Some(_)));
5472        roots.insert(height, computable);
5473    }
5474    Ok(roots)
5475}
5476
5477/// Anchor-retention boundaries that lie below the checkpoint window, on blocks that carry no
5478/// note commitment, are checkpointed and retained in every tree, and each such checkpoint is a
5479/// usable anchor: its root is computable, and the received note has a witness there. This holds
5480/// whether the wallet scans the boundaries before or after the checkpoint window at the tip.
5481#[cfg(feature = "orchard")]
5482pub fn retained_boundaries_below_window_are_usable_anchors<
5483    T: ShieldedPoolTester,
5484    Dsf: DataStoreFactory,
5485>(
5486    ds_factory: Dsf,
5487    cache: impl TestCache,
5488    interval: AnchorRetentionInterval,
5489    scan_order: BoundaryScanOrder,
5490) {
5491    /// The number of blocks between the last boundary and the bottom of the checkpoint window.
5492    const BLOCKS_BELOW_WINDOW: u32 = 20;
5493    /// The number of blocks by which the chain tip advances after the wallet scans the
5494    /// checkpoint window, in the tip-first order. The advance creates enough checkpoints to
5495    /// exceed the checkpoint budget, so the oldest checkpoints are pruned.
5496    const TIP_ADVANCE: u32 = 20;
5497
5498    let interval_blocks = interval.block_count().get();
5499
5500    // A network on which NU6.3 (Ironwood) is active from the Sapling activation height, so anchor
5501    // retention is live with its floor at the account birthday.
5502    let activation = BlockHeight::from_u32(100_000);
5503    let ironwood_active_network = LocalNetwork {
5504        nu6: Some(activation),
5505        nu6_1: Some(activation),
5506        nu6_2: Some(activation),
5507        nu6_3: Some(activation),
5508        ..TestBuilder::<(), ()>::DEFAULT_NETWORK
5509    };
5510
5511    let mut st = TestDsl::from(
5512        TestBuilder::new()
5513            .with_network(ironwood_active_network)
5514            .with_data_store_factory(ds_factory)
5515            .with_block_cache(cache)
5516            .with_anchor_retention_interval(interval)
5517            .with_account_from_sapling_activation(BlockHash([0; 32])),
5518    )
5519    .build::<T>();
5520
5521    let (received_height, _, _) =
5522        st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(500_000));
5523    let received = u32::from(received_height);
5524    let account_id = st.get_account().id();
5525    let note_position = T::select_spendable_notes(
5526        &st,
5527        account_id,
5528        TargetValue::AtLeast(Zatoshis::const_from_u64(1)),
5529        TargetHeight::from(received_height + 1),
5530        ConfirmationsPolicy::MIN,
5531        &[],
5532    )
5533    .unwrap()
5534    .first()
5535    .expect("the received note is selectable")
5536    .note_commitment_tree_position();
5537
5538    // Boundaries strictly above the received note. Every boundary block is empty, so it has no
5539    // checkpoint of its own, and the block below it carries between one and
5540    // `MAX_OUTPUTS_BELOW_BOUNDARY` commitments, so the leaf that ends it falls at varying
5541    // positions within its subtree.
5542    const BOUNDARY_COUNT: u32 = 6;
5543    const MAX_OUTPUTS_BELOW_BOUNDARY: u32 = 3;
5544    let first_boundary = {
5545        let mut b = u32::from(anchor_grid(st.network(), interval).boundary_at_or_above(activation));
5546        while b <= received + 1 {
5547            b += interval_blocks;
5548        }
5549        b
5550    };
5551    let boundaries = (0..BOUNDARY_COUNT)
5552        .map(|i| first_boundary + i * interval_blocks)
5553        .collect::<Vec<_>>();
5554    let batch_end = boundaries[boundaries.len() - 1] + 2;
5555    let tip = batch_end + BLOCKS_BELOW_WINDOW + PRUNING_DEPTH;
5556
5557    // Above the boundary batch every block carries a commitment, so scanning the checkpoint
5558    // window creates a checkpoint at each of its heights and exceeds the checkpoint budget.
5559    let not_our_fvk = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
5560    let filler = || {
5561        FakeCompactOutput::new(
5562            not_our_fvk.clone(),
5563            AddressType::DefaultExternal,
5564            Zatoshis::const_from_u64(10_000),
5565        )
5566    };
5567    for height in (received + 1)..=(tip + TIP_ADVANCE) {
5568        let below_batch_end = height <= batch_end;
5569        let generated = if below_batch_end
5570            && anchor_grid(st.network(), interval).is_boundary(BlockHeight::from_u32(height))
5571        {
5572            st.generate_empty_block().0
5573        } else if let Some(index) = boundaries
5574            .iter()
5575            .position(|boundary| below_batch_end && *boundary == height + 1)
5576        {
5577            let output_count = (index as u32 % MAX_OUTPUTS_BELOW_BOUNDARY) + 1;
5578            let outputs = (0..output_count).map(|_| filler()).collect::<Vec<_>>();
5579            st.generate_next_block_multi(&outputs).0
5580        } else {
5581            st.generate_next_block_multi(&[filler()]).0
5582        };
5583        assert_eq!(u32::from(generated), height, "cache height must track");
5584    }
5585
5586    st.wallet_mut()
5587        .update_chain_tip(BlockHeight::from_u32(tip))
5588        .unwrap();
5589    let window_start = tip - (PRUNING_DEPTH - 1);
5590    if scan_order == BoundaryScanOrder::TipFirst {
5591        st.scan_cached_blocks(BlockHeight::from_u32(window_start), PRUNING_DEPTH as usize);
5592        st.wallet_mut()
5593            .update_chain_tip(BlockHeight::from_u32(tip + TIP_ADVANCE))
5594            .unwrap();
5595        st.scan_cached_blocks(BlockHeight::from_u32(tip + 1), TIP_ADVANCE as usize);
5596        let min_checkpoint = match T::SHIELDED_PROTOCOL {
5597            ShieldedPool::Sapling => st
5598                .wallet_mut()
5599                .with_sapling_tree_mut(|tree| {
5600                    tree.store()
5601                        .min_checkpoint_id()
5602                        .map_err(ShardTreeError::Storage)
5603                })
5604                .unwrap(),
5605            ShieldedPool::Orchard => st
5606                .wallet_mut()
5607                .with_orchard_tree_mut(|tree| {
5608                    tree.store()
5609                        .min_checkpoint_id()
5610                        .map_err(ShardTreeError::Storage)
5611                })
5612                .unwrap(),
5613            other => {
5614                unreachable!("this test covers only Sapling and Orchard, got {other:?}")
5615            }
5616        };
5617        assert!(
5618            min_checkpoint > Some(BlockHeight::from_u32(batch_end)),
5619            "test invariant: the oldest checkpoint must lie above the boundary batch, \
5620             found {min_checkpoint:?}",
5621        );
5622    }
5623    // One batch, covering both boundaries, entirely below the checkpoint window.
5624    st.scan_cached_blocks(received_height + 1, (batch_end - received) as usize);
5625
5626    for &boundary in &boundaries {
5627        let anchor_height = BlockHeight::from_u32(boundary);
5628        let state = match T::SHIELDED_PROTOCOL {
5629            ShieldedPool::Sapling => st
5630                .wallet_mut()
5631                .with_sapling_tree_mut(|tree| {
5632                    retained_anchor_state(tree, note_position, anchor_height)
5633                })
5634                .unwrap(),
5635            ShieldedPool::Orchard => st
5636                .wallet_mut()
5637                .with_orchard_tree_mut(|tree| {
5638                    retained_anchor_state(tree, note_position, anchor_height)
5639                })
5640                .unwrap(),
5641            other => {
5642                unreachable!("this test covers only Sapling and Orchard, got {other:?}")
5643            }
5644        };
5645        assert_eq!(
5646            state,
5647            RetainedAnchorState {
5648                checkpointed: true,
5649                retained: true,
5650                witness_computable: true,
5651            },
5652            "the empty boundary at height {boundary} must be a retained checkpoint at which the \
5653             received note has a witness ({scan_order:?})",
5654        );
5655    }
5656
5657    // Each callback must be a closure: `with_*_tree_mut` requires a callback that is generic over
5658    // the lifetime of the tree it receives, which a function item does not satisfy.
5659    #[allow(clippy::redundant_closure)]
5660    let roots = [
5661        (
5662            "Sapling",
5663            st.wallet_mut()
5664                .with_sapling_tree_mut(|tree| retained_checkpoint_roots(tree))
5665                .unwrap(),
5666        ),
5667        (
5668            "Orchard",
5669            st.wallet_mut()
5670                .with_orchard_tree_mut(|tree| retained_checkpoint_roots(tree))
5671                .unwrap(),
5672        ),
5673        (
5674            "Ironwood",
5675            st.wallet_mut()
5676                .with_ironwood_tree_mut(|tree| retained_checkpoint_roots(tree))
5677                .unwrap()
5678                .expect("the data store maintains an Ironwood tree"),
5679        ),
5680    ];
5681    for (pool, roots) in roots {
5682        for &boundary in &boundaries {
5683            assert!(
5684                roots.contains_key(&BlockHeight::from_u32(boundary)),
5685                "the {pool} tree must retain the boundary at height {boundary} ({scan_order:?})",
5686            );
5687        }
5688        let unusable = roots
5689            .iter()
5690            .filter(|(_, computable)| !**computable)
5691            .map(|(height, _)| *height)
5692            .collect::<Vec<_>>();
5693        assert!(
5694            unusable.is_empty(),
5695            "the {pool} tree cannot compute the root of retained checkpoints {unusable:?} \
5696             ({scan_order:?})",
5697        );
5698    }
5699}
5700
5701#[cfg(feature = "orchard")]
5702pub fn pool_crossing_required<P0: ShieldedPoolTester, P1: ShieldedPoolTester>(
5703    ds_factory: impl DataStoreFactory,
5704    cache: impl TestCache,
5705) {
5706    // TODO: Allow for Orchard activation after Sapling
5707    // Here we choose P0, but this has no effect since we supply the viewing keys
5708    // and generate the blocks directly on the state.
5709    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<P0>();
5710
5711    let account = st.test_account().cloned().unwrap();
5712
5713    let p0_fvk = P0::test_account_fvk(&st);
5714
5715    let p1_fvk = P1::test_account_fvk(&st);
5716    let p1_to = P1::fvk_default_address(&p1_fvk);
5717
5718    let note_value = Zatoshis::const_from_u64(350000);
5719    st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
5720    st.scan_cached_blocks(account.birthday().height(), 2);
5721
5722    let initial_balance = note_value;
5723    assert_eq!(st.get_total_balance(account.id()), initial_balance);
5724    assert_eq!(
5725        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
5726        initial_balance
5727    );
5728
5729    let transfer_amount = Zatoshis::const_from_u64(200000);
5730    let p0_to_p1 = TransactionRequest::new(vec![Payment::without_memo(
5731        p1_to.to_zcash_address(st.network()),
5732        transfer_amount,
5733    )])
5734    .unwrap();
5735
5736    let input_selector = GreedyInputSelector::new();
5737    let change_strategy =
5738        single_output_change_strategy(StandardFeeRule::Zip317, None, P1::SHIELDED_PROTOCOL);
5739    let proposal0 = st
5740        .propose_transfer(
5741            account.id(),
5742            &input_selector,
5743            &change_strategy,
5744            p0_to_p1,
5745            ConfirmationsPolicy::MIN,
5746        )
5747        .unwrap();
5748
5749    let _min_target_height = proposal0.min_target_height();
5750    assert_eq!(proposal0.steps().len(), 1);
5751    let step0 = &proposal0.steps().head;
5752
5753    // We expect 4 logical actions, two per pool (due to padding).
5754    let expected_fee = Zatoshis::const_from_u64(20000);
5755    assert_eq!(step0.balance().fee_required(), expected_fee);
5756
5757    let expected_change = (note_value - transfer_amount - expected_fee).unwrap();
5758    let proposed_change = step0.balance().proposed_change();
5759    assert_eq!(proposed_change.len(), 1);
5760    let change_output = proposed_change.first().unwrap();
5761    // Since this is a cross-pool transfer, change will be sent to the preferred pool.
5762    assert_eq!(
5763        change_output.output_pool(),
5764        PoolType::Shielded(std::cmp::max(ShieldedPool::Sapling, ShieldedPool::Orchard))
5765    );
5766    assert_eq!(change_output.value(), expected_change);
5767
5768    let txids = st.create_proposed_expecting(&proposal0, 1);
5769
5770    let (h, _) = st.generate_next_block_including(txids[0]);
5771    st.scan_cached_blocks(h, 1);
5772
5773    assert_eq!(
5774        st.get_total_balance(account.id()),
5775        (initial_balance - expected_fee).unwrap()
5776    );
5777    assert_eq!(
5778        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
5779        (initial_balance - expected_fee).unwrap()
5780    );
5781}
5782
5783#[cfg(feature = "orchard")]
5784pub fn fully_funded_fully_private<P0: ShieldedPoolTester, P1: ShieldedPoolTester>(
5785    ds_factory: impl DataStoreFactory,
5786    cache: impl TestCache,
5787) {
5788    // TODO: Allow for Orchard activation after Sapling
5789    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<P0>();
5790
5791    let account = st.test_account().cloned().unwrap();
5792
5793    let p0_fvk = P0::test_account_fvk(&st);
5794
5795    let p1_fvk = P1::test_account_fvk(&st);
5796    let p1_to = P1::fvk_default_address(&p1_fvk);
5797
5798    let note_value = Zatoshis::const_from_u64(350000);
5799    st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
5800    st.generate_next_block(&p1_fvk, AddressType::DefaultExternal, note_value);
5801    st.scan_cached_blocks(account.birthday().height(), 2);
5802
5803    let initial_balance = (note_value * 2u64).unwrap();
5804    assert_eq!(st.get_total_balance(account.id()), initial_balance);
5805    assert_eq!(
5806        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
5807        initial_balance
5808    );
5809
5810    let transfer_amount = Zatoshis::const_from_u64(200000);
5811    let p0_to_p1 = TransactionRequest::new(vec![Payment::without_memo(
5812        p1_to.to_zcash_address(st.network()),
5813        transfer_amount,
5814    )])
5815    .unwrap();
5816
5817    let input_selector = GreedyInputSelector::new();
5818    // We set the default change output pool to P0, because we want to verify later that
5819    // change is actually sent to P1 (as the transaction is fully fundable from P1).
5820    let change_strategy =
5821        single_output_change_strategy(StandardFeeRule::Zip317, None, P0::SHIELDED_PROTOCOL);
5822    let proposal0 = st
5823        .propose_transfer(
5824            account.id(),
5825            &input_selector,
5826            &change_strategy,
5827            p0_to_p1,
5828            ConfirmationsPolicy::MIN,
5829        )
5830        .unwrap();
5831
5832    let _min_target_height = proposal0.min_target_height();
5833    assert_eq!(proposal0.steps().len(), 1);
5834    let step0 = &proposal0.steps().head;
5835
5836    // We expect 2 logical actions, since either pool can pay the full balance required
5837    // and note selection should choose the fully-private path.
5838    let expected_fee = Zatoshis::const_from_u64(10000);
5839    assert_eq!(step0.balance().fee_required(), expected_fee);
5840
5841    let expected_change = (note_value - transfer_amount - expected_fee).unwrap();
5842    let proposed_change = step0.balance().proposed_change();
5843    assert_eq!(proposed_change.len(), 1);
5844    let change_output = proposed_change.first().unwrap();
5845    // Since there are sufficient funds in either pool, change is kept in the same pool as
5846    // the source note (the target pool), and does not necessarily follow preference order.
5847    assert_eq!(
5848        change_output.output_pool(),
5849        PoolType::Shielded(P1::SHIELDED_PROTOCOL)
5850    );
5851    assert_eq!(change_output.value(), expected_change);
5852
5853    let txids = st.create_proposed_expecting(&proposal0, 1);
5854
5855    let (h, _) = st.generate_next_block_including(txids[0]);
5856    st.scan_cached_blocks(h, 1);
5857
5858    assert_eq!(
5859        st.get_total_balance(account.id()),
5860        (initial_balance - expected_fee).unwrap()
5861    );
5862    assert_eq!(
5863        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
5864        (initial_balance - expected_fee).unwrap()
5865    );
5866}
5867
5868#[cfg(all(feature = "orchard", feature = "transparent-inputs"))]
5869pub fn fully_funded_send_to_t<P0: ShieldedPoolTester, P1: ShieldedPoolTester>(
5870    ds_factory: impl DataStoreFactory,
5871    cache: impl TestCache,
5872) {
5873    // TODO: Allow for Orchard activation after Sapling
5874    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<P0>();
5875
5876    let account = st.test_account().cloned().unwrap();
5877
5878    let p0_fvk = P0::test_account_fvk(&st);
5879    let p1_fvk = P1::test_account_fvk(&st);
5880    let (p1_to, _) = account.usk().default_transparent_address();
5881
5882    let note_value = Zatoshis::const_from_u64(350000);
5883    st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
5884    st.generate_next_block(&p1_fvk, AddressType::DefaultExternal, note_value);
5885    st.scan_cached_blocks(account.birthday().height(), 2);
5886
5887    let initial_balance = (note_value * 2u64).unwrap();
5888    assert_eq!(st.get_total_balance(account.id()), initial_balance);
5889    assert_eq!(
5890        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
5891        initial_balance
5892    );
5893
5894    let transfer_amount = Zatoshis::const_from_u64(200000);
5895    let p0_to_p1 = TransactionRequest::new(vec![Payment::without_memo(
5896        Address::Transparent(p1_to).to_zcash_address(st.network()),
5897        transfer_amount,
5898    )])
5899    .unwrap();
5900
5901    let input_selector = GreedyInputSelector::new();
5902    // We set the default change output pool to P0, because we want to verify later that
5903    // change is actually sent to P1 (as the transaction is fully fundable from P1).
5904    let change_strategy =
5905        single_output_change_strategy(StandardFeeRule::Zip317, None, P0::SHIELDED_PROTOCOL);
5906    let proposal0 = st
5907        .propose_transfer(
5908            account.id(),
5909            &input_selector,
5910            &change_strategy,
5911            p0_to_p1,
5912            ConfirmationsPolicy::MIN,
5913        )
5914        .unwrap();
5915
5916    let _min_target_height = proposal0.min_target_height();
5917    assert_eq!(proposal0.steps().len(), 1);
5918    let step0 = &proposal0.steps().head;
5919
5920    // We expect 3 logical actions, one for the transparent output and two for the source pool.
5921    let expected_fee = Zatoshis::const_from_u64(15000);
5922    assert_eq!(step0.balance().fee_required(), expected_fee);
5923
5924    let expected_change = (note_value - transfer_amount - expected_fee).unwrap();
5925    let proposed_change = step0.balance().proposed_change();
5926    assert_eq!(proposed_change.len(), 1);
5927    let change_output = proposed_change.first().unwrap();
5928    // Since there are sufficient funds in either pool, change is kept in the same pool as
5929    // the source note (the target pool), and does not necessarily follow preference order.
5930    // The source note will always be sapling, as we spend Sapling funds preferentially.
5931    assert_eq!(change_output.output_pool(), PoolType::SAPLING);
5932    assert_eq!(change_output.value(), expected_change);
5933
5934    let txids = st.create_proposed_expecting(&proposal0, 1);
5935
5936    let (h, _) = st.generate_next_block_including(txids[0]);
5937    st.scan_cached_blocks(h, 1);
5938
5939    // Since the recipient address is in the same account, the total balance includes the transfer
5940    // amount.
5941    assert_eq!(
5942        st.get_total_balance(account.id()),
5943        (initial_balance - expected_fee).unwrap()
5944    );
5945    // The spendable balance doesn't include the transparent value, so it excludes the transfer
5946    // amount.
5947    assert_eq!(
5948        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
5949        (initial_balance - transfer_amount - expected_fee).unwrap()
5950    );
5951}
5952
5953#[cfg(feature = "orchard")]
5954pub fn multi_pool_checkpoint<P0: ShieldedPoolTester, P1: ShieldedPoolTester>(
5955    ds_factory: impl DataStoreFactory,
5956    cache: impl TestCache,
5957) {
5958    // TODO: Allow for Orchard activation after Sapling
5959    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<P0>();
5960
5961    let account = st.test_account().cloned().unwrap();
5962    let acct_id = account.id();
5963
5964    let p0_fvk = P0::test_account_fvk(&st);
5965    let p1_fvk = P1::test_account_fvk(&st);
5966
5967    // Add some funds to the wallet; we add two notes to allow successive spends. Also,
5968    // we will generate a note in the P1 pool to ensure that we have some tree state.
5969    let note_value = Zatoshis::const_from_u64(500000);
5970    let (start_height, _, _) =
5971        st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
5972    st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
5973    st.generate_next_block(&p1_fvk, AddressType::DefaultExternal, note_value);
5974    let scanned = st.scan_cached_blocks(start_height, 3);
5975
5976    let next_to_scan = scanned.scanned_range().end;
5977
5978    let initial_balance = (note_value * 3u64).unwrap();
5979    assert_eq!(st.get_total_balance(acct_id), initial_balance);
5980    assert_eq!(
5981        st.get_spendable_balance(acct_id, ConfirmationsPolicy::MIN),
5982        initial_balance
5983    );
5984
5985    // Generate several empty blocks
5986    for _ in 0..10 {
5987        st.generate_empty_block();
5988    }
5989
5990    // Scan into the middle of the empty range
5991    let scanned = st.scan_cached_blocks(next_to_scan, 5);
5992    let next_to_scan = scanned.scanned_range().end;
5993
5994    // The initial balance should be unchanged.
5995    assert_eq!(st.get_total_balance(acct_id), initial_balance);
5996    assert_eq!(
5997        st.get_spendable_balance(acct_id, ConfirmationsPolicy::MIN),
5998        initial_balance
5999    );
6000
6001    // Set up the fee rule and input selector we'll use for all the transfers.
6002    let input_selector = GreedyInputSelector::new();
6003    let change_strategy =
6004        single_output_change_strategy(StandardFeeRule::Zip317, None, P1::SHIELDED_PROTOCOL);
6005
6006    // First, send funds just to P0
6007    let transfer_amount = Zatoshis::const_from_u64(200000);
6008    let p0_transfer = TransactionRequest::new(vec![Payment::without_memo(
6009        P0::random_address(st.rng_mut()).to_zcash_address(st.network()),
6010        transfer_amount,
6011    )])
6012    .unwrap();
6013    let res = st
6014        .spend(
6015            &input_selector,
6016            &change_strategy,
6017            account.usk(),
6018            p0_transfer,
6019            OvkPolicy::Sender,
6020            ConfirmationsPolicy::MIN,
6021        )
6022        .unwrap();
6023    st.generate_next_block_including(*res.first());
6024
6025    let expected_fee = Zatoshis::const_from_u64(10000);
6026    let expected_change = (note_value - transfer_amount - expected_fee).unwrap();
6027    assert_eq!(
6028        st.get_total_balance(acct_id),
6029        ((note_value * 2u64).unwrap() + expected_change).unwrap()
6030    );
6031    assert_eq!(
6032        st.get_pending_change(acct_id, ConfirmationsPolicy::MIN),
6033        expected_change
6034    );
6035
6036    // In the next block, send funds to both P0 and P1
6037    let both_transfer = TransactionRequest::new(vec![
6038        Payment::without_memo(
6039            P0::random_address(st.rng_mut()).to_zcash_address(st.network()),
6040            transfer_amount,
6041        ),
6042        Payment::without_memo(
6043            P1::random_address(st.rng_mut()).to_zcash_address(st.network()),
6044            transfer_amount,
6045        ),
6046    ])
6047    .unwrap();
6048    let res = st
6049        .spend(
6050            &input_selector,
6051            &change_strategy,
6052            account.usk(),
6053            both_transfer,
6054            OvkPolicy::Sender,
6055            ConfirmationsPolicy::MIN,
6056        )
6057        .unwrap();
6058    st.generate_next_block_including(*res.first());
6059
6060    // Generate a few more empty blocks
6061    for _ in 0..5 {
6062        st.generate_empty_block();
6063    }
6064
6065    // Generate another block with funds for us
6066    let (max_height, _, _) =
6067        st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
6068
6069    // Scan everything.
6070    st.scan_cached_blocks(
6071        next_to_scan,
6072        usize::try_from(u32::from(max_height) - u32::from(next_to_scan) + 1).unwrap(),
6073    );
6074
6075    let expected_final = (initial_balance + note_value
6076        - (transfer_amount * 3u64).unwrap()
6077        - (expected_fee * 3u64).unwrap())
6078    .unwrap();
6079    assert_eq!(st.get_total_balance(acct_id), expected_final);
6080
6081    // Every scanned height lies within `PRUNING_DEPTH` of the chain tip, so each one carries a
6082    // checkpoint in both trees, at the position of the nearest preceding commitment in that
6083    // tree.
6084    let expected_checkpoints_p0: Vec<(BlockHeight, Option<Position>)> = [(99999u32, None)]
6085        .into_iter()
6086        .chain([(100000, Some(0u64))])
6087        .chain((100001..=100012).map(|h| (h, Some(1))))
6088        .chain([(100013, Some(3))])
6089        .chain((100014..=100019).map(|h| (h, Some(5))))
6090        .chain([(100020, Some(6))])
6091        .map(|(h, pos)| (BlockHeight::from(h), pos.map(Position::from)))
6092        .collect();
6093
6094    let expected_checkpoints_p1: Vec<(BlockHeight, Option<Position>)> = [(99999u32, None)]
6095        .into_iter()
6096        .chain([(100000, None), (100001, None)])
6097        .chain((100002..=100013).map(|h| (h, Some(0u64))))
6098        .chain((100014..=100020).map(|h| (h, Some(2))))
6099        .map(|(h, pos)| (BlockHeight::from(h), pos.map(Position::from)))
6100        .collect();
6101
6102    let p0_checkpoints = st
6103        .wallet()
6104        .get_checkpoint_history(&P0::SHIELDED_PROTOCOL)
6105        .unwrap();
6106    assert_eq!(p0_checkpoints.to_vec(), expected_checkpoints_p0);
6107
6108    let p1_checkpoints = st
6109        .wallet()
6110        .get_checkpoint_history(&P1::SHIELDED_PROTOCOL)
6111        .unwrap();
6112    assert_eq!(p1_checkpoints.to_vec(), expected_checkpoints_p1);
6113}
6114
6115#[cfg(feature = "orchard")]
6116pub fn multi_pool_checkpoints_with_pruning<P0: ShieldedPoolTester, P1: ShieldedPoolTester>(
6117    ds_factory: impl DataStoreFactory,
6118    cache: impl TestCache,
6119) {
6120    // TODO: Allow for Orchard activation after Sapling
6121    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<P0>();
6122
6123    let account = st.test_account().cloned().unwrap();
6124
6125    let p0_fvk = P0::random_fvk(st.rng_mut());
6126    let p1_fvk = P1::random_fvk(st.rng_mut());
6127
6128    let note_value = Zatoshis::const_from_u64(10000);
6129    // Generate 100 P0 blocks, then 100 P1 blocks, then another 100 P0 blocks.
6130    for _ in 0..10 {
6131        for _ in 0..10 {
6132            st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
6133        }
6134        for _ in 0..10 {
6135            st.generate_next_block(&p1_fvk, AddressType::DefaultExternal, note_value);
6136        }
6137    }
6138    st.scan_cached_blocks(account.birthday().height(), 200);
6139    for _ in 0..100 {
6140        st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
6141        st.generate_next_block(&p1_fvk, AddressType::DefaultExternal, note_value);
6142    }
6143    st.scan_cached_blocks(account.birthday().height() + 200, 200);
6144}
6145
6146pub fn valid_chain_states<T: ShieldedPoolTester>(
6147    ds_factory: impl DataStoreFactory,
6148    cache: impl TestCache,
6149) {
6150    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
6151
6152    let dfvk = T::test_account_fvk(&st);
6153
6154    // Empty chain should return None
6155    assert_matches!(st.wallet().chain_height(), Ok(None));
6156
6157    // Create a fake CompactBlock sending value to the address
6158    let (h1, _, _) = st.generate_next_block(
6159        &dfvk,
6160        AddressType::DefaultExternal,
6161        Zatoshis::const_from_u64(5),
6162    );
6163
6164    // Scan the cache
6165    st.scan_cached_blocks(h1, 1);
6166
6167    // Create a second fake CompactBlock sending more value to the address
6168    let (h2, _, _) = st.generate_next_block(
6169        &dfvk,
6170        AddressType::DefaultExternal,
6171        Zatoshis::const_from_u64(7),
6172    );
6173
6174    // Scanning should detect no inconsistencies
6175    st.scan_cached_blocks(h2, 1);
6176}
6177
6178// FIXME: This requires fixes to the test framework.
6179#[allow(dead_code)]
6180pub fn invalid_chain_cache_disconnected<T: ShieldedPoolTester>(
6181    ds_factory: impl DataStoreFactory,
6182    cache: impl TestCache,
6183) {
6184    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
6185
6186    let dfvk = T::test_account_fvk(&st);
6187
6188    // Create some fake CompactBlocks
6189    let (h, _, _) = st.generate_next_block(
6190        &dfvk,
6191        AddressType::DefaultExternal,
6192        Zatoshis::const_from_u64(5),
6193    );
6194    let (last_contiguous_height, _, _) = st.generate_next_block(
6195        &dfvk,
6196        AddressType::DefaultExternal,
6197        Zatoshis::const_from_u64(7),
6198    );
6199
6200    // Scanning the cache should find no inconsistencies
6201    st.scan_cached_blocks(h, 2);
6202
6203    // Create more fake CompactBlocks that don't connect to the scanned ones
6204    let disconnect_height = last_contiguous_height + 1;
6205    st.generate_block_at(
6206        disconnect_height,
6207        BlockHash([1; 32]),
6208        &[FakeCompactOutput::new(
6209            &dfvk,
6210            AddressType::DefaultExternal,
6211            Zatoshis::const_from_u64(8),
6212        )],
6213        2,
6214        2,
6215        0,
6216        true,
6217    );
6218    st.generate_next_block(
6219        &dfvk,
6220        AddressType::DefaultExternal,
6221        Zatoshis::const_from_u64(3),
6222    );
6223
6224    // Data+cache chain should be invalid at the data/cache boundary
6225    assert_matches!(
6226        st.try_scan_cached_blocks(
6227            disconnect_height,
6228            2
6229        ),
6230        Err(chain::error::Error::Scan(ScanError::PrevHashMismatch { at_height }))
6231            if at_height == disconnect_height
6232    );
6233}
6234
6235pub fn data_db_truncation<T: ShieldedPoolTester, Dsf>(ds_factory: Dsf, cache: impl TestCache)
6236where
6237    Dsf: DataStoreFactory,
6238    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
6239{
6240    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
6241
6242    let account = st.test_account().cloned().unwrap();
6243    let dfvk = T::test_account_fvk(&st);
6244
6245    // Wallet summary is not yet available
6246    assert_eq!(st.get_wallet_summary(ConfirmationsPolicy::MIN), None);
6247
6248    // Create fake CompactBlocks sending value to the address
6249    let value = Zatoshis::const_from_u64(50000);
6250    let value2 = Zatoshis::const_from_u64(70000);
6251    let (h, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
6252    st.generate_next_block(&dfvk, AddressType::DefaultExternal, value2);
6253
6254    // Scan the cache
6255    st.scan_cached_blocks(h, 2);
6256
6257    // Spendable balance should reflect both received notes
6258    assert_eq!(
6259        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
6260        (value + value2).unwrap()
6261    );
6262
6263    // "Rewind" to height of last scanned block (this is a no-op)
6264    st.wallet_mut().truncate_to_height(h + 1).unwrap();
6265
6266    // Spendable balance should be unaltered
6267    assert_eq!(
6268        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
6269        (value + value2).unwrap()
6270    );
6271
6272    // Rewind so that one block is dropped
6273    st.wallet_mut().truncate_to_height(h).unwrap();
6274
6275    // Spendable balance should only contain the first received note;
6276    // the rest should be pending.
6277    assert_eq!(
6278        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
6279        value
6280    );
6281    assert_eq!(
6282        st.get_pending_shielded_balance(account.id(), ConfirmationsPolicy::MIN),
6283        value2
6284    );
6285
6286    // Scan the cache again
6287    st.scan_cached_blocks(h, 2);
6288
6289    // Account balance should again reflect both received notes
6290    assert_eq!(
6291        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
6292        (value + value2).unwrap()
6293    );
6294}
6295
6296pub fn truncate_to_chain_state<T: ShieldedPoolTester, Dsf>(ds_factory: Dsf, cache: impl TestCache)
6297where
6298    Dsf: DataStoreFactory,
6299    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
6300{
6301    // Test plan:
6302    // 1. Set up test environment with account
6303    // 2. Generate and scan initial blocks to populate the note commitment tree
6304    // 3. Capture the chain state at a specific height
6305    // 4. Generate and scan blocks beyond PRUNING_DEPTH to ensure early checkpoints are pruned
6306    // 5. Verify that normal truncate_to_height fails due to missing checkpoints
6307    // 6. Test that truncate_to_chain_state succeeds using the captured chain state
6308    // 7. Verify wallet state after truncation
6309
6310    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
6311
6312    let sapling_activation = st
6313        .network()
6314        .activation_height(consensus::NetworkUpgrade::Sapling)
6315        .unwrap();
6316
6317    // Step 2: Generate and scan initial blocks to populate the note commitment tree.
6318    // The first block pays the wallet's own account, so the wallet holds a witnessed note
6319    // below the capture height; without one, a store may satisfy the step-5 truncation by
6320    // emptying the pool's tree outright (which is tolerated when no witness data would be
6321    // lost). The remaining blocks use an "other" fvk so that their notes won't be tracked
6322    // by the wallet (keeping the test focused on tree state rather than wallet balances).
6323    let account_fvk = T::test_account_fvk(&st);
6324    let seed = [1u8; 32];
6325    let other_sk = T::sk(&seed);
6326    let other_fvk = T::sk_to_fvk(&other_sk);
6327
6328    let initial_block_count = 8u32;
6329    st.generate_next_block(
6330        &account_fvk,
6331        AddressType::DefaultExternal,
6332        Zatoshis::const_from_u64(10000),
6333    );
6334    for _ in 1..initial_block_count {
6335        st.generate_next_block(
6336            &other_fvk,
6337            AddressType::DefaultExternal,
6338            Zatoshis::const_from_u64(10000),
6339        );
6340    }
6341    let scan_start = sapling_activation;
6342    st.scan_cached_blocks(scan_start, initial_block_count as usize);
6343
6344    // Step 3: Capture the chain state at the current tip. The CachedBlock tracks the
6345    // exact frontier that corresponds to the end of each generated block.
6346    let capture_height = sapling_activation + initial_block_count - 1;
6347    let captured_chain_state = st
6348        .latest_cached_block()
6349        .expect("should have cached blocks")
6350        .chain_state()
6351        .clone();
6352    assert_eq!(captured_chain_state.block_height(), capture_height);
6353
6354    // Step 4: Generate and scan blocks well beyond PRUNING_DEPTH so that the checkpoint
6355    // at capture_height is pruned from the note commitment tree.
6356    let extra_blocks = PRUNING_DEPTH + 10;
6357    for _ in 0..extra_blocks {
6358        st.generate_next_block(
6359            &other_fvk,
6360            AddressType::DefaultExternal,
6361            Zatoshis::const_from_u64(5000),
6362        );
6363    }
6364    st.scan_cached_blocks(capture_height + 1, extra_blocks as usize);
6365
6366    let tip = st
6367        .wallet()
6368        .chain_height()
6369        .unwrap()
6370        .expect("chain tip should be set");
6371    assert!(
6372        tip >= capture_height + PRUNING_DEPTH,
6373        "tip should be beyond pruning depth from capture height"
6374    );
6375
6376    // Step 5: Verify that truncate_to_height fails at capture_height: the checkpoint there
6377    // has been pruned, and the wallet holds a witnessed note below that height, so the
6378    // truncation cannot be satisfied by emptying the tree either.
6379    let truncation_result = st.wallet_mut().truncate_to_height(capture_height);
6380    assert!(
6381        truncation_result.is_err(),
6382        "truncate_to_height should fail when checkpoint has been pruned"
6383    );
6384
6385    // Step 6: truncate_to_chain_state should succeed because it inserts the frontier
6386    // as a checkpoint before truncating.
6387    st.wallet_mut()
6388        .truncate_to_chain_state(captured_chain_state.clone())
6389        .expect("truncate_to_chain_state should succeed");
6390
6391    // Step 7: Verify wallet state after truncation.
6392    // The chain tip should now be at the capture height.
6393    let new_tip = st
6394        .wallet()
6395        .chain_height()
6396        .unwrap()
6397        .expect("chain tip should still be set after truncation");
6398    assert_eq!(new_tip, capture_height);
6399
6400    // The block hash at capture_height should match what was in the captured chain state.
6401    let hash_at_capture = st
6402        .wallet()
6403        .get_block_hash(capture_height)
6404        .unwrap()
6405        .expect("block hash should exist at capture height");
6406    assert_eq!(hash_at_capture, captured_chain_state.block_hash());
6407
6408    // Blocks above the capture height should have been removed.
6409    assert_eq!(
6410        st.wallet().get_block_hash(capture_height + 1).unwrap(),
6411        None,
6412        "blocks above capture height should be removed"
6413    );
6414}
6415
6416pub fn truncate_to_chain_state_below_birthday<T: ShieldedPoolTester, Dsf>(
6417    ds_factory: Dsf,
6418    cache: impl TestCache,
6419) where
6420    Dsf: DataStoreFactory,
6421    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
6422{
6423    // Regression test: truncate_to_chain_state should succeed when truncating to a height
6424    // below the wallet birthday (where no entry exists in the blocks table). Previously,
6425    // this would fail with RequestedRewindInvalid because select_truncation_height requires
6426    // the target height to have an entry in the blocks table.
6427
6428    let mut st = TestBuilder::new()
6429        .with_data_store_factory(ds_factory)
6430        .with_block_cache(cache)
6431        .with_initial_chain_state(|rng, network| {
6432            let birthday_height = network.activation_height(NetworkUpgrade::Sapling).unwrap() + 200;
6433
6434            let (prior_sapling_roots, sapling_initial_tree) =
6435                Frontier::random_with_prior_subtree_roots(rng, 1u64, NonZeroU8::new(16).unwrap());
6436            let prior_sapling_roots = prior_sapling_roots
6437                .into_iter()
6438                .map(|root| CommitmentTreeRoot::from_parts(birthday_height - 100, root))
6439                .collect::<Vec<_>>();
6440
6441            #[cfg(feature = "orchard")]
6442            let (prior_orchard_roots, orchard_initial_tree) =
6443                Frontier::random_with_prior_subtree_roots(rng, 1u64, NonZeroU8::new(16).unwrap());
6444            #[cfg(feature = "orchard")]
6445            let prior_orchard_roots = prior_orchard_roots
6446                .into_iter()
6447                .map(|root| CommitmentTreeRoot::from_parts(birthday_height - 100, root))
6448                .collect::<Vec<_>>();
6449
6450            // Ironwood is not active at these test heights, so its tree is empty.
6451            #[cfg(feature = "orchard")]
6452            let ironwood_initial_tree = Frontier::empty();
6453
6454            InitialChainState {
6455                chain_state: ChainState::new(
6456                    birthday_height - 1,
6457                    BlockHash([5; 32]),
6458                    sapling_initial_tree,
6459                    #[cfg(feature = "orchard")]
6460                    orchard_initial_tree,
6461                    #[cfg(feature = "orchard")]
6462                    ironwood_initial_tree,
6463                ),
6464                prior_sapling_roots,
6465                #[cfg(feature = "orchard")]
6466                prior_orchard_roots,
6467            }
6468        })
6469        .with_account_having_current_birthday()
6470        .build();
6471
6472    // Generate and scan a few initial blocks from the birthday height.
6473    let other_fvk = T::random_fvk(st.rng_mut());
6474    let birthday_height = st.test_account().unwrap().birthday().height();
6475
6476    for _ in 0..5 {
6477        st.generate_next_block(
6478            &other_fvk,
6479            AddressType::DefaultExternal,
6480            Zatoshis::const_from_u64(10000),
6481        );
6482    }
6483    st.scan_cached_blocks(birthday_height, 5);
6484
6485    // Generate and scan blocks well beyond PRUNING_DEPTH to ensure early checkpoints
6486    // are pruned from the note commitment tree.
6487    let extra_blocks = PRUNING_DEPTH + 10;
6488    for _ in 0..extra_blocks {
6489        st.generate_next_block(
6490            &other_fvk,
6491            AddressType::DefaultExternal,
6492            Zatoshis::const_from_u64(5000),
6493        );
6494    }
6495    st.scan_cached_blocks(birthday_height + 5, extra_blocks as usize);
6496
6497    // Get the prior chain state from the account birthday. This chain state is at
6498    // birthday_height - 1, which has valid tree frontiers but NO entry in the blocks
6499    // table (since the wallet never scanned a block at that height).
6500    let prior_chain_state = st
6501        .test_account()
6502        .unwrap()
6503        .birthday()
6504        .prior_chain_state()
6505        .clone();
6506
6507    // This should succeed. On the buggy code, this fails with RequestedRewindInvalid
6508    // because select_truncation_height cannot find an entry in the blocks table at the
6509    // target height.
6510    let _target_height = prior_chain_state.block_height();
6511    st.wallet_mut()
6512        .truncate_to_chain_state(prior_chain_state)
6513        .expect("truncate_to_chain_state below birthday should succeed");
6514
6515    // All blocks were above the target height, so they should have been removed.
6516    assert_eq!(
6517        st.wallet().get_block_hash(birthday_height).unwrap(),
6518        None,
6519        "blocks at birthday height should be removed after truncating below birthday"
6520    );
6521}
6522
6523pub fn truncate_to_chain_state_above_scanned<T: ShieldedPoolTester, Dsf>(
6524    ds_factory: Dsf,
6525    cache: impl TestCache,
6526) where
6527    Dsf: DataStoreFactory,
6528    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
6529{
6530    // Regression test: when truncate_to_chain_state is called with a target height above
6531    // the max scanned height, the frontier insertion must be skipped (it would introduce
6532    // a subtree root discontinuity) but the scan queue must still be trimmed. Without the
6533    // fix, inserting a frontier in shard 2 when the wallet only has shard 0 fails because
6534    // shard 1's subtree root is unknown.
6535
6536    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
6537
6538    let birthday_height = st.test_account().unwrap().birthday().height();
6539
6540    // Generate and scan initial blocks, then scan beyond PRUNING_DEPTH to ensure
6541    // early checkpoints are pruned.
6542    let other_fvk = T::random_fvk(st.rng_mut());
6543    let initial_blocks = 5u32;
6544    for _ in 0..initial_blocks {
6545        st.generate_next_block(
6546            &other_fvk,
6547            AddressType::DefaultExternal,
6548            Zatoshis::const_from_u64(10000),
6549        );
6550    }
6551    st.scan_cached_blocks(birthday_height, initial_blocks as usize);
6552
6553    let extra_blocks = PRUNING_DEPTH + 10;
6554    for _ in 0..extra_blocks {
6555        st.generate_next_block(
6556            &other_fvk,
6557            AddressType::DefaultExternal,
6558            Zatoshis::const_from_u64(5000),
6559        );
6560    }
6561    st.scan_cached_blocks(birthday_height + initial_blocks, extra_blocks as usize);
6562    let max_scanned = birthday_height + initial_blocks + extra_blocks - 1;
6563
6564    // Simulate downloading subtree roots from the network: add a known subtree root
6565    // for shard 0 only. This creates a state where shard 0 exists in the shard store
6566    // but shard 1 does not.
6567    T::put_subtree_roots(
6568        &mut st,
6569        0,
6570        &[CommitmentTreeRoot::from_parts(
6571            birthday_height,
6572            T::empty_tree_leaf(),
6573        )],
6574    )
6575    .unwrap();
6576
6577    // Extend the scan queue beyond max_scanned.
6578    let chain_tip = max_scanned + 500;
6579    st.wallet_mut().update_chain_tip(chain_tip).unwrap();
6580
6581    // Construct a ChainState above max_scanned with a frontier in shard 2. The wallet
6582    // has shard 0 (from put_subtree_roots above) but does NOT have shard 1. Inserting a
6583    // frontier in shard 2 introduces a discontinuity because shard 1's subtree root is
6584    // unknown.
6585    let target_height = max_scanned + 50;
6586    let shard_2_tree_size: u64 = (0x2 << 16) + 2;
6587    let (_, shard2_sapling_frontier) = Frontier::random_with_prior_subtree_roots(
6588        st.rng_mut(),
6589        shard_2_tree_size,
6590        NonZeroU8::new(16).unwrap(),
6591    );
6592    #[cfg(feature = "orchard")]
6593    let (_, shard2_orchard_frontier) = Frontier::random_with_prior_subtree_roots(
6594        st.rng_mut(),
6595        shard_2_tree_size,
6596        NonZeroU8::new(16).unwrap(),
6597    );
6598    // Ironwood is not active at these test heights, so its tree is empty.
6599    #[cfg(feature = "orchard")]
6600    let shard2_ironwood_frontier = Frontier::empty();
6601
6602    let target_chain_state = ChainState::new(
6603        target_height,
6604        BlockHash([7; 32]),
6605        shard2_sapling_frontier,
6606        #[cfg(feature = "orchard")]
6607        shard2_orchard_frontier,
6608        #[cfg(feature = "orchard")]
6609        shard2_ironwood_frontier,
6610    );
6611
6612    // Verify the scan queue extends beyond the target.
6613    let pre_truncation_tip = st
6614        .wallet()
6615        .chain_height()
6616        .unwrap()
6617        .expect("chain tip should be set");
6618    assert!(pre_truncation_tip > target_height);
6619
6620    // Truncate to the target height, which is above max_scanned. With the fix, this
6621    // skips the frontier insertion (avoiding the discontinuity) and trims the scan queue.
6622    // Without the fix, this would fail because inserting a frontier in shard 2 requires
6623    // shard 1's subtree root, which is unknown.
6624    st.wallet_mut()
6625        .truncate_to_chain_state(target_chain_state)
6626        .expect("truncate_to_chain_state above max scanned should succeed");
6627
6628    // The scan queue should have been trimmed to the target height.
6629    let post_truncation_tip = st
6630        .wallet()
6631        .chain_height()
6632        .unwrap()
6633        .expect("chain tip should still be set after truncation");
6634    assert_eq!(
6635        post_truncation_tip, target_height,
6636        "scan queue should be trimmed to target height, not extend to the old chain tip"
6637    );
6638
6639    // Existing blocks below max_scanned should be preserved.
6640    assert!(
6641        st.wallet().get_block_hash(max_scanned).unwrap().is_some(),
6642        "blocks at max_scanned should be preserved"
6643    );
6644}
6645
6646pub fn rewind_to_chain_state_deep<T: ShieldedPoolTester, Dsf>(
6647    ds_factory: Dsf,
6648    cache: impl TestCache,
6649) where
6650    Dsf: DataStoreFactory,
6651    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
6652{
6653    // Deep-rewind test plan:
6654    // 1. Set up a birthday-aligned account.
6655    // 2. Generate and scan initial blocks to populate the note commitment tree.
6656    // 3. Pick a rewind target well below the future prune floor.
6657    // 4. Generate and scan more than PRUNING_DEPTH extra blocks so that the checkpoint at the
6658    //    target is pruned AND the target lies below `tip - PRUNING_DEPTH` (the "deep" branch).
6659    // 5. Call `rewind_to_chain_state(target)` and verify:
6660    //    - the scan queue is rewound all the way to `target`;
6661    //    - blocks, transactions, tx_locator_map entries, and note commitment trees are
6662    //      only rewound to `tip - (PRUNING_DEPTH - 1)` (the oldest retained checkpoint).
6663
6664    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
6665
6666    let sapling_activation = st
6667        .network()
6668        .activation_height(consensus::NetworkUpgrade::Sapling)
6669        .unwrap();
6670
6671    // Generate and scan initial blocks using an "other" fvk so notes are not tracked
6672    // by the wallet.
6673    let seed = [1u8; 32];
6674    let other_fvk = T::sk_to_fvk(&T::sk(&seed));
6675
6676    let initial_block_count = 8u32;
6677    for _ in 0..initial_block_count {
6678        st.generate_next_block(
6679            &other_fvk,
6680            AddressType::DefaultExternal,
6681            Zatoshis::const_from_u64(10000),
6682        );
6683    }
6684    st.scan_cached_blocks(sapling_activation, initial_block_count as usize);
6685
6686    // The rewind target is the tip of the initial range.
6687    let rewind_target = sapling_activation + initial_block_count - 1;
6688
6689    // Scan more than PRUNING_DEPTH extra blocks so that the checkpoint at rewind_target is pruned
6690    // AND rewind_target is below `tip - PRUNING_DEPTH`.
6691    let extra_blocks = PRUNING_DEPTH + 10;
6692    for _ in 0..extra_blocks {
6693        st.generate_next_block(
6694            &other_fvk,
6695            AddressType::DefaultExternal,
6696            Zatoshis::const_from_u64(5000),
6697        );
6698    }
6699    st.scan_cached_blocks(rewind_target + 1, extra_blocks as usize);
6700
6701    let pre_rewind_tip = st
6702        .wallet()
6703        .chain_height()
6704        .unwrap()
6705        .expect("chain tip should be set");
6706    assert!(
6707        pre_rewind_tip > rewind_target + PRUNING_DEPTH,
6708        "tip should be strictly beyond pruning depth from the rewind target"
6709    );
6710
6711    // Capture the block hash at the prune boundary so we can assert it survives the rewind
6712    // unchanged (rather than merely that something exists at that height).
6713    let prune_boundary = pre_rewind_tip - (PRUNING_DEPTH - 1);
6714    let boundary_hash_before = st
6715        .wallet()
6716        .get_block_hash(prune_boundary)
6717        .unwrap()
6718        .expect("block at prune boundary should be present before rewind");
6719
6720    // `rewind_to_chain_state` must succeed at the same target.
6721    st.wallet_mut()
6722        .rewind_to_chain_state(
6723            ChainState::empty(rewind_target, BlockHash([0; 32])),
6724            HashSet::new(),
6725        )
6726        .expect("rewind_to_chain_state should succeed for a deep target");
6727
6728    // The chain tip (derived from scan_queue) should still report the pre-rewind tip:
6729    // `rewind_to_chain_state` overwrites the scan-queue range above the rewind target
6730    // with a `Historic` rescan range that extends up to the pre-rewind tip.
6731    let new_tip = st
6732        .wallet()
6733        .chain_height()
6734        .unwrap()
6735        .expect("chain tip should still be set after rewind");
6736    assert_eq!(new_tip, pre_rewind_tip);
6737
6738    // A deep rewind preserves block, transaction, tx_locator_map, and note commitment tree
6739    // data only as far back as the oldest retained checkpoint at `tip - (PRUNING_DEPTH - 1)`.
6740    // Data at that boundary is kept (so stabilized notes remain spendable); data above it is
6741    // removed.
6742    let wallet = st.wallet();
6743    assert_eq!(
6744        wallet.get_block_hash(prune_boundary).unwrap(),
6745        Some(boundary_hash_before),
6746        "block hash at (tip - (PRUNING_DEPTH - 1)) should be preserved unchanged by a deep rewind"
6747    );
6748    assert!(
6749        wallet.get_block_hash(prune_boundary + 1).unwrap().is_none(),
6750        "block entries above (tip - (PRUNING_DEPTH - 1)) must be removed by a deep rewind"
6751    );
6752    assert!(
6753        wallet.get_block_hash(pre_rewind_tip).unwrap().is_none(),
6754        "block entries up to the pre-rewind tip must be removed by a deep rewind"
6755    );
6756    assert_eq!(
6757        wallet
6758            .block_max_scanned()
6759            .unwrap()
6760            .map(|m| m.block_height()),
6761        Some(prune_boundary),
6762        "block_max_scanned should equal (tip - (PRUNING_DEPTH - 1)) after a deep rewind"
6763    );
6764}
6765
6766pub fn rewind_to_chain_state_shallow<T: ShieldedPoolTester, Dsf>(
6767    ds_factory: Dsf,
6768    cache: impl TestCache,
6769) where
6770    Dsf: DataStoreFactory,
6771    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
6772{
6773    // Shallow-rewind test plan:
6774    // 1. Set up a birthday-aligned account.
6775    // 2. Generate and scan initial blocks to populate the note commitment tree.
6776    // 3. Pick a rewind target.
6777    // 4. Generate and scan `PRUNING_DEPTH - 1` extra blocks so that the target sits at
6778    //    the shallow boundary (`target == tip - (PRUNING_DEPTH - 1)`, exactly the oldest
6779    //    retained checkpoint).
6780    // 5. Call `rewind_to_chain_state(target)` and verify all wallet data is rewound to the
6781    //    target: data at the target is preserved, anything above is removed.
6782
6783    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
6784
6785    let sapling_activation = st
6786        .network()
6787        .activation_height(consensus::NetworkUpgrade::Sapling)
6788        .unwrap();
6789
6790    let seed = [1u8; 32];
6791    let other_fvk = T::sk_to_fvk(&T::sk(&seed));
6792
6793    let initial_block_count = 8u32;
6794    for _ in 0..initial_block_count {
6795        st.generate_next_block(
6796            &other_fvk,
6797            AddressType::DefaultExternal,
6798            Zatoshis::const_from_u64(10000),
6799        );
6800    }
6801    st.scan_cached_blocks(sapling_activation, initial_block_count as usize);
6802
6803    let rewind_target = sapling_activation + initial_block_count - 1;
6804
6805    // Scan `PRUNING_DEPTH - 1` extra blocks so the target sits at the shallow boundary
6806    // (`target == tip - (PRUNING_DEPTH - 1)`, exactly the oldest retained checkpoint
6807    // given the tree's `max_checkpoints = PRUNING_DEPTH`).
6808    let extra_blocks = PRUNING_DEPTH - 1;
6809    for _ in 0..extra_blocks {
6810        st.generate_next_block(
6811            &other_fvk,
6812            AddressType::DefaultExternal,
6813            Zatoshis::const_from_u64(5000),
6814        );
6815    }
6816    st.scan_cached_blocks(rewind_target + 1, extra_blocks as usize);
6817
6818    let tip = st
6819        .wallet()
6820        .chain_height()
6821        .unwrap()
6822        .expect("chain tip should be set");
6823    assert_eq!(
6824        tip,
6825        rewind_target + (PRUNING_DEPTH - 1),
6826        "tip should be exactly at the shallow boundary from the rewind target"
6827    );
6828
6829    let target_hash_before = st
6830        .wallet()
6831        .get_block_hash(rewind_target)
6832        .unwrap()
6833        .expect("block at the rewind target should be present before rewind");
6834
6835    st.wallet_mut()
6836        .rewind_to_chain_state(
6837            ChainState::empty(rewind_target, BlockHash([0; 32])),
6838            HashSet::new(),
6839        )
6840        .expect("rewind_to_chain_state should succeed for a shallow target");
6841
6842    // The chain tip (derived from scan_queue) should still report the pre-rewind tip:
6843    // `rewind_to_chain_state` overwrites the scan-queue range above the rewind target with
6844    // a `Historic` rescan range that extends up to the pre-rewind tip.
6845    let new_tip = st
6846        .wallet()
6847        .chain_height()
6848        .unwrap()
6849        .expect("chain tip should still be set after rewind");
6850    assert_eq!(new_tip, tip);
6851
6852    // A shallow rewind truncates blocks, tx_locator_map, and note commitment trees
6853    // directly to the rewind target: data at the target is preserved (with the same
6854    // content it had before), anything above is removed.
6855    let wallet = st.wallet();
6856    assert_eq!(
6857        wallet.get_block_hash(rewind_target).unwrap(),
6858        Some(target_hash_before),
6859        "block hash at the rewind target should be preserved unchanged"
6860    );
6861    assert!(
6862        wallet.get_block_hash(rewind_target + 1).unwrap().is_none(),
6863        "block entries above the rewind target should be removed by a shallow rewind"
6864    );
6865    assert_eq!(
6866        wallet
6867            .block_max_scanned()
6868            .unwrap()
6869            .map(|m| m.block_height()),
6870        Some(rewind_target),
6871        "block_max_scanned should equal the rewind target after a shallow rewind"
6872    );
6873}
6874
6875pub fn rewind_after_non_contiguous_scan<T: ShieldedPoolTester, Dsf>(
6876    ds_factory: Dsf,
6877    cache: impl TestCache,
6878) where
6879    Dsf: DataStoreFactory,
6880    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
6881{
6882    // Regression test: after the scan scheduler processes a `ChainTip` range before a
6883    // lower `Historic` range, `MAX(height) FROM blocks` points into one scanned region
6884    // while `last_scanned - (PRUNING_DEPTH - 1)` lands inside the unscanned gap between
6885    // the two regions. `rewind_to_chain_state` must still succeed: an implementation that
6886    // expected a checkpoint at exactly the PD floor would return `CorruptedData` via
6887    // `truncate_to_checkpoint`; clamping forward to the lowest checkpoint inside the
6888    // prune window keeps us aligned with a real checkpoint.
6889
6890    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
6891
6892    let sapling_activation = st
6893        .network()
6894        .activation_height(consensus::NetworkUpgrade::Sapling)
6895        .unwrap();
6896
6897    // Scan is always sequential in cache order, but `scan_cached_blocks` is happy to be
6898    // invoked on subranges out of order. We pre-generate a contiguous chain of blocks
6899    // and scan it in two disjoint segments with a gap in between.
6900    let seed = [1u8; 32];
6901    let other_fvk = T::sk_to_fvk(&T::sk(&seed));
6902    let filler_value = Zatoshis::const_from_u64(10_000);
6903
6904    let low_count: u32 = 10;
6905    let gap_size: u32 = PRUNING_DEPTH + 5; // must exceed PD so the PD floor lands in the gap
6906    let high_count: u32 = 10;
6907    let total_generated = low_count + gap_size + high_count;
6908
6909    for _ in 0..total_generated {
6910        st.generate_next_block(&other_fvk, AddressType::DefaultExternal, filler_value);
6911    }
6912
6913    let low_start = sapling_activation;
6914    let low_end_inclusive = low_start + low_count - 1;
6915    let high_start = low_end_inclusive + gap_size + 1;
6916
6917    // Scan the low range first (simulating a historic range).
6918    st.scan_cached_blocks(low_start, low_count as usize);
6919
6920    // Scan the high range next (simulating a chain-tip range), leaving `gap_size` blocks
6921    // in the middle unscanned. Because `high_start > low_end_inclusive + PRUNING_DEPTH`,
6922    // the PD floor after this scan (`high_end_inclusive - (PRUNING_DEPTH - 1)`) lands
6923    // inside the unscanned gap.
6924    st.scan_cached_blocks(high_start, high_count as usize);
6925
6926    let max_scanned_height = st
6927        .wallet()
6928        .block_max_scanned()
6929        .unwrap()
6930        .map(|m| m.block_height())
6931        .expect("block_max_scanned should report the high-range tip");
6932    let high_end_inclusive = high_start + high_count - 1;
6933    assert_eq!(max_scanned_height, high_end_inclusive);
6934    let pd_floor = max_scanned_height - (PRUNING_DEPTH - 1);
6935    assert!(
6936        pd_floor > low_end_inclusive && pd_floor < high_start,
6937        "test invariant: PD floor must lie in the unscanned gap (got {pd_floor}, \
6938         gap is ({low_end_inclusive}, {high_start}))"
6939    );
6940
6941    // `rewind_to_chain_state` must return `Ok(_)` rather than `CorruptedData`: clamping
6942    // forward to the lowest checkpoint inside the window (which sits at `high_start`)
6943    // keeps us aligned with a real checkpoint.
6944    st.wallet_mut()
6945        .rewind_to_chain_state(
6946            ChainState::empty(low_end_inclusive, BlockHash([0; 32])),
6947            HashSet::new(),
6948        )
6949        .expect("rewind_to_chain_state should succeed across a non-contiguous scan");
6950}
6951
6952/// Helper: drive the value-conservation checks once a recovery sequence
6953/// claims the note is spendable again. Run a send-max proposal (consume
6954/// exactly the reported balance) and a real fixed-value spend that must
6955/// construct a transaction end-to-end.
6956fn assert_recovered_balance_spends<T, Cache, DbT, ParamsT, AccountIdT, ErrT>(
6957    st: &mut TestState<Cache, DbT, ParamsT>,
6958    account_id: AccountIdT,
6959    usk: &UnifiedSpendingKey,
6960    expected_balance: Zatoshis,
6961) where
6962    T: ShieldedPoolTester,
6963    Cache: TestCache,
6964    <Cache::BlockSource as BlockSource>::Error: std::fmt::Debug,
6965    ParamsT: consensus::Parameters + Send + 'static,
6966    AccountIdT: std::fmt::Debug + std::cmp::Eq + std::hash::Hash + Copy,
6967    ErrT: std::fmt::Debug,
6968    DbT: InputSource<AccountId = AccountIdT, Error = ErrT>
6969        + WalletTest
6970        + WalletWrite
6971        + WalletRead<AccountId = AccountIdT, Error = ErrT>
6972        + WalletCommitmentTrees,
6973    <DbT as WalletRead>::AccountId: ConditionallySelectable + Default + Send + Sync + 'static,
6974    <DbT as WalletRead>::Account: data_api::Account<AccountId = AccountIdT>,
6975{
6976    // Send-max consumes exactly the reported balance.
6977    assert_send_max_consumes_balance::<T, _, _, _, _, _>(st, account_id, expected_balance);
6978
6979    // A small fixed-value spend must construct a transaction.
6980    let to_extsk = T::sk(&[0xcc; 32]);
6981    let to: Address = T::sk_default_address(&to_extsk);
6982    let send_value = Zatoshis::const_from_u64(10_000);
6983    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
6984        to.to_zcash_address(st.network()),
6985        send_value,
6986    )])
6987    .unwrap();
6988    let change_strategy =
6989        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
6990    let input_selector = GreedyInputSelector::new();
6991    let proposal = st
6992        .propose_transfer(
6993            account_id,
6994            &input_selector,
6995            &change_strategy,
6996            request,
6997            ConfirmationsPolicy::MIN,
6998        )
6999        .expect("propose_transfer should succeed against stabilized notes after the recovery scan");
7000    let txids = st
7001        .create_proposed_transactions::<std::convert::Infallible, _, std::convert::Infallible, _>(
7002            usk,
7003            OvkPolicy::Sender,
7004            &proposal,
7005        )
7006        .expect("transaction construction should succeed");
7007    assert_eq!(
7008        txids.len(),
7009        1,
7010        "the spend should produce exactly one transaction",
7011    );
7012}
7013
7014/// A note in the chain-tip shard stays recoverable across a rewind to below
7015/// its account's birthday, as long as the chain has real history there to
7016/// re-scan.
7017///
7018/// Uses `build_two_account_recovery_fixture`: account B's birthday is
7019/// `H_A + 5`, and account A contributes the real blocks `H_A ..= H_A + 4`.
7020/// The rewind targets `H_A + 2` -- below B's birthday but inside A's history
7021/// -- so the recovery re-scan covers genuine cached blocks rather than faked
7022/// tree state (the `CacheMiss` failure mode of an all-faked pre-birthday
7023/// fixture).
7024///
7025///   1. Baseline: both accounts' notes are spendable.
7026///   2. After the rewind: B's balance is zero (its chain-tip shard is
7027///      re-dirtied and the pruning window has `Anchor` priority).
7028///   3. After re-scanning the dirty range: B's note is spendable again and
7029///      value conservation holds.
7030pub fn b_note_stable_across_rewind_below_birthday<T, Dsf>(ds_factory: Dsf, cache: impl TestCache)
7031where
7032    T: ShieldedPoolTester,
7033    Dsf: DataStoreFactory,
7034    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
7035{
7036    let (mut st, account_b_id, usk_b) =
7037        build_two_account_recovery_fixture::<T, Dsf>(ds_factory, cache);
7038    let account_a = st.test_account().unwrap().clone();
7039    let birthday_a = account_a.birthday().height();
7040    let birthday_b = birthday_a + 5;
7041
7042    // (1) Baseline: both notes spendable.
7043    assert_eq!(
7044        st.get_spendable_balance(account_a.id(), ConfirmationsPolicy::MIN),
7045        RECOVERY_A_NOTE_VALUE,
7046        "account A's note must be spendable in the freshly-built fixture",
7047    );
7048    assert_eq!(
7049        st.get_spendable_balance(account_b_id, ConfirmationsPolicy::MIN),
7050        RECOVERY_B_NOTE_VALUE,
7051        "account B's note must be spendable in the freshly-built fixture",
7052    );
7053
7054    // (2) Rewind to `H_A + 2`: below B's birthday (`H_A + 5`) but within the
7055    // run of real blocks contributed by account A.
7056    let rewind_target = birthday_a + 2;
7057    assert!(
7058        rewind_target < birthday_b,
7059        "the rewind target must sit below account B's birthday",
7060    );
7061    st.wallet_mut()
7062        .rewind_to_chain_state(
7063            ChainState::empty(rewind_target, BlockHash([0; 32])),
7064            HashSet::from([account_b_id]),
7065        )
7066        .expect("rewind_to_chain_state should succeed");
7067
7068    assert_eq!(
7069        st.get_spendable_balance(account_b_id, ConfirmationsPolicy::MIN),
7070        Zatoshis::ZERO,
7071        "immediately after the rewind account B's note must not be spendable",
7072    );
7073
7074    // (3) Re-scan every dirtied block. `H_A + 3 ..= chain_tip` is a
7075    // contiguous run of real cached blocks, so the re-scan completes without
7076    // a `CacheMiss`.
7077    let chain_tip = st
7078        .wallet()
7079        .chain_height()
7080        .unwrap()
7081        .expect("chain tip should still be set after rewind");
7082    let rescan_from = rewind_target + 1;
7083    let rescan_count = u32::from(chain_tip) - u32::from(rescan_from) + 1;
7084    st.scan_cached_blocks(rescan_from, rescan_count as usize);
7085
7086    assert_eq!(
7087        st.get_spendable_balance(account_b_id, ConfirmationsPolicy::MIN),
7088        RECOVERY_B_NOTE_VALUE,
7089        "after re-scanning the dirty range account B's note must be spendable again",
7090    );
7091    assert_eq!(
7092        st.get_spendable_balance(account_a.id(), ConfirmationsPolicy::MIN),
7093        RECOVERY_A_NOTE_VALUE,
7094        "account A's note is unaffected by a rewind that stays above its shard",
7095    );
7096
7097    assert_recovered_balance_spends::<T, _, _, _, _, _>(
7098        &mut st,
7099        account_b_id,
7100        &usk_b,
7101        RECOVERY_B_NOTE_VALUE,
7102    );
7103}
7104
7105/// A rewind below an account's birthday requeues every block above the rewind target for
7106/// scanning, but it truncates only the chain-tip pruning window. The witness data that the wallet
7107/// holds below the window for a note in a completed shard is unaffected, so the note is spendable
7108/// again as soon as the pruning window is rescanned, while its own shard's blocks are still
7109/// queued.
7110///
7111/// Uses `build_two_account_recovery_fixture`. Account A's note sits at the start of shard 1,
7112/// which Block A2 completes. The rewind targets `H_A - 1`:
7113///
7114///   1. Baseline: A's note is spendable.
7115///   2. After the rewind: A's balance is zero, because the pruning window is unscanned.
7116///   3. After rescanning only the pruning window: A's note is spendable, while Blocks A1 and A2
7117///      remain queued for scanning.
7118pub fn completed_shard_note_spendable_after_rewind_once_window_rescanned<T, Dsf>(
7119    ds_factory: Dsf,
7120    cache: impl TestCache,
7121) where
7122    T: ShieldedPoolTester,
7123    Dsf: DataStoreFactory,
7124    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
7125{
7126    let (mut st, account_b_id, _) = build_two_account_recovery_fixture::<T, Dsf>(ds_factory, cache);
7127    let account_a = st.test_account().unwrap().clone();
7128    let birthday_a = account_a.birthday().height();
7129    let block_a1_height = birthday_a;
7130
7131    // (1) Baseline.
7132    assert_eq!(
7133        st.get_spendable_balance(account_a.id(), ConfirmationsPolicy::MIN),
7134        RECOVERY_A_NOTE_VALUE,
7135        "account A's note must be spendable in the freshly-built fixture",
7136    );
7137
7138    // (2) Rewind below A's birthday. Both accounts' birthdays sit above the target, so both are
7139    // reset.
7140    let rewind_target = birthday_a - 1;
7141    st.wallet_mut()
7142        .rewind_to_chain_state(
7143            ChainState::empty(rewind_target, BlockHash([0; 32])),
7144            HashSet::from([account_a.id(), account_b_id]),
7145        )
7146        .expect("rewind_to_chain_state should succeed");
7147
7148    assert_eq!(
7149        st.get_spendable_balance(account_a.id(), ConfirmationsPolicy::MIN),
7150        Zatoshis::ZERO,
7151        "immediately after the rewind account A's note must not be spendable",
7152    );
7153
7154    // (3) Rescan only the chain-tip pruning window.
7155    let chain_tip = st
7156        .wallet()
7157        .chain_height()
7158        .unwrap()
7159        .expect("chain tip should still be set after rewind");
7160    let pruning_window_start = chain_tip - (PRUNING_DEPTH - 1);
7161    st.scan_cached_blocks(pruning_window_start, PRUNING_DEPTH as usize);
7162
7163    let unscanned = st.wallet().suggest_scan_ranges().unwrap();
7164    assert!(
7165        unscanned
7166            .iter()
7167            .any(|range| range.block_range().contains(&block_a1_height)),
7168        "test invariant: Block A1 must still be queued for scanning: {unscanned:?}",
7169    );
7170    assert_eq!(
7171        st.get_spendable_balance(account_a.id(), ConfirmationsPolicy::MIN),
7172        RECOVERY_A_NOTE_VALUE,
7173        "once the pruning window is rescanned account A's note is spendable again",
7174    );
7175
7176    assert_recovered_balance_spends::<T, _, _, _, _, _>(
7177        &mut st,
7178        account_a.id(),
7179        account_a.usk(),
7180        RECOVERY_A_NOTE_VALUE,
7181    );
7182}
7183
7184/// Imports an account whose birthday lies `PRE_BIRTHDAY_BLOCKS / 2` blocks below the wallet
7185/// birthday, which requeues every block above the new birthday for scanning. The account's seed
7186/// differs from the seed of every fixture account.
7187fn import_account_below_wallet_birthday<Cache, DbT, ParamsT>(
7188    st: &mut TestState<Cache, DbT, ParamsT>,
7189) where
7190    Cache: TestCache,
7191    DbT: WalletTest + WalletWrite,
7192    ParamsT: consensus::Parameters + Send + 'static,
7193{
7194    const IMPORTED_SEED: [u8; 32] = [7u8; 32];
7195    let wallet_birthday = st
7196        .wallet()
7197        .get_wallet_birthday()
7198        .unwrap()
7199        .expect("the wallet has a birthday");
7200    let prior_height = wallet_birthday - PRE_BIRTHDAY_BLOCKS / 2 - 1;
7201    let prior_chain_state = st
7202        .cached_blocks
7203        .get(&prior_height)
7204        .expect("the block below the new birthday is cached")
7205        .chain_state()
7206        .clone();
7207    let birthday = AccountBirthday::from_parts(prior_chain_state, None);
7208    st.wallet_mut()
7209        .import_account_hd(
7210            "imported",
7211            &Secret::new(IMPORTED_SEED.to_vec()),
7212            zip32::AccountId::ZERO,
7213            &birthday,
7214            None,
7215        )
7216        .expect("account import should succeed");
7217}
7218
7219/// Importing an account whose birthday lies below the wallet birthday requeues the blocks above
7220/// the new birthday so that they are scanned with the new account's keys. The witness data that
7221/// the wallet holds for an existing note in a completed shard is unaffected, so the note is
7222/// spendable again as soon as the chain-tip pruning window is rescanned.
7223pub fn completed_shard_note_spendable_across_older_birthday_import<T, Dsf>(
7224    ds_factory: Dsf,
7225    cache: impl TestCache,
7226) where
7227    T: ShieldedPoolTester,
7228    Dsf: DataStoreFactory,
7229    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
7230{
7231    let (mut st, account_id, usk) = build_stable_shard_fixture::<T, Dsf>(ds_factory, cache);
7232    assert_eq!(
7233        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
7234        SHARD_1_NOTE_VALUE
7235    );
7236
7237    import_account_below_wallet_birthday(&mut st);
7238    assert_eq!(
7239        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
7240        Zatoshis::ZERO,
7241        "immediately after the import the pruning window is unscanned",
7242    );
7243
7244    let chain_tip = st
7245        .wallet()
7246        .chain_height()
7247        .unwrap()
7248        .expect("chain tip is known");
7249    let pruning_window_start = chain_tip - (PRUNING_DEPTH - 1);
7250    st.scan_cached_blocks(pruning_window_start, PRUNING_DEPTH as usize);
7251
7252    let unscanned = st.wallet().suggest_scan_ranges().unwrap();
7253    assert!(
7254        unscanned
7255            .iter()
7256            .any(|range| range.block_range().start < pruning_window_start),
7257        "test invariant: blocks below the pruning window must remain queued: {unscanned:?}",
7258    );
7259    assert_eq!(
7260        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
7261        SHARD_1_NOTE_VALUE,
7262        "once the pruning window is rescanned the completed-shard note is spendable again",
7263    );
7264    assert_recovered_balance_spends::<T, _, _, _, _, _>(
7265        &mut st,
7266        account_id,
7267        &usk,
7268        SHARD_1_NOTE_VALUE,
7269    );
7270}
7271
7272/// As [`completed_shard_note_spendable_across_older_birthday_import`] describes, an import below
7273/// the wallet birthday requeues the blocks above the new birthday. A note in the open chain-tip
7274/// shard, buried deeper than the pruning window, has its witness data settled through the pruning
7275/// floor, so it too is spendable again as soon as the pruning window is rescanned.
7276pub fn open_shard_note_spendable_across_older_birthday_import<T, Dsf>(
7277    ds_factory: Dsf,
7278    cache: impl TestCache,
7279) where
7280    T: ShieldedPoolTester,
7281    Dsf: DataStoreFactory,
7282    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
7283{
7284    const OPEN_SHARD_NOTE_VALUE: Zatoshis = Zatoshis::const_from_u64(70_000);
7285
7286    let (mut st, account_id, usk) = build_stable_shard_fixture::<T, Dsf>(ds_factory, cache);
7287    let dfvk = T::sk_to_fvk(T::usk_to_sk(&usk));
7288
7289    // Place a note in the open shard 2, then bury it deeper than the pruning window with empty
7290    // blocks, so that shard 2 stays open.
7291    let (note_height, _, _) =
7292        st.generate_next_block(&dfvk, AddressType::DefaultExternal, OPEN_SHARD_NOTE_VALUE);
7293    let burial = PRUNING_DEPTH + 10;
7294    for _ in 0..burial {
7295        st.generate_empty_block();
7296    }
7297    st.scan_cached_blocks(note_height, (burial + 1) as usize);
7298    let total = (SHARD_1_NOTE_VALUE + OPEN_SHARD_NOTE_VALUE).unwrap();
7299    assert_eq!(
7300        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
7301        total
7302    );
7303
7304    import_account_below_wallet_birthday(&mut st);
7305    assert_eq!(
7306        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
7307        Zatoshis::ZERO,
7308        "immediately after the import the pruning window is unscanned",
7309    );
7310
7311    let chain_tip = st
7312        .wallet()
7313        .chain_height()
7314        .unwrap()
7315        .expect("chain tip is known");
7316    let pruning_window_start = chain_tip - (PRUNING_DEPTH - 1);
7317    st.scan_cached_blocks(pruning_window_start, PRUNING_DEPTH as usize);
7318
7319    let unscanned = st.wallet().suggest_scan_ranges().unwrap();
7320    assert!(
7321        unscanned
7322            .iter()
7323            .any(|range| range.block_range().start < pruning_window_start),
7324        "test invariant: blocks below the pruning window must remain queued: {unscanned:?}",
7325    );
7326    assert_eq!(
7327        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
7328        total,
7329        "once the pruning window is rescanned both existing notes are spendable again",
7330    );
7331    assert_recovered_balance_spends::<T, _, _, _, _, _>(&mut st, account_id, &usk, total);
7332}
7333
7334/// R2: rewind to a height above shard 1's end (stable-shard fixture).
7335///
7336/// The rewind target sits *above* `shard 1`'s `subtree_end_height`
7337/// (= `birthday + 1`). The force-rewrite covers
7338/// `(new_birthday = target + 1, chain_tip + 1]` as `Historic`; that range
7339/// starts above shard 1's end and therefore does *not* overlap shard 1's
7340/// extent. `mark_anchor_priority_window` upgrades the pruning window
7341/// portion of the rewrite to `Anchor`.
7342///
7343/// Class 2 (target between shard end and pruning floor) and Class 3 (target
7344/// inside pruning window) of the previous test suite collapse here: in both
7345/// cases the rewrite range starts above shard 1 and so leaves the shard's
7346/// scan-state untouched. We pick `birthday + 5` as a representative target.
7347///
7348/// The note's settled height is shard 1's end, below the truncation height, so
7349/// the rewind keeps it, and only the chain-tip pruning window needs to be
7350/// rescanned to restore the note's `spendable` status.
7351pub fn stabilized_note_rewind_above_shard_end<T, Dsf>(ds_factory: Dsf, cache: impl TestCache)
7352where
7353    T: ShieldedPoolTester,
7354    Dsf: DataStoreFactory,
7355    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
7356{
7357    let (mut st, account_id, usk) = build_stable_shard_fixture::<T, Dsf>(ds_factory, cache);
7358    let birthday_height = st
7359        .wallet()
7360        .get_wallet_birthday()
7361        .unwrap()
7362        .expect("account birthday should be set");
7363
7364    // Baseline.
7365    assert_eq!(
7366        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
7367        SHARD_1_NOTE_VALUE,
7368        "fixture must report the stabilized note as spendable",
7369    );
7370
7371    // Rewind to a height above shard 1's end (= birthday + 1). Picking
7372    // `birthday + 5` lands in the Historic territory below the pruning
7373    // window; any choice in `(birthday + 1, chain_tip]` would exercise the
7374    // same regime.
7375    let rewind_target = birthday_height + 5;
7376    st.wallet_mut()
7377        .rewind_to_chain_state(
7378            ChainState::empty(rewind_target, BlockHash([0; 32])),
7379            HashSet::new(),
7380        )
7381        .expect("rewind_to_chain_state should succeed");
7382
7383    assert_eq!(
7384        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
7385        Zatoshis::ZERO,
7386        "immediately after rewind the window's `Anchor` priority blocks the balance",
7387    );
7388
7389    // Rescan only the chain-tip pruning window. Shard 1's extent
7390    // `(shard_0_end, birthday + 1]` sits below the rewrite range, so the
7391    // note's settled height survives the rewind, and rescanning the window
7392    // restores the note to `spendable`.
7393    let chain_tip = st
7394        .wallet()
7395        .chain_height()
7396        .unwrap()
7397        .expect("chain tip should still be set after rewind");
7398    let pruning_window_start = chain_tip - (PRUNING_DEPTH - 1);
7399    st.scan_cached_blocks(pruning_window_start, PRUNING_DEPTH as usize);
7400
7401    assert_eq!(
7402        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
7403        SHARD_1_NOTE_VALUE,
7404        "shard 1's extent is below the rewrite range; pruning-window rescan must restore the note",
7405    );
7406
7407    assert_recovered_balance_spends::<T, _, _, _, _, _>(
7408        &mut st,
7409        account_id,
7410        &usk,
7411        SHARD_1_NOTE_VALUE,
7412    );
7413}
7414
7415/// R3: rewind un-mines the shard-completion block (tip-shard fixture).
7416///
7417/// The tip-shard fixture leaves the wallet's birthday inside the chain-tip
7418/// pruning window (`chain_tip = birthday + 6`,
7419/// `pruning_floor = birthday - 94`,
7420/// `lowest_window_checkpoint = birthday - 93`). A rewind target below the
7421/// birthday therefore drives `truncation_target` to
7422/// `max(target, birthday - 93)`; with `target = birthday - 50` the
7423/// truncation lands at the lowest checkpoint at or above `birthday - 50`,
7424/// which is the account's birthday-frontier checkpoint at `birthday - 1`
7425/// (the pre-birthday blocks are unscanned and so carry no checkpoints).
7426/// Truncation removes shardtree state strictly above `birthday - 1`, which
7427/// discards the leaves inserted by Blocks A and B (positions
7428/// 131001..131080). Shard 1's last leaf (position 131071) is among those
7429/// discarded, so shard 1 reverts from complete to partial.
7430///
7431/// The truncation clears the note's settled height, so the note must not be
7432/// reported as spendable. Recovery requires rescanning from the lowered
7433/// birthday through the chain tip — all genuine cached blocks — so that
7434/// shard 1's leaves are reinserted and the note stabilizes again.
7435pub fn stabilized_note_rewind_un_mines_shard_completion<T, Dsf>(
7436    ds_factory: Dsf,
7437    cache: impl TestCache,
7438) where
7439    T: ShieldedPoolTester,
7440    Dsf: DataStoreFactory,
7441    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
7442{
7443    let (mut st, account_id, usk) = build_tip_shard_fixture::<T, Dsf>(ds_factory, cache);
7444    let birthday_height = st
7445        .wallet()
7446        .get_wallet_birthday()
7447        .unwrap()
7448        .expect("account birthday should be set");
7449
7450    // Baseline: the note is stabilized via the active-shard interpretation
7451    // (witness_settled_height = birthday = Block A's height), and the rule
7452    // accepts it because every block above that height has been scanned.
7453    assert_eq!(
7454        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
7455        SHARD_1_NOTE_VALUE,
7456        "tip-shard fixture must report the active-shard-stabilized note as spendable",
7457    );
7458
7459    // Rewind to a height well below the birthday, acknowledging that this
7460    // lowers the account birthday to `rewind_target + 1`. Truncation lands at
7461    // the lowest tree checkpoint at or above the target — the account's
7462    // birthday-frontier checkpoint at `birthday - 1` — removing both Block
7463    // A's and Block B's leaves and reverting shard 1 to partial. The rewind
7464    // target sits above the cache floor
7465    // (`birthday - PRE_BIRTHDAY_BLOCKS`), so the whole post-rewind scan
7466    // range is backed by genuine cached blocks.
7467    let rewind_target = birthday_height - 50;
7468    st.wallet_mut()
7469        .rewind_to_chain_state(
7470            ChainState::empty(rewind_target, BlockHash([0; 32])),
7471            HashSet::from([account_id]),
7472        )
7473        .expect("rewind_to_chain_state should succeed");
7474
7475    assert_eq!(
7476        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
7477        Zatoshis::ZERO,
7478        "after rewind the cleared settled height withholds the note",
7479    );
7480
7481    // Recover by re-scanning every cached block from the lowered birthday
7482    // (`rewind_target + 1`) through the chain tip: 49 pre-birthday empty
7483    // blocks, Block A, Block B, and the 5 trailing fillers. The block cache
7484    // is contiguous across the original birthday, so a single
7485    // `scan_cached_blocks` call drives the full re-scan. After this, shard 1
7486    // is complete and the note has a settled height again.
7487    let new_birthday = rewind_target + 1;
7488    let recovery_block_count = 49 + 1 + 1 + 5;
7489    st.scan_cached_blocks(new_birthday, recovery_block_count as usize);
7490
7491    assert_eq!(
7492        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
7493        SHARD_1_NOTE_VALUE,
7494        "after re-scanning from the lowered birthday through the chain tip, shard 1 is \
7495         complete and the note is spendable again",
7496    );
7497
7498    assert_recovered_balance_spends::<T, _, _, _, _, _>(
7499        &mut st,
7500        account_id,
7501        &usk,
7502        SHARD_1_NOTE_VALUE,
7503    );
7504}
7505
7506/// A stabilized note must remain spendable across a chain-tip advance smaller than the
7507/// trusted anchor depth, and must stop being spendable once the advance reaches that
7508/// depth.
7509///
7510/// `update_chain_tip` queues the unscanned extension `(max_scanned, new_tip]` at
7511/// `ChainTip` priority. The anchor the wallet will select for a spend is derived from
7512/// the *new* tip (`target - min_confirmations(trusted)`); while the tip has advanced by
7513/// fewer than `min_confirmations` blocks, that anchor still lies within scanned history:
7514/// the tree structure between the note's settled height and the anchor is fully
7515/// known and a witness against exactly that anchor's root is constructable, so the
7516/// unscanned extension — which lies entirely *above* the anchor and cannot participate
7517/// in the witness — must not veto spendability.
7518///
7519/// Once the advance reaches the anchor depth, the policy anchor lies in unscanned
7520/// territory, so the wallet has no anchor and must report zero spendable value until it
7521/// has scanned forward.
7522pub fn stabilized_note_spendable_across_small_tip_advance<T, Dsf>(
7523    ds_factory: Dsf,
7524    cache: impl TestCache,
7525) where
7526    T: ShieldedPoolTester,
7527    Dsf: DataStoreFactory,
7528    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
7529{
7530    let (mut st, account_id, _usk) = build_stable_shard_fixture::<T, Dsf>(ds_factory, cache);
7531
7532    let policy = ConfirmationsPolicy::default();
7533    let anchor_depth = u32::from(policy.trusted());
7534    assert!(
7535        anchor_depth > 1,
7536        "this test requires a trusted anchor depth of at least 2 so that a nonzero tip \
7537         advance can stay below it",
7538    );
7539
7540    // Baseline: the wallet is fully scanned and the stabilized note is spendable.
7541    assert_eq!(
7542        st.get_spendable_balance(account_id, policy),
7543        SHARD_1_NOTE_VALUE,
7544        "fixture must report the stabilized note as spendable under the default policy",
7545    );
7546
7547    let scanned_tip = st
7548        .wallet()
7549        .chain_height()
7550        .unwrap()
7551        .expect("chain tip is known");
7552
7553    // Advance the chain tip by one block fewer than the trusted anchor depth, without
7554    // scanning. The policy anchor against the new tip
7555    // (`new_tip + 1 - anchor_depth = scanned_tip - 1`) is still within scanned history,
7556    // so the note must remain spendable.
7557    st.wallet_mut()
7558        .update_chain_tip(scanned_tip + (anchor_depth - 1))
7559        .unwrap();
7560    assert_eq!(
7561        st.get_spendable_balance(account_id, policy),
7562        SHARD_1_NOTE_VALUE,
7563        "a tip advance smaller than the anchor depth must not suspend spendability",
7564    );
7565
7566    // Advance the tip by exactly the anchor depth. The policy anchor
7567    // (`new_tip + 1 - anchor_depth = scanned_tip + 1`) now lies in the unscanned
7568    // extension, so nothing may be reported spendable until the wallet scans forward.
7569    st.wallet_mut()
7570        .update_chain_tip(scanned_tip + anchor_depth)
7571        .unwrap();
7572    assert_eq!(
7573        st.get_spendable_balance(account_id, policy),
7574        Zatoshis::ZERO,
7575        "a tip advance reaching the anchor depth must suspend spendability until the \
7576         wallet has scanned to the new anchor",
7577    );
7578}
7579
7580/// A note that the wallet discovers in a shard completed within the last `min_confirmations`
7581/// blocks has a settled height at the shard's end, above the anchor height. The note is
7582/// spendable, and a transaction spending it can be built, as soon as it has the required
7583/// confirmations.
7584pub fn note_in_recently_completed_shard_spendable_once_confirmed<T, Dsf>(
7585    ds_factory: Dsf,
7586    cache: impl TestCache,
7587) where
7588    T: ShieldedPoolTester,
7589    Dsf: DataStoreFactory,
7590    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
7591{
7592    let confirmations = ConfirmationsPolicy::default().untrusted();
7593    let policy = ConfirmationsPolicy::new_symmetrical(
7594        confirmations,
7595        #[cfg(feature = "transparent-inputs")]
7596        false,
7597    );
7598
7599    // The fixture's chain tip is `birthday + 1 + trailing_blocks`, and the note is mined at
7600    // `birthday`, so the note has `trailing_blocks + 2` confirmations: one fewer than required.
7601    let trailing_blocks = confirmations.get() - 3;
7602    let (mut st, account_id, usk) = build_shard_1_note_fixture::<T, Dsf>(
7603        ds_factory,
7604        cache,
7605        trailing_blocks,
7606        Shard1ScanOrder::CompletionFirst,
7607    );
7608    assert_eq!(st.get_spendable_balance(account_id, policy), Zatoshis::ZERO);
7609
7610    // One more block confirms the note. The anchor height is then the note's own block, below
7611    // shard 1's end at `birthday + 1`.
7612    let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
7613    let (h, _, _) = st.generate_next_block(
7614        &not_our_key,
7615        AddressType::DefaultExternal,
7616        Zatoshis::const_from_u64(1000),
7617    );
7618    st.scan_cached_blocks(h, 1);
7619    assert_eq!(
7620        st.get_spendable_balance(account_id, policy),
7621        SHARD_1_NOTE_VALUE
7622    );
7623
7624    let to = T::sk_default_address(&T::sk(&[0xcc; 32]));
7625    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
7626        to.to_zcash_address(st.network()),
7627        Zatoshis::const_from_u64(10_000),
7628    )])
7629    .unwrap();
7630    let change_strategy =
7631        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
7632    let proposal = st
7633        .propose_transfer(
7634            account_id,
7635            &GreedyInputSelector::new(),
7636            &change_strategy,
7637            request,
7638            policy,
7639        )
7640        .unwrap();
7641    let txids = st
7642        .create_proposed_transactions::<std::convert::Infallible, _, std::convert::Infallible, _>(
7643            &usk,
7644            OvkPolicy::Sender,
7645            &proposal,
7646        )
7647        .unwrap();
7648    assert_eq!(txids.len(), 1);
7649}
7650
7651/// The anchor for a new transaction is the tree state `trusted` confirmations below the
7652/// target, or absent. The wallet never substitutes an older tree state: an anchor older than
7653/// the policy depth would publish, on chain, how far behind the tip the wallet was when it
7654/// spent. Every height within the pruning window is checkpointed, so scanned empty blocks do
7655/// not move the anchor below the policy depth.
7656pub fn anchor_is_policy_depth_state_or_absent<T, Dsf>(ds_factory: Dsf, cache: impl TestCache)
7657where
7658    T: ShieldedPoolTester,
7659    Dsf: DataStoreFactory,
7660    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
7661{
7662    let (mut st, account_id, _usk) = build_stable_shard_fixture::<T, Dsf>(ds_factory, cache);
7663    let policy = ConfirmationsPolicy::default();
7664
7665    // Synced to the tip: the anchor sits exactly `trusted` below the target.
7666    let (target, anchor) = st
7667        .wallet()
7668        .get_target_and_anchor_heights(policy.trusted())
7669        .unwrap()
7670        .expect("a synced wallet has an anchor");
7671    assert_eq!(anchor, policy.anchor_height(target));
7672    assert_eq!(
7673        st.get_spendable_balance(account_id, policy),
7674        SHARD_1_NOTE_VALUE
7675    );
7676
7677    // Reopen after an offline period longer than the pruning window. The sync loop's first
7678    // act is `update_chain_tip`; nothing above the old tip has been scanned.
7679    let scanned_tip = st
7680        .wallet()
7681        .chain_height()
7682        .unwrap()
7683        .expect("chain tip is known");
7684    let advance = PRUNING_DEPTH + 10;
7685    st.wallet_mut()
7686        .update_chain_tip(scanned_tip + advance)
7687        .unwrap();
7688
7689    assert_eq!(
7690        st.wallet()
7691            .get_target_and_anchor_heights(policy.trusted())
7692            .unwrap(),
7693        None,
7694        "no checkpoint exists at the policy anchor, so there must be no anchor at all",
7695    );
7696    assert_eq!(st.get_spendable_balance(account_id, policy), Zatoshis::ZERO);
7697
7698    let to = T::sk_default_address(&T::sk(&[0xf5; 32]));
7699    let request = TransactionRequest::new(vec![Payment::without_memo(
7700        to.to_zcash_address(st.network()),
7701        Zatoshis::const_from_u64(10000),
7702    )])
7703    .unwrap();
7704    let change_strategy =
7705        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
7706    let input_selector = GreedyInputSelector::new();
7707    assert_matches!(
7708        st.propose_transfer(
7709            account_id,
7710            &input_selector,
7711            &change_strategy,
7712            request,
7713            policy
7714        ),
7715        Err(Error::ScanRequired)
7716    );
7717
7718    // Catch up. Once the block at the policy anchor is scanned, the anchor returns at exactly
7719    // `trusted` below the new target and the note is spendable again.
7720    let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
7721    for _ in 0..advance {
7722        st.generate_next_block(
7723            &not_our_key,
7724            AddressType::DefaultExternal,
7725            Zatoshis::const_from_u64(1000),
7726        );
7727    }
7728    st.scan_cached_blocks(scanned_tip + 1, advance as usize);
7729    let (target, anchor) = st
7730        .wallet()
7731        .get_target_and_anchor_heights(policy.trusted())
7732        .unwrap()
7733        .expect("a caught-up wallet has an anchor");
7734    assert_eq!(anchor, policy.anchor_height(target));
7735    assert_eq!(
7736        st.get_spendable_balance(account_id, policy),
7737        SHARD_1_NOTE_VALUE
7738    );
7739
7740    // Scanned empty blocks carry no new commitments, but every height within the pruning
7741    // window is checkpointed, so the anchor stays at the policy depth once it lies among them.
7742    let last_filler = st
7743        .wallet()
7744        .chain_height()
7745        .unwrap()
7746        .expect("chain tip is known");
7747    let empty_blocks = u32::from(policy.trusted()) + 2;
7748    for _ in 0..empty_blocks {
7749        st.generate_empty_block();
7750    }
7751    st.scan_cached_blocks(last_filler + 1, empty_blocks as usize);
7752    let (target, anchor) = st
7753        .wallet()
7754        .get_target_and_anchor_heights(policy.trusted())
7755        .unwrap()
7756        .expect("a wallet synced across empty blocks has an anchor");
7757    assert!(
7758        policy.anchor_height(target) > last_filler,
7759        "test invariant: the policy depth must lie among the empty blocks",
7760    );
7761    assert_eq!(anchor, policy.anchor_height(target));
7762    assert_eq!(
7763        st.get_spendable_balance(account_id, policy),
7764        SHARD_1_NOTE_VALUE
7765    );
7766}
7767
7768/// The spendable balance that the wallet summary reports equals the value of the notes that note
7769/// selection returns for the same confirmations policy, through both selection paths, in each of
7770/// several wallet states: confirmed notes, an unconfirmed note, a chain tip advance shorter than
7771/// the anchor depth, a chain tip advance far beyond the pruning window, and after the wallet
7772/// scans to the new tip.
7773pub fn spendable_balance_agrees_with_note_selection<T, Dsf>(ds_factory: Dsf, cache: impl TestCache)
7774where
7775    T: ShieldedPoolTester,
7776    Dsf: DataStoreFactory,
7777    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
7778{
7779    /// The number of wallet notes received before the first comparison.
7780    const RECEIVED_NOTES: u32 = 3;
7781    /// The number of blocks by which a small chain tip advance moves the tip; fewer than the
7782    /// trusted confirmations of the default policy.
7783    const SMALL_TIP_ADVANCE: u32 = 2;
7784    /// The number of blocks beyond the pruning depth by which a far chain tip advance moves the
7785    /// tip.
7786    const FAR_TIP_ADVANCE_BEYOND_WINDOW: u32 = 20;
7787
7788    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
7789    let account_id = st.test_account().unwrap().id();
7790    let policy = ConfirmationsPolicy::default();
7791    let fvk = T::test_account_fvk(&st);
7792    let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
7793    let note_value = Zatoshis::const_from_u64(100_000);
7794    let filler_value = Zatoshis::const_from_u64(1000);
7795
7796    macro_rules! assert_agreement {
7797        ($state:expr) => {{
7798            let chain_tip = st
7799                .wallet()
7800                .chain_height()
7801                .unwrap()
7802                .expect("chain tip is known");
7803            let target_height = TargetHeight::from(chain_tip + 1);
7804            let summary = st.get_spendable_balance(account_id, policy);
7805            let selected_value = |target_value| {
7806                T::select_spendable_notes(&st, account_id, target_value, target_height, policy, &[])
7807                    .unwrap()
7808                    .iter()
7809                    .map(|note| T::note_value(note.note()))
7810                    .try_fold(Zatoshis::ZERO, |sum, value| sum + value)
7811                    .expect("the selected value is in range")
7812            };
7813            assert_eq!(
7814                selected_value(TargetValue::AllFunds(MaxSpendMode::MaxSpendable)),
7815                summary,
7816                "selection of all spendable funds disagrees with the summary: {}",
7817                $state,
7818            );
7819            assert_eq!(
7820                selected_value(TargetValue::AtLeast(Zatoshis::const_from_u64(MAX_MONEY))),
7821                summary,
7822                "value-targeted selection disagrees with the summary: {}",
7823                $state,
7824            );
7825            summary
7826        }};
7827    }
7828
7829    let first_note_height = st
7830        .wallet()
7831        .chain_height()
7832        .unwrap()
7833        .map_or_else(|| st.sapling_activation_height(), |tip| tip + 1);
7834    for _ in 0..RECEIVED_NOTES {
7835        st.generate_next_block(&fvk, AddressType::DefaultExternal, note_value);
7836    }
7837    let confirming_blocks = u32::from(policy.untrusted());
7838    for _ in 0..confirming_blocks {
7839        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, filler_value);
7840    }
7841    st.scan_cached_blocks(
7842        first_note_height,
7843        (RECEIVED_NOTES + confirming_blocks) as usize,
7844    );
7845    let confirmed_balance = assert_agreement!("confirmed notes");
7846    assert!(
7847        confirmed_balance > Zatoshis::ZERO,
7848        "test invariant: the confirmed notes must be spendable",
7849    );
7850
7851    let (unconfirmed_height, _, _) =
7852        st.generate_next_block(&fvk, AddressType::DefaultExternal, note_value);
7853    st.scan_cached_blocks(unconfirmed_height, 1);
7854    assert_agreement!("an unconfirmed note");
7855
7856    let tip = st
7857        .wallet()
7858        .chain_height()
7859        .unwrap()
7860        .expect("chain tip is known");
7861    st.wallet_mut()
7862        .update_chain_tip(tip + SMALL_TIP_ADVANCE)
7863        .unwrap();
7864    assert_agreement!("a chain tip advance shorter than the anchor depth");
7865
7866    let far_tip = tip + PRUNING_DEPTH + FAR_TIP_ADVANCE_BEYOND_WINDOW;
7867    st.wallet_mut().update_chain_tip(far_tip).unwrap();
7868    assert_eq!(
7869        assert_agreement!("a chain tip advance far beyond the pruning window"),
7870        Zatoshis::ZERO,
7871        "test invariant: no note is spendable before the wallet scans to the new tip",
7872    );
7873
7874    for _ in u32::from(tip)..u32::from(far_tip) {
7875        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, filler_value);
7876    }
7877    st.scan_cached_blocks(tip + 1, (far_tip - tip) as usize);
7878    assert!(
7879        assert_agreement!("after the wallet scans to the new tip") > confirmed_balance,
7880        "test invariant: every received note must be spendable once the wallet is synced",
7881    );
7882}
7883
7884/// Shard completeness is a property of the scan queue, not of the subtree-root table. A note
7885/// stabilized in the open tip shard, whose shard the server later reports complete while the
7886/// blocks between the wallet's scanned tip and the shard's end remain unscanned, must not be
7887/// reported spendable: the wallet holds no leaves for that region, so no witness against any
7888/// later anchor can be built. Scanning the region restores spendability.
7889pub fn shard_completeness_derives_from_scan_queue<T, Dsf>(ds_factory: Dsf, cache: impl TestCache)
7890where
7891    T: ShieldedPoolTester,
7892    Dsf: DataStoreFactory,
7893    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
7894{
7895    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
7896    let value = Zatoshis::const_from_u64(500_000);
7897    let (note_height, _, _) = st.add_a_single_note_checking_balance(value);
7898    let account_id = st.test_account().unwrap().id();
7899    let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
7900    let filler_value = Zatoshis::const_from_u64(1000);
7901    let policy = ConfirmationsPolicy::default();
7902
7903    // Bury the note beyond the pruning depth so that it stabilizes while its shard is open.
7904    let buried_blocks = PRUNING_DEPTH + 10;
7905    for _ in 0..buried_blocks {
7906        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, filler_value);
7907    }
7908    st.scan_cached_blocks(note_height + 1, buried_blocks as usize);
7909    let scanned_tip = st
7910        .wallet()
7911        .chain_height()
7912        .unwrap()
7913        .expect("chain tip is known");
7914    assert_eq!(st.get_spendable_balance(account_id, policy), value);
7915
7916    // Offline: the server reports the note's shard complete at `shard_end`, the tip advances
7917    // to `new_tip`, and the wallet scans only the pruning window at the new tip. The blocks
7918    // between the old tip and `shard_end` stay unscanned.
7919    let shard_end = scanned_tip + 300;
7920    let new_tip = scanned_tip + 400;
7921    T::put_subtree_roots(
7922        &mut st,
7923        0,
7924        &[CommitmentTreeRoot::from_parts(
7925            shard_end,
7926            T::empty_tree_leaf(),
7927        )],
7928    )
7929    .unwrap();
7930    st.wallet_mut().update_chain_tip(new_tip).unwrap();
7931    for _ in 0..(new_tip - scanned_tip) {
7932        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, filler_value);
7933    }
7934    let window_start = new_tip - (PRUNING_DEPTH - 1);
7935    st.scan_cached_blocks(window_start, PRUNING_DEPTH as usize);
7936
7937    assert_eq!(
7938        st.get_spendable_balance(account_id, policy),
7939        Zatoshis::ZERO,
7940        "the note's shard has unscanned blocks below the pruning window, so the note is not \
7941         witnessable and must not be reported spendable",
7942    );
7943
7944    // Scanning the unscanned region makes the note spendable.
7945    st.scan_cached_blocks(scanned_tip + 1, (window_start - scanned_tip - 1) as usize);
7946    assert_eq!(st.get_spendable_balance(account_id, policy), value);
7947}
7948
7949/// A chain tip advance that leaves the wallet more than the pruning window behind schedules the
7950/// window ahead of the rest of the unscanned range. Scanning only the ranges scheduled above
7951/// [`ScanPriority::ChainTip`] makes a note in a completed shard spendable again, while blocks
7952/// between the previously scanned tip and the window remain unscanned.
7953pub fn completed_shard_note_spendable_after_scanning_anchor_window<T, Dsf>(
7954    ds_factory: Dsf,
7955    cache: impl TestCache,
7956) where
7957    T: ShieldedPoolTester,
7958    Dsf: DataStoreFactory,
7959    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
7960{
7961    let (mut st, account_id, usk) = build_stable_shard_fixture::<T, Dsf>(ds_factory, cache);
7962    let policy = ConfirmationsPolicy::default();
7963    assert_eq!(
7964        st.get_spendable_balance(account_id, policy),
7965        SHARD_1_NOTE_VALUE
7966    );
7967
7968    // Fall behind the chain by twice the pruning window, as a wallet does when it is reopened
7969    // after a period offline.
7970    let scanned_tip = st
7971        .wallet()
7972        .chain_height()
7973        .unwrap()
7974        .expect("chain tip is known");
7975    let advance = 2 * PRUNING_DEPTH;
7976    let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
7977    let filler_value = Zatoshis::const_from_u64(1000);
7978    for _ in 0..advance {
7979        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, filler_value);
7980    }
7981    let new_tip = scanned_tip + advance;
7982    st.wallet_mut().update_chain_tip(new_tip).unwrap();
7983    assert_eq!(
7984        st.get_spendable_balance(account_id, policy),
7985        Zatoshis::ZERO,
7986        "nothing is spendable until the wallet has scanned to the policy anchor",
7987    );
7988
7989    // Scan, in suggested order, only the ranges scheduled ahead of ordinary forward sync.
7990    while let Some(range) = st
7991        .wallet()
7992        .suggest_scan_ranges()
7993        .unwrap()
7994        .into_iter()
7995        .find(|range| range.priority() > ScanPriority::ChainTip)
7996    {
7997        st.scan_cached_blocks(range.block_range().start, range.len());
7998    }
7999
8000    let window_start = new_tip - (PRUNING_DEPTH - 1);
8001    let unscanned = st.wallet().suggest_scan_ranges().unwrap();
8002    assert!(
8003        unscanned
8004            .iter()
8005            .any(|range| range.block_range().start < window_start),
8006        "test invariant: blocks below the pruning window must remain unscanned: {unscanned:?}",
8007    );
8008    assert_eq!(
8009        st.get_spendable_balance(account_id, policy),
8010        SHARD_1_NOTE_VALUE,
8011        "once the pruning window is scanned, the completed-shard note must be spendable",
8012    );
8013    assert_recovered_balance_spends::<T, _, _, _, _, _>(
8014        &mut st,
8015        account_id,
8016        &usk,
8017        SHARD_1_NOTE_VALUE,
8018    );
8019}
8020
8021/// `Checkpoint` retention covers every height within `PRUNING_DEPTH` of the chain tip, so a
8022/// commitment-free stretch of blocks never leaves the wallet without an anchor at the policy
8023/// depth. A note in the open tip shard, whose settled height advances with the pruning floor,
8024/// therefore stays spendable across such a stretch.
8025pub fn open_shard_note_spendable_across_commitment_free_stretch<T, Dsf>(
8026    ds_factory: Dsf,
8027    cache: impl TestCache,
8028) where
8029    T: ShieldedPoolTester,
8030    Dsf: DataStoreFactory,
8031    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
8032{
8033    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
8034    let value = Zatoshis::const_from_u64(500_000);
8035    let (note_height, _, _) = st.add_a_single_note_checking_balance(value);
8036    let account_id = st.test_account().unwrap().id();
8037    let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
8038    let policy = ConfirmationsPolicy::default();
8039
8040    // Bury the note beyond the pruning depth so that it stabilizes while its shard is open.
8041    let buried_blocks = PRUNING_DEPTH + 10;
8042    for _ in 0..buried_blocks {
8043        st.generate_next_block(
8044            &not_our_key,
8045            AddressType::DefaultExternal,
8046            Zatoshis::const_from_u64(1000),
8047        );
8048    }
8049    st.scan_cached_blocks(note_height + 1, buried_blocks as usize);
8050    let last_commitment = st
8051        .wallet()
8052        .chain_height()
8053        .unwrap()
8054        .expect("chain tip is known");
8055    assert_eq!(st.get_spendable_balance(account_id, policy), value);
8056
8057    // More than `PRUNING_DEPTH` blocks without a shielded output in any pool, scanned as one
8058    // batch, so no block-end checkpoint is created for any of them.
8059    let stretch = PRUNING_DEPTH + 10;
8060    for _ in 0..stretch {
8061        st.generate_empty_block();
8062    }
8063    st.scan_cached_blocks(last_commitment + 1, stretch as usize);
8064
8065    let (target, anchor) = st
8066        .wallet()
8067        .get_target_and_anchor_heights(policy.trusted())
8068        .unwrap()
8069        .expect("a synced wallet has an anchor");
8070    assert_eq!(
8071        anchor,
8072        policy.anchor_height(target),
8073        "every height within the pruning window is checkpointed, so the anchor is the policy \
8074         depth even though no block there carries a commitment",
8075    );
8076    assert_eq!(st.get_spendable_balance(account_id, policy), value);
8077}
8078
8079/// A note's in-shard witness needs every leaf to its right through the shard's end, and none
8080/// to its left beyond what the frontier inserted when its block was scanned already supplies.
8081/// A note found in the block that completes its shard is therefore spendable while the earlier
8082/// block of that shard remains unscanned.
8083pub fn completed_shard_note_spendable_with_unscanned_gap_below_it<T, Dsf>(
8084    ds_factory: Dsf,
8085    cache: impl TestCache,
8086) where
8087    T: ShieldedPoolTester,
8088    Dsf: DataStoreFactory,
8089    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
8090{
8091    /// The number of non-wallet outputs in Block A1, which precede the wallet note in shard 1.
8092    const BLOCK_A1_FILLERS: u32 = 35;
8093    const NOTE_VALUE: Zatoshis = Zatoshis::const_from_u64(150_000);
8094
8095    let (mut st, account_id, usk, dfvk) = build_shard_1_prefix_fixture::<T, Dsf>(ds_factory, cache);
8096
8097    let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
8098    let filler_value = Zatoshis::const_from_u64(1000);
8099
8100    // Block A1 at the birthday: the first `BLOCK_A1_FILLERS` positions of the gap below the
8101    // end of shard 1, all non-wallet fillers.
8102    let block_a1_outputs: Vec<_> = (0..BLOCK_A1_FILLERS)
8103        .map(|_| {
8104            FakeCompactOutput::new(
8105                not_our_key.clone(),
8106                AddressType::DefaultExternal,
8107                filler_value,
8108            )
8109        })
8110        .collect();
8111    let (block_a1_height, _, _) = st.generate_next_block_multi(&block_a1_outputs);
8112
8113    // Block A2: the wallet note, then fillers through the last position of shard 1.
8114    let block_a2_output_count = SHARD_1_FRONTIER_GAP - BLOCK_A1_FILLERS;
8115    let mut block_a2_outputs = Vec::with_capacity(block_a2_output_count as usize);
8116    block_a2_outputs.push(FakeCompactOutput::new(
8117        dfvk.clone(),
8118        AddressType::DefaultExternal,
8119        NOTE_VALUE,
8120    ));
8121    for _ in 1..block_a2_output_count {
8122        block_a2_outputs.push(FakeCompactOutput::new(
8123            not_our_key.clone(),
8124            AddressType::DefaultExternal,
8125            filler_value,
8126        ));
8127    }
8128    let (block_a2_height, _, _) = st.generate_next_block_multi(&block_a2_outputs);
8129
8130    // Bury shard 1 beyond the pruning depth.
8131    let trailing_blocks = PRUNING_DEPTH + 10;
8132    for _ in 0..trailing_blocks {
8133        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, filler_value);
8134    }
8135    let chain_tip = block_a2_height + trailing_blocks;
8136
8137    // Scan from Block A2 onward only, leaving Block A1 unscanned below the note.
8138    st.wallet_mut().update_chain_tip(chain_tip).unwrap();
8139    st.scan_cached_blocks(block_a2_height, 1);
8140    let shard_1_root = T::shard_root(&mut st, 1).unwrap();
8141    T::put_subtree_roots(
8142        &mut st,
8143        1,
8144        &[CommitmentTreeRoot::from_parts(
8145            block_a2_height,
8146            shard_1_root,
8147        )],
8148    )
8149    .unwrap();
8150    st.scan_cached_blocks(block_a2_height + 1, trailing_blocks as usize);
8151
8152    let unscanned = st.wallet().suggest_scan_ranges().unwrap();
8153    assert!(
8154        unscanned
8155            .iter()
8156            .any(|range| range.block_range().contains(&block_a1_height)),
8157        "test invariant: Block A1 must remain unscanned: {unscanned:?}",
8158    );
8159
8160    assert_eq!(
8161        st.get_spendable_balance(account_id, ConfirmationsPolicy::default()),
8162        NOTE_VALUE,
8163        "every leaf after the note through its shard's end is present, so the note is \
8164         witnessable and must be spendable",
8165    );
8166    assert_recovered_balance_spends::<T, _, _, _, _, _>(&mut st, account_id, &usk, NOTE_VALUE);
8167}
8168
8169/// A note's settled height (`witness_settled_height`) is a claim about the chain the wallet
8170/// was observing when the height was written: every block bearing on the note's witness
8171/// context up to that height has been scanned, so the wallet's determination of witness
8172/// constructability is grounded in chain data it has verified. A rewind that truncates wallet
8173/// state below a settled height discards the scanned blocks and tree data backing that claim,
8174/// so the claim must not survive the truncation.
8175///
8176/// This test drives the false positive that arises if it does. A change note is mined at
8177/// the chain tip and stabilizes with its settled height at its own mined height. A reorg then
8178/// rewinds the wallet three blocks below that height, and the same transaction is
8179/// re-mined two blocks lower on the new chain, with a non-wallet output in the block
8180/// directly above it that the wallet does not (yet) scan. Once the new chain advances far
8181/// enough that the unscanned block falls below the chain-tip pruning window, the
8182/// window-scanned check no longer sees the gap, and the stale settled height — exactly at
8183/// the gap's upper boundary — vouches that the region between the note and the window is
8184/// durably scanned. Every spendability check then passes and the wallet reports the note
8185/// spendable, even though that determination rests on blocks that exist only on the
8186/// reorged-away chain: the unscanned gap on the new chain has been neither
8187/// hash-chain-verified nor checked for spends of the wallet's notes.
8188///
8189/// The truncation must instead clear the settled height. The note then re-stabilizes from
8190/// new-chain data only once the gap is scanned, so the wallet reports zero
8191/// spendable value while the gap remains, and the note becomes spendable when the gap is
8192/// scanned.
8193pub fn stabilized_note_settled_height_invalidated_by_reorg<T, Dsf>(
8194    ds_factory: Dsf,
8195    cache: impl TestCache,
8196) where
8197    T: ShieldedPoolTester,
8198    Dsf: DataStoreFactory,
8199    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
8200{
8201    let (mut st, account_id, usk) = build_stable_shard_fixture::<T, Dsf>(ds_factory, cache);
8202    let policy = ConfirmationsPolicy::default();
8203
8204    // Baseline: the fixture note is stabilized and spendable.
8205    assert_eq!(
8206        st.get_spendable_balance(account_id, policy),
8207        SHARD_1_NOTE_VALUE,
8208        "fixture must report the stabilized note as spendable under the default policy",
8209    );
8210
8211    // Spend the fixture note, producing a wallet transaction whose change note carries
8212    // the settled height under test. (A received note cannot be used here: re-mining
8213    // the *same* transaction at a different height is what lets the note row keep its
8214    // settled height across the reorg, and only wallet-created transactions can be mined
8215    // into the fake chain twice.) The proposal is created against the fixture chain
8216    // state, before the additional blocks below are generated, so input selection can
8217    // only see the fixture note.
8218    let to = T::sk_default_address(&T::sk(&[0xf5; 32]));
8219    let request = TransactionRequest::new(vec![Payment::without_memo(
8220        to.to_zcash_address(st.network()),
8221        Zatoshis::const_from_u64(10000),
8222    )])
8223    .unwrap();
8224    let change_strategy =
8225        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
8226    let input_selector = GreedyInputSelector::new();
8227    let proposal = st
8228        .propose_transfer(
8229            account_id,
8230            &input_selector,
8231            &change_strategy,
8232            request,
8233            policy,
8234        )
8235        .unwrap();
8236    let txid = st
8237        .create_proposed_transactions::<Infallible, _, Infallible, _>(
8238            &usk,
8239            OvkPolicy::Sender,
8240            &proposal,
8241        )
8242        .unwrap()[0];
8243
8244    // Extend the old chain by three scanned blocks: a second wallet note, a non-wallet
8245    // filler, and the transaction created above. The second wallet note is structural:
8246    // it occupies the first note-commitment-tree position that the upcoming rewind
8247    // truncates away. A marked (wallet-note) leaf keeps its pruned sibling's hash stored
8248    // explicitly, so truncating at its boundary cleanly splits the pair; were the leaf a
8249    // pruned non-wallet commitment, truncation would leave behind a merged hash node
8250    // spanning the boundary, and re-scanning the divergent chain would hit a note
8251    // commitment tree insertion conflict instead of exercising the spendability rule.
8252    let dfvk = T::sk_to_fvk(T::usk_to_sk(&usk));
8253    let extra_note_value = Zatoshis::const_from_u64(25000);
8254    let (extra_height, _, _) =
8255        st.generate_next_block(&dfvk, AddressType::DefaultExternal, extra_note_value);
8256
8257    let not_our_fvk = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
8258    let filler_value = Zatoshis::const_from_u64(1000);
8259    st.generate_next_block(&not_our_fvk, AddressType::DefaultExternal, filler_value);
8260
8261    let (tx_height, _) = st.generate_next_block_including(txid);
8262
8263    // Scan all three blocks in a single batch. This matters for the tree surgery below:
8264    // scanning in one batch writes no batch-boundary frontier (and thus no cached
8265    // interior-node hash annotations) above the rewind target, so truncating there and
8266    // re-scanning the divergent chain does not conflict with stale annotations. The
8267    // change note lands in the open chain-tip shard, which has no unscanned range after
8268    // the batch, so it stabilizes immediately with its settled height at its own mined
8269    // height (above the pruning floor).
8270    st.scan_cached_blocks(extra_height, 3);
8271
8272    // The wallet's whole balance is now the change note plus the second wallet note (the
8273    // fixture note is spent). The reorg below permanently un-mines the second note, so
8274    // the recovered balance at the end of the test is the change value alone.
8275    let change_value = (st.get_total_balance(account_id) - extra_note_value)
8276        .expect("balance covers the extra note value");
8277    assert!(change_value > Zatoshis::ZERO);
8278
8279    // Reorg: rewind the wallet to three blocks below the transaction's mined height —
8280    // just below the second wallet note. This truncates the tree data above the rewind
8281    // target, including everything the change note's settled height vouches for, and
8282    // un-mines both the transaction and the second note. The block cache is truncated
8283    // separately so that the chain regenerated below diverges from the reorged-away one.
8284    let rewind_target = tx_height - 3;
8285    st.wallet_mut()
8286        .rewind_to_chain_state(
8287            ChainState::empty(rewind_target, BlockHash([0; 32])),
8288            HashSet::new(),
8289        )
8290        .expect("rewind_to_chain_state should succeed");
8291    st.truncate_cache_to_height(rewind_target);
8292
8293    // On the new chain, the same transaction is re-mined two blocks lower than before
8294    // (the second wallet note is not re-mined at all)...
8295    let (remine_height, _) = st.generate_next_block_including(txid);
8296    assert_eq!(remine_height, tx_height - 2);
8297
8298    // ...with a non-wallet output in the block directly above it. The output makes the
8299    // gap material: the wallet can obtain that commitment's value only by scanning the
8300    // gap block or by trusting a server-supplied frontier, and until the block is
8301    // scanned it may conceal spends of the wallet's notes.
8302    let (gap_height, _, _) =
8303        st.generate_next_block(&not_our_fvk, AddressType::DefaultExternal, filler_value);
8304    assert_eq!(gap_height, tx_height - 1);
8305
8306    // Extend the new chain with single-output filler blocks (empty blocks would leave
8307    // the note commitment tree without checkpoints at the new heights, clamping the
8308    // wallet's anchor selection below the region under test) until the gap block sits
8309    // just below the pruning window of the new tip
8310    // (`new_tip - PRUNING_DEPTH = gap_height + 1`).
8311    let mut new_tip = gap_height;
8312    for _ in 0..(PRUNING_DEPTH + 1) {
8313        new_tip = st
8314            .generate_next_block(&not_our_fvk, AddressType::DefaultExternal, filler_value)
8315            .0;
8316    }
8317
8318    // Scan the re-mined transaction's block, then everything above the gap block, which
8319    // is deliberately left unscanned: it is the only hole in the wallet's view of the
8320    // new chain, and it lies below the pruning window, where only the note's settled
8321    // height guards against it.
8322    st.scan_cached_blocks(remine_height, 1);
8323    st.wallet_mut().update_chain_tip(new_tip).unwrap();
8324    st.scan_cached_blocks(gap_height + 1, (PRUNING_DEPTH + 1) as usize);
8325
8326    // The change note's old settled height (its old-chain mined height) sits exactly at
8327    // the top of the unscanned gap; were it to survive the truncation, it would vouch that
8328    // the gap does not matter and the note would be reported spendable. The truncation
8329    // must instead have cleared it, and the note must not have re-stabilized while its
8330    // shard holds the unscanned gap.
8331    assert_eq!(
8332        st.get_spendable_balance(account_id, policy),
8333        Zatoshis::ZERO,
8334        "a settled height written on the reorged-away chain must not vouch for \
8335         spendability while the new chain has an unscanned gap below the pruning window",
8336    );
8337
8338    // Scanning the gap block closes the hole: the change note re-stabilizes from
8339    // new-chain data and becomes spendable.
8340    st.scan_cached_blocks(gap_height, 1);
8341    assert_eq!(
8342        st.get_spendable_balance(account_id, policy),
8343        change_value,
8344        "closing the gap must restore spendability of the change note",
8345    );
8346}
8347
8348pub fn reorg_to_checkpoint<T: ShieldedPoolTester, Dsf, C>(ds_factory: Dsf, cache: C)
8349where
8350    Dsf: DataStoreFactory,
8351    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
8352    C: TestCache,
8353{
8354    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
8355
8356    let account = st.test_account().cloned().unwrap();
8357
8358    // Create a sequence of blocks to serve as the foundation of our chain state.
8359    let p0_fvk = T::random_fvk(st.rng_mut());
8360    let gen_random_block = |st: &mut TestState<C, Dsf::DataStore, LocalNetwork>,
8361                            output_count: usize| {
8362        let fake_outputs =
8363            std::iter::repeat_with(|| FakeCompactOutput::random(st.rng_mut(), p0_fvk.clone()))
8364                .take(output_count)
8365                .collect::<Vec<_>>();
8366        st.generate_next_block_multi(&fake_outputs[..]);
8367        output_count
8368    };
8369
8370    // The stable portion of the tree will contain 20 notes.
8371    for _ in 0..10 {
8372        gen_random_block(&mut st, 4);
8373    }
8374
8375    // We will reorg to this height.
8376    let reorg_height = account.birthday().height() + 4;
8377    let reorg_position = Position::from(19);
8378
8379    // Scan the first 5 blocks. The last block in this sequence will be where we simulate a
8380    // reorg.
8381    st.scan_cached_blocks(account.birthday().height(), 5);
8382    assert_eq!(
8383        st.wallet()
8384            .block_max_scanned()
8385            .unwrap()
8386            .unwrap()
8387            .block_height(),
8388        reorg_height
8389    );
8390
8391    // There will be 6 checkpoints: one for the prior block frontier, and then one for each scanned
8392    // block.
8393    let checkpoints = st
8394        .wallet()
8395        .get_checkpoint_history(&T::SHIELDED_PROTOCOL)
8396        .unwrap();
8397    assert_eq!(checkpoints.len(), 6);
8398    assert_eq!(
8399        checkpoints.last(),
8400        Some(&(reorg_height, Some(reorg_position)))
8401    );
8402
8403    // Scan another block, then simulate a reorg.
8404    st.scan_cached_blocks(reorg_height + 1, 1);
8405    assert_eq!(
8406        st.wallet()
8407            .block_max_scanned()
8408            .unwrap()
8409            .unwrap()
8410            .block_height(),
8411        reorg_height + 1
8412    );
8413    let checkpoints = st
8414        .wallet()
8415        .get_checkpoint_history(&T::SHIELDED_PROTOCOL)
8416        .unwrap();
8417    assert_eq!(checkpoints.len(), 7);
8418    assert_eq!(
8419        checkpoints.last(),
8420        Some(&(reorg_height + 1, Some(reorg_position + 4)))
8421    );
8422
8423    //        /\  /\  /\
8424    //  .... /\/\/\/\/\/\
8425    //          c   d   e
8426
8427    // Truncate back to the reorg height, but retain the block cache.
8428    st.truncate_to_height_retaining_cache(reorg_height);
8429
8430    // The following error-prone tree state is generated by the a previous (buggy) truncate
8431    // implementation:
8432    //        /\  /\
8433    //  .... /\/\/\/\
8434    //          c
8435
8436    // We have pruned back to the original checkpoints & tree state.
8437    let checkpoints = st
8438        .wallet()
8439        .get_checkpoint_history(&T::SHIELDED_PROTOCOL)
8440        .unwrap();
8441    assert_eq!(checkpoints.len(), 6);
8442    assert_eq!(
8443        checkpoints.last(),
8444        Some(&(reorg_height, Some(reorg_position)))
8445    );
8446
8447    // Skip two blocks, then (re) scan the same block.
8448    st.scan_cached_blocks(reorg_height + 2, 1);
8449
8450    // Given the buggy truncation, this would result in this the following tree state:
8451    //        /\  /\   \  /\
8452    //  .... /\/\/\/\   \/\/\
8453    //          c       e   f
8454
8455    let checkpoints = st
8456        .wallet()
8457        .get_checkpoint_history(&T::SHIELDED_PROTOCOL)
8458        .unwrap();
8459    // Even though we only scanned one block, we get a checkpoint at both the start and the end of
8460    // the block due to the insertion of the prior block frontier.
8461    assert_eq!(checkpoints.len(), 8);
8462    assert_eq!(
8463        checkpoints.last(),
8464        Some(&(reorg_height + 2, Some(reorg_position + 8)))
8465    );
8466
8467    // Now, fully truncate back to the reorg height. This should leave the tree in a state
8468    // where it can be added to with arbitrary notes.
8469    st.truncate_to_height(reorg_height);
8470
8471    // Generate some new random blocks
8472    for _ in 0..10 {
8473        let output_count = st.rng_mut().random_range(2..10);
8474        gen_random_block(&mut st, output_count);
8475    }
8476
8477    // The previous truncation retained the cache, so re-scanning the same blocks would have
8478    // resulted in the same note commitment tree state, and hence no conflicts; could occur. Now
8479    // that we have cleared the cache and generated a different sequence blocks, if truncation did
8480    // not completely clear the tree state this would generates a note commitment tree conflict.
8481    st.scan_cached_blocks(reorg_height + 1, 1);
8482}
8483
8484pub fn scan_cached_blocks_allows_blocks_out_of_order<T: ShieldedPoolTester>(
8485    ds_factory: impl DataStoreFactory,
8486    cache: impl TestCache,
8487) {
8488    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
8489
8490    let account = st.test_account().cloned().unwrap();
8491    let dfvk = T::test_account_fvk(&st);
8492
8493    let value = Zatoshis::const_from_u64(50000);
8494    let (h1, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
8495    st.scan_cached_blocks(h1, 1);
8496    assert_eq!(st.get_total_balance(account.id()), value);
8497
8498    // Create blocks to reach height + 2
8499    let (h2, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
8500    let (h3, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
8501
8502    // Scan the later block first
8503    st.scan_cached_blocks(h3, 1);
8504
8505    // Now scan the block of height height + 1
8506    st.scan_cached_blocks(h2, 1);
8507    assert_eq!(
8508        st.get_total_balance(account.id()),
8509        Zatoshis::const_from_u64(150_000)
8510    );
8511
8512    // We can spend the received notes
8513    let req = TransactionRequest::new(vec![Payment::without_memo(
8514        T::fvk_default_address(&dfvk).to_zcash_address(st.network()),
8515        Zatoshis::const_from_u64(110_000),
8516    )])
8517    .unwrap();
8518
8519    let input_selector = GreedyInputSelector::new();
8520    let change_strategy =
8521        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
8522
8523    assert_matches!(
8524        st.spend(
8525            &input_selector,
8526            &change_strategy,
8527            account.usk(),
8528            req,
8529            OvkPolicy::Sender,
8530            ConfirmationsPolicy::MIN,
8531        ),
8532        Ok(_)
8533    );
8534}
8535
8536pub fn scan_cached_blocks_finds_received_notes<T: ShieldedPoolTester, Dsf>(
8537    ds_factory: Dsf,
8538    cache: impl TestCache,
8539) where
8540    Dsf: DataStoreFactory,
8541    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
8542{
8543    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
8544
8545    let account = st.test_account().cloned().unwrap();
8546    let dfvk = T::test_account_fvk(&st);
8547
8548    // Wallet summary is not yet available
8549    assert_eq!(st.get_wallet_summary(ConfirmationsPolicy::MIN), None);
8550
8551    // Create a fake CompactBlock sending value to the address
8552    let value = Zatoshis::const_from_u64(50000);
8553    let (h1, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
8554
8555    // Scan the cache
8556    let summary = st.scan_cached_blocks(h1, 1);
8557    assert_eq!(summary.scanned_range().start, h1);
8558    assert_eq!(summary.scanned_range().end, h1 + 1);
8559    assert_eq!(T::received_note_count(&summary), 1);
8560
8561    // Account balance should reflect the received note
8562    assert_eq!(st.get_total_balance(account.id()), value);
8563
8564    // Create a second fake CompactBlock sending more value to the address
8565    let value2 = Zatoshis::const_from_u64(70000);
8566    let (h2, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value2);
8567
8568    // Scan the cache again
8569    let summary = st.scan_cached_blocks(h2, 1);
8570    assert_eq!(summary.scanned_range().start, h2);
8571    assert_eq!(summary.scanned_range().end, h2 + 1);
8572    assert_eq!(T::received_note_count(&summary), 1);
8573
8574    // Account balance should reflect both received notes
8575    assert_eq!(
8576        st.get_total_balance(account.id()),
8577        (value + value2).unwrap()
8578    );
8579}
8580
8581pub fn scan_cached_blocks_finds_change_notes<T: ShieldedPoolTester, Dsf>(
8582    ds_factory: Dsf,
8583    cache: impl TestCache,
8584) where
8585    Dsf: DataStoreFactory,
8586    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
8587{
8588    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
8589
8590    let account = st.test_account().cloned().unwrap();
8591    let dfvk = T::test_account_fvk(&st);
8592
8593    // Wallet summary is not yet available
8594    assert_eq!(st.get_wallet_summary(ConfirmationsPolicy::MIN), None);
8595
8596    // Create a fake CompactBlock sending value to the address
8597    let value = Zatoshis::const_from_u64(50000);
8598    let (_, _, nf) = st.add_a_single_note_checking_balance(value);
8599
8600    // Create a second fake CompactBlock spending value from the address
8601    let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
8602    let to2 = T::fvk_default_address(&not_our_key);
8603    let value2 = Zatoshis::const_from_u64(20000);
8604    let (spent_height, _) = st.generate_next_block_spending(&dfvk, (nf, value), to2, value2);
8605
8606    // Scan the cache again
8607    st.scan_cached_blocks(spent_height, 1);
8608
8609    // Account balance should equal the change
8610    assert_eq!(
8611        st.get_total_balance(account.id()),
8612        (value - value2).unwrap()
8613    );
8614}
8615
8616pub fn scan_cached_blocks_detects_spends_out_of_order<T: ShieldedPoolTester, Dsf>(
8617    ds_factory: Dsf,
8618    cache: impl TestCache,
8619) where
8620    Dsf: DataStoreFactory,
8621    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
8622{
8623    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
8624
8625    let account = st.test_account().cloned().unwrap();
8626    let dfvk = T::test_account_fvk(&st);
8627
8628    // Wallet summary is not yet available
8629    assert_eq!(st.get_wallet_summary(ConfirmationsPolicy::MIN), None);
8630
8631    // Create a fake CompactBlock sending value to the address
8632    let value = Zatoshis::const_from_u64(50000);
8633    let (received_height, _, nf) =
8634        st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
8635
8636    // Create a second fake CompactBlock spending value from the address
8637    let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
8638    let to2 = T::fvk_default_address(&not_our_key);
8639    let value2 = Zatoshis::const_from_u64(20000);
8640    let (spent_height, _) = st.generate_next_block_spending(&dfvk, (nf, value), to2, value2);
8641
8642    // Scan the spending block first.
8643    st.scan_cached_blocks(spent_height, 1);
8644
8645    // Account balance should equal the change
8646    assert_eq!(
8647        st.get_total_balance(account.id()),
8648        (value - value2).unwrap()
8649    );
8650
8651    // Now scan the block in which we received the note that was spent.
8652    st.scan_cached_blocks(received_height, 1);
8653
8654    // Account balance should be the same.
8655    assert_eq!(
8656        st.get_total_balance(account.id()),
8657        (value - value2).unwrap()
8658    );
8659}
8660
8661/// Note selection draws the OLDEST eligible notes first, where age is chain order — the note's
8662/// commitment tree position — not discovery order. Priority scanning discovers recent blocks
8663/// before back-filling history, so a restored wallet's newest notes carry its lowest row ids;
8664/// ordering by id would spend fresh change while far older notes sat idle. The ordering must
8665/// therefore survive scanning blocks out of order.
8666pub fn oldest_note_is_selected_first<T: ShieldedPoolTester, Dsf>(
8667    ds_factory: Dsf,
8668    cache: impl TestCache,
8669) where
8670    Dsf: DataStoreFactory,
8671{
8672    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
8673    let account = st.test_account().cloned().unwrap();
8674    let dfvk = T::test_account_fvk(&st);
8675
8676    // Two notes; the OLDER one is larger, so which note a small selection returns identifies
8677    // the ordering in use.
8678    let older_value = Zatoshis::const_from_u64(500_000);
8679    let newer_value = Zatoshis::const_from_u64(300_000);
8680    let (older_height, _, _) =
8681        st.generate_next_block(&dfvk, AddressType::DefaultExternal, older_value);
8682    let (newer_height, _, _) =
8683        st.generate_next_block(&dfvk, AddressType::DefaultExternal, newer_value);
8684
8685    // Scan the NEWER block first: its note is discovered first and takes the lower row id,
8686    // exactly as happens to recent notes when a restored wallet syncs tip-first.
8687    st.scan_cached_blocks(newer_height, 1);
8688    st.scan_cached_blocks(older_height, 1);
8689
8690    // Either note alone covers the target, so selection returns exactly one — the OLDER.
8691    let selected = T::select_spendable_notes(
8692        &st,
8693        account.id(),
8694        TargetValue::AtLeast(Zatoshis::const_from_u64(200_000)),
8695        TargetHeight::from(newer_height + 1),
8696        ConfirmationsPolicy::MIN,
8697        &[],
8698    )
8699    .unwrap();
8700    assert_eq!(selected.len(), 1, "a single note covers the target");
8701    assert_eq!(
8702        T::note_value(selected.first().expect("nonempty").note()),
8703        older_value,
8704        "the oldest sufficient note must be drawn first, not the first-discovered"
8705    );
8706}
8707
8708pub fn metadata_queries_exclude_unwanted_notes<T: ShieldedPoolTester, Dsf, TC>(
8709    ds_factory: Dsf,
8710    cache: TC,
8711) where
8712    Dsf: DataStoreFactory,
8713    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
8714    TC: TestCache,
8715{
8716    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
8717
8718    // Create 10 blocks with successively increasing value
8719    let note_values = (1..=10)
8720        .map(|i| Zatoshis::const_from_u64(i * 100_0000))
8721        .collect::<Vec<_>>();
8722    let h0 = st
8723        .add_notes_checking_balance(note_values.clone().into_iter().map(Some))
8724        .first_block_height()
8725        .unwrap();
8726
8727    let target_height = TargetHeight::from(h0 + 10);
8728    let account = st.test_account().cloned().unwrap();
8729    let test_meta = |st: &TestState<TC, Dsf::DataStore, LocalNetwork>, query, expected_count| {
8730        let metadata = st
8731            .wallet()
8732            .get_account_metadata(
8733                account.id(),
8734                &query,
8735                target_height,
8736                &[],
8737                LockFilter::Unfiltered,
8738            )
8739            .unwrap();
8740
8741        assert_eq!(metadata.note_count(T::SHIELDED_PROTOCOL), expected_count);
8742    };
8743
8744    test_meta(
8745        &st,
8746        NoteFilter::ExceedsMinValue(Zatoshis::const_from_u64(1000_0000)),
8747        Some(0),
8748    );
8749    test_meta(
8750        &st,
8751        NoteFilter::ExceedsMinValue(Zatoshis::const_from_u64(500_0000)),
8752        Some(5),
8753    );
8754    test_meta(
8755        &st,
8756        NoteFilter::ExceedsBalancePercentage(BoundedU8::new_const(10)),
8757        Some(5),
8758    );
8759
8760    // We haven't sent any funds yet, so we can't evaluate this query
8761    test_meta(
8762        &st,
8763        NoteFilter::ExceedsPriorSendPercentile(BoundedU8::new_const(50)),
8764        None,
8765    );
8766
8767    // Spend half of each one of our notes, so that we can get a distribution of sent note values.
8768    // FIXME: This test is currently excessively specialized to the `zcash_client_sqlite::WalletDb`
8769    // implmentation of the `InputSource` trait. A better approach would be to create a test input
8770    // source that can select a set of notes directly based upon their nullifiers.
8771    let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
8772    let to = T::fvk_default_address(&not_our_key).to_zcash_address(st.network());
8773    let nz2 = NonZeroU64::new(2).unwrap();
8774
8775    for value in &note_values {
8776        let txids = st
8777            .create_standard_transaction(&account, to.clone(), *value / nz2)
8778            .unwrap();
8779        st.generate_next_block_including(txids.head);
8780    }
8781    st.scan_cached_blocks(h0 + 10, 10);
8782
8783    // Since we've spent half our notes, our remaining notes each have approximately half their
8784    // original value. The 50th percentile of our spends should be 250_0000 ZAT, and half of our
8785    // remaining notes should have value greater than that.
8786    test_meta(
8787        &st,
8788        NoteFilter::ExceedsPriorSendPercentile(BoundedU8::new_const(50)),
8789        Some(5),
8790    );
8791}
8792
8793#[cfg(feature = "pczt")]
8794pub fn pczt_single_step<P0: ShieldedPoolTester, P1: ShieldedPoolTester, Dsf>(
8795    ds_factory: Dsf,
8796    cache: impl TestCache,
8797    pin_expiry_above_target: Option<u32>,
8798) where
8799    Dsf: DataStoreFactory,
8800    <Dsf as DataStoreFactory>::AccountId: serde::Serialize + serde::de::DeserializeOwned,
8801{
8802    let mut st = TestBuilder::new()
8803        .with_data_store_factory(ds_factory)
8804        .with_block_cache(cache)
8805        .with_initial_chain_state(|_, network| {
8806            // Initialize the chain state to after ZIP 212 became enforced.
8807            let birthday_height = std::cmp::max(
8808                network.activation_height(NetworkUpgrade::Nu5).unwrap(),
8809                network.activation_height(NetworkUpgrade::Canopy).unwrap() + ZIP212_GRACE_PERIOD,
8810            );
8811
8812            // Ironwood is not active at these test heights, so its tree is empty.
8813            #[cfg(feature = "orchard")]
8814            let ironwood_initial_tree = Frontier::empty();
8815
8816            InitialChainState {
8817                chain_state: ChainState::new(
8818                    birthday_height - 1,
8819                    BlockHash([5; 32]),
8820                    Frontier::empty(),
8821                    #[cfg(feature = "orchard")]
8822                    Frontier::empty(),
8823                    #[cfg(feature = "orchard")]
8824                    ironwood_initial_tree,
8825                ),
8826                prior_sapling_roots: vec![],
8827                #[cfg(feature = "orchard")]
8828                prior_orchard_roots: vec![],
8829            }
8830        })
8831        .with_account_having_current_birthday()
8832        .build();
8833
8834    let account = st.test_account().cloned().unwrap();
8835
8836    let p0_fvk = P0::test_account_fvk(&st);
8837
8838    let p1_fvk = P1::test_account_fvk(&st);
8839    let p1_to = P1::fvk_default_address(&p1_fvk);
8840
8841    // Only mine a block in P0 to ensure the transactions source is there.
8842    let note_value = Zatoshis::const_from_u64(350000);
8843    st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
8844    st.scan_cached_blocks(account.birthday().height(), 1);
8845
8846    assert_eq!(st.get_total_balance(account.id()), note_value);
8847    assert_eq!(
8848        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
8849        note_value
8850    );
8851
8852    let transfer_amount = Zatoshis::const_from_u64(200000);
8853    let p0_to_p1 = TransactionRequest::new(vec![Payment::without_memo(
8854        p1_to.to_zcash_address(st.network()),
8855        transfer_amount,
8856    )])
8857    .unwrap();
8858
8859    let input_selector = GreedyInputSelector::new();
8860    let change_strategy =
8861        single_output_change_strategy(StandardFeeRule::Zip317, None, P0::SHIELDED_PROTOCOL);
8862    let proposal0 = st
8863        .propose_transfer(
8864            account.id(),
8865            &input_selector,
8866            &change_strategy,
8867            p0_to_p1,
8868            ConfirmationsPolicy::MIN,
8869        )
8870        .unwrap();
8871
8872    let min_target_height = proposal0.min_target_height();
8873    assert_eq!(proposal0.steps().len(), 1);
8874
8875    let expiry_height =
8876        pin_expiry_above_target.map(|delta| BlockHeight::from(min_target_height) + delta);
8877
8878    if expiry_height.is_some() {
8879        // This is rejected before transaction building, so the successful call below
8880        // can reuse the same proposal.
8881        assert_matches!(
8882            st.create_pczt_from_proposal::<Infallible, _, Infallible>(
8883                account.id(),
8884                OvkPolicy::Sender,
8885                &proposal0,
8886                Some(min_target_height.saturating_sub(1)),
8887            ),
8888            Err(Error::ExpiryHeightBelowTargetHeight { .. })
8889        );
8890    }
8891
8892    let create_proposed_result = st.create_pczt_from_proposal::<Infallible, _, Infallible>(
8893        account.id(),
8894        OvkPolicy::Sender,
8895        &proposal0,
8896        expiry_height,
8897    );
8898    assert_matches!(&create_proposed_result, Ok(_));
8899    let pczt_created = create_proposed_result.unwrap();
8900    let pczt_branch_id =
8901        consensus::BranchId::try_from(*pczt_created.global().consensus_branch_id())
8902            .expect("the PCZT carries a valid consensus branch ID");
8903
8904    // Signability invariant: the test account's derivation is known, so every
8905    // shielded spend must be signable by SOME party: already signed
8906    // (IO-finalized protocol dummies), carrying the dummy key that lets the IO
8907    // Finalizer sign it, or exposing the ZIP 32 derivation metadata by which
8908    // an external Signer identifies the spend as its own. A spend meeting none
8909    // of these is unsignable and dooms transaction extraction.
8910    fn assert_signable_orchard_bundle(bundle: &orchard::pczt::Bundle) {
8911        for action in bundle.actions() {
8912            assert!(
8913                action.spend().spend_auth_sig().is_some()
8914                    || action.spend().dummy_sk().is_some()
8915                    || action.spend().zip32_derivation().is_some(),
8916                "unsignable Orchard-protocol spend: no signature, dummy key, or derivation",
8917            );
8918        }
8919    }
8920    pczt::roles::verifier::Verifier::new(pczt_created.clone())
8921        .with_orchard::<Infallible, _>(|bundle| {
8922            assert_signable_orchard_bundle(bundle);
8923            Ok(())
8924        })
8925        .unwrap()
8926        .with_ironwood::<Infallible, _>(|bundle| {
8927            assert_signable_orchard_bundle(bundle);
8928            Ok(())
8929        })
8930        .unwrap()
8931        .with_sapling::<Infallible, _>(|bundle| {
8932            for spend in bundle.spends() {
8933                assert!(
8934                    spend.spend_auth_sig().is_some()
8935                        || spend.proof_generation_key().is_some()
8936                        || spend.zip32_derivation().is_some(),
8937                    "unsignable Sapling spend: no signature, dummy proving material, or derivation",
8938                );
8939            }
8940            Ok(())
8941        })
8942        .unwrap();
8943
8944    // If we don't create proofs or signatures, we will fail to extract a transaction.
8945    assert_matches!(
8946        st.extract_and_store_transaction_from_pczt(pczt_created.clone()),
8947        Err(Error::Pczt(data_api::error::PcztError::Extraction(_)))
8948    );
8949
8950    // Add proof generation keys to Sapling spends.
8951    let pczt_updated = P0::add_proof_generation_keys(pczt_created, account.usk()).unwrap();
8952
8953    // Create proofs, using the circuit that governs the Orchard pool under the
8954    // consensus branch the PCZT was created for. (The test network's most recent
8955    // upgrade is NU5, so this is currently the historical pre-NU6.2 circuit;
8956    // modernizing the test network fixture is part of the broader Ironwood test
8957    // coverage work.)
8958    let sapling_prover = LocalTxProver::bundled();
8959    let orchard_pk = zcash_primitives::transaction::builder::cached_orchard_proving_key(
8960        zcash_primitives::transaction::components::orchard::bundle_version_for_branch(
8961            pczt_branch_id,
8962            ::orchard::ValuePool::Orchard,
8963        )
8964        .expect("the PCZT's consensus branch supports the Orchard pool")
8965        .circuit_version(),
8966    );
8967    let pczt_proven = Prover::new(pczt_updated)
8968        .create_orchard_proof(UnwrapErr(SysRng), orchard_pk)
8969        .unwrap()
8970        .create_sapling_proofs(UnwrapErr(SysRng), &sapling_prover, &sapling_prover)
8971        .unwrap()
8972        .finish();
8973
8974    // The signer view of a v5 PCZT commits to the same transaction effects. V5
8975    // anchors are retained, while Orchard effecting fields are compacted using
8976    // the v2 PCZT encoding. Passing the proof-bearing authoritative copy also
8977    // exercises redaction of data that the external Signer does not need.
8978    let original_sighash = Signer::new(pczt_proven.clone()).unwrap().shielded_sighash();
8979    let original_len = pczt_proven.clone().serialize().unwrap().len();
8980    let signer_view = redact_pczt_for_signer(&pczt_proven, SignerView::Compact);
8981    assert_eq!(
8982        *signer_view.global().tx_version(),
8983        zcash_protocol::constants::V5_TX_VERSION,
8984    );
8985    assert_eq!(
8986        signer_view.sapling().anchor(),
8987        pczt_proven.sapling().anchor()
8988    );
8989    assert_eq!(
8990        signer_view.orchard().anchor(),
8991        pczt_proven.orchard().anchor()
8992    );
8993    if !signer_view.orchard().actions().is_empty() {
8994        assert!(pczt::v1::Pczt::try_from(signer_view.clone()).is_err());
8995        assert!(
8996            signer_view
8997                .orchard()
8998                .actions()
8999                .iter()
9000                .all(|action| action.cv_net().is_none() && action.output().cmx().is_none())
9001        );
9002    }
9003
9004    let signer_view_bytes = signer_view.serialize().unwrap();
9005    assert!(signer_view_bytes.len() < original_len);
9006    let signer_view = pczt::Pczt::parse(&signer_view_bytes).unwrap();
9007    assert_eq!(
9008        Signer::new(signer_view.clone()).unwrap().shielded_sighash(),
9009        original_sighash,
9010    );
9011
9012    // The full signer view is for receivers that predate the compact view:
9013    // it commits to the same transaction effects, retains proofs and anchors,
9014    // clears witnesses and dummy signing keys, and (for v5 transactions)
9015    // remains representable in the v1 PCZT encoding.
9016    let full_view = redact_pczt_for_signer(&pczt_proven, SignerView::Full);
9017    assert_eq!(
9018        Signer::new(full_view.clone()).unwrap().shielded_sighash(),
9019        original_sighash,
9020    );
9021    assert_eq!(full_view.orchard().anchor(), pczt_proven.orchard().anchor());
9022    assert_eq!(full_view.sapling().anchor(), pczt_proven.sapling().anchor());
9023    assert_eq!(
9024        full_view.orchard().zkproof().is_some(),
9025        pczt_proven.orchard().zkproof().is_some(),
9026    );
9027    assert!(full_view.orchard().actions().iter().all(|action| {
9028        action.spend().witness().is_none() && action.spend().dummy_sk().is_none()
9029    }));
9030    assert!(
9031        full_view
9032            .sapling()
9033            .spends()
9034            .iter()
9035            .all(|spend| spend.witness().is_none())
9036    );
9037    // Redaction's primary purpose is removing the wallet's proprietary metadata,
9038    // which the Signer has no use for and should never see.
9039    assert!(
9040        !full_view
9041            .global()
9042            .proprietary()
9043            .contains_key("zcash_client_backend:proposal_info")
9044    );
9045    for bundle in [full_view.orchard(), full_view.ironwood()] {
9046        assert!(bundle.actions().iter().all(|action| {
9047            !action
9048                .output()
9049                .proprietary()
9050                .contains_key("zcash_client_backend:output_info")
9051        }));
9052    }
9053    assert!(full_view.sapling().outputs().iter().all(|output| {
9054        !output
9055            .proprietary()
9056            .contains_key("zcash_client_backend:output_info")
9057    }));
9058    assert!(full_view.transparent().outputs().iter().all(|output| {
9059        !output
9060            .proprietary()
9061            .contains_key("zcash_client_backend:output_info")
9062    }));
9063    if *full_view.global().tx_version() == zcash_protocol::constants::V5_TX_VERSION {
9064        let full_view_bytes = full_view.clone().serialize().unwrap();
9065        assert!(pczt::v1::Pczt::try_from(full_view).is_ok());
9066        assert_eq!(
9067            u32::from_le_bytes(full_view_bytes[4..8].try_into().unwrap()),
9068            1,
9069            "the full signer view of a v5 PCZT serializes in the v1 encoding",
9070        );
9071    }
9072
9073    // Apply signatures to the transported signer view, then combine the
9074    // contribution with the proof-bearing authoritative copy.
9075    let mut signer = Signer::new(signer_view).unwrap();
9076    P0::apply_signatures_to_pczt(&mut signer, account.usk()).unwrap();
9077    let pczt_authorized = Combiner::new(vec![pczt_proven, signer.finish()])
9078        .combine()
9079        .unwrap();
9080
9081    // Now we can extract the transaction.
9082    let extract_and_store_result = st.extract_and_store_transaction_from_pczt(pczt_authorized);
9083    assert_matches!(&extract_and_store_result, Ok(_));
9084    let txid = extract_and_store_result.unwrap();
9085
9086    if let Some(expiry_height) = expiry_height {
9087        let tx = st.wallet().get_transaction(txid).unwrap().unwrap();
9088        assert_eq!(tx.expiry_height(), expiry_height);
9089    }
9090
9091    let (h, _) = st.generate_next_block_including(txid);
9092    st.scan_cached_blocks(h, 1);
9093}
9094
9095/// Ensure that wallet recovery recomputes fees.
9096///
9097/// Callers must provide an `intervene` function that deletes fee information for the specified
9098/// txid from the database. This deletion is checked and the test will fail if fee information is
9099/// not deleted.
9100#[cfg(feature = "transparent-inputs")]
9101pub fn wallet_recovery_computes_fees<T: ShieldedPoolTester, DsF: DataStoreFactory>(
9102    ds_factory: DsF,
9103    cache: impl TestCache,
9104    mut intervene: impl FnMut(&mut DsF::DataStore, TxId) -> Result<(), DsF::DsError>,
9105) {
9106    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
9107
9108    let seed = Secret::new(st.test_seed().unwrap().expose_secret().clone());
9109    let source_account = st.test_account().cloned().unwrap();
9110    let (dest_account_id, dest_usk) = st
9111        .wallet_mut()
9112        .create_account("dest", &seed, source_account.birthday(), None)
9113        .unwrap();
9114
9115    let (to, _) = dest_usk.default_transparent_address();
9116
9117    // Get some funds in the source account
9118    let note_value = Zatoshis::const_from_u64(350000);
9119    let _summary = st.add_notes_checking_balance([Some(note_value), Some(note_value)]);
9120
9121    // Create two transactions sending from the source account to a transparent address in the
9122    // destination account.
9123    let input_selector = GreedyInputSelector::new();
9124    let change_strategy =
9125        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
9126    let transfer_amount = Zatoshis::const_from_u64(200000);
9127    let request = TransactionRequest::new(vec![Payment::without_memo(
9128        Address::from(to).to_zcash_address(st.network()),
9129        transfer_amount,
9130    )])
9131    .unwrap();
9132
9133    let mut send_transparent = || {
9134        let p0 = st
9135            .propose_transfer(
9136                source_account.id(),
9137                &input_selector,
9138                &change_strategy,
9139                request.clone(),
9140                ConfirmationsPolicy::MIN,
9141            )
9142            .unwrap();
9143        let result0 = st
9144            .create_proposed_transactions::<Infallible, _, Infallible, _>(
9145                source_account.usk(),
9146                OvkPolicy::Sender,
9147                &p0,
9148            )
9149            .unwrap();
9150        assert_eq!(result0.len(), 1);
9151        let txid = result0[0];
9152        let (h, _) = st.generate_next_block_including(txid);
9153        st.scan_cached_blocks(h, 1);
9154
9155        // Make the destination account aware of the received UTXOs
9156        let tx = st.wallet().get_transaction(txid).unwrap().unwrap();
9157        let t_bundle = tx.transparent_bundle().unwrap();
9158        assert_eq!(t_bundle.vout.len(), 1);
9159
9160        let outpoint = OutPoint::new(*txid.as_ref(), 0);
9161        let utxo = WalletTransparentOutput::from_parts(
9162            outpoint,
9163            t_bundle.vout[0].clone(),
9164            Some(h),
9165            Some(dest_account_id),
9166            Some(TransparentKeyScope::EXTERNAL),
9167            None,
9168        )
9169        .unwrap();
9170        st.wallet_mut()
9171            .put_received_transparent_utxo(&utxo)
9172            .unwrap();
9173
9174        (txid, h)
9175    };
9176
9177    send_transparent();
9178    let (input_tx_1_txid, input_tx_1_height) = send_transparent();
9179
9180    assert_eq!(
9181        st.get_total_balance(dest_account_id),
9182        (transfer_amount + transfer_amount).unwrap()
9183    );
9184
9185    // Shield the funds in the destination account
9186    let p1 = st
9187        .propose_shielding(
9188            &input_selector,
9189            &change_strategy,
9190            Zatoshis::const_from_u64(10000),
9191            &[to],
9192            dest_account_id,
9193            ConfirmationsPolicy::MIN,
9194            CoinbaseFilter::AllTransparentOutputs,
9195        )
9196        .unwrap();
9197    let result1 = st
9198        .create_proposed_transactions::<Infallible, _, Infallible, _>(
9199            &dest_usk,
9200            OvkPolicy::Sender,
9201            &p1,
9202        )
9203        .unwrap();
9204    assert_eq!(result1.len(), 1);
9205    let txid = result1[0];
9206    let (h, _) = st.generate_next_block_including(txid);
9207    st.scan_cached_blocks(h, 1);
9208
9209    // Since our wallet constructed the transaction, we have the fee information;
9210    // we will need to wipe it out via a backend-level intervention in order to simulate
9211    // what happens in recovery.
9212    let shielding_tx = st.get_tx_from_history(txid).unwrap().unwrap();
9213    assert_matches!(shielding_tx.fee_paid, Some(_));
9214    let created_fee = shielding_tx.fee_paid.unwrap();
9215
9216    intervene(st.wallet_mut(), txid).unwrap();
9217
9218    // Verify that the intervention removed the fee information for the transaction.
9219    let shielding_tx = st.get_tx_from_history(txid).unwrap().unwrap();
9220    assert_matches!(shielding_tx.fee_paid, None);
9221
9222    // Run `decrypt_and_store_transaction; this should restore the fee, since the wallet has all of
9223    // the necessary input and output data.
9224    let tx = st.wallet().get_transaction(txid).unwrap().unwrap();
9225    let network = *st.network();
9226    decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, Some(h)).unwrap();
9227
9228    // Verify that the fee information has been restored.
9229    let shielding_tx = st.get_tx_from_history(txid).unwrap().unwrap();
9230    assert_eq!(shielding_tx.fee_paid, Some(created_fee));
9231
9232    // Wipe the fee information again; calling `decrypt_and_store_transaction` with the *input* tx
9233    // should also cause the fees to be restored.
9234    intervene(st.wallet_mut(), txid).unwrap();
9235
9236    let shielding_tx = st.get_tx_from_history(txid).unwrap().unwrap();
9237    assert_matches!(shielding_tx.fee_paid, None);
9238
9239    // Run `decrypt_and_store_transaction with one of the inputs; this should also restore the fee,
9240    // since the wallet has all of the necessary input and output data.
9241    let tx = st
9242        .wallet()
9243        .get_transaction(input_tx_1_txid)
9244        .unwrap()
9245        .unwrap();
9246    let network = *st.network();
9247    decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, Some(input_tx_1_height)).unwrap();
9248
9249    // Verify that the fee information has been restored.
9250    let shielding_tx = st.get_tx_from_history(txid).unwrap().unwrap();
9251    assert_eq!(shielding_tx.fee_paid, Some(created_fee));
9252}
9253
9254/// Tests that the wallet correctly reports balance with two notes that are identical
9255/// other than their note randomness.
9256pub fn receive_two_notes_with_same_value<T: ShieldedPoolTester>(
9257    dsf: impl DataStoreFactory,
9258    cache: impl TestCache,
9259) {
9260    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
9261
9262    // Add funds to the wallet in two identical notes
9263    let value = Zatoshis::const_from_u64(60000);
9264    let h = st
9265        .add_notes_checking_balance([[value, value]])
9266        .block_height()
9267        .unwrap();
9268
9269    // Spendable balance matches total balance.
9270    let account = st.test_account().cloned().unwrap();
9271    let total_value = (value + value).unwrap();
9272    assert_eq!(
9273        st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
9274        total_value
9275    );
9276
9277    let target_height = (h + 1).into();
9278
9279    // Both notes are unspent.
9280    let unspent_notes = T::select_unspent_notes(&st, account.id(), target_height, &[]).unwrap();
9281    assert_eq!(unspent_notes.len(), 2);
9282    for note in unspent_notes {
9283        assert_eq!(T::note_value(note.note()), value);
9284    }
9285
9286    // Both notes are spendable with 1 confirmation.
9287    let spendable_notes = T::select_spendable_notes(
9288        &st,
9289        account.id(),
9290        TargetValue::AllFunds(MaxSpendMode::MaxSpendable),
9291        target_height,
9292        ConfirmationsPolicy::MIN,
9293        &[],
9294    )
9295    .unwrap();
9296    assert_eq!(spendable_notes.len(), 2);
9297    for note in spendable_notes {
9298        assert_eq!(T::note_value(note.note()), value);
9299    }
9300}
9301
9302#[cfg(feature = "pczt")]
9303fn build_transparent_coinbase_tx(
9304    network: &LocalNetwork,
9305    target_height: TargetHeight,
9306    value: Zatoshis,
9307    recipient: TransparentAddress,
9308    miner_data: Option<PushValue>,
9309) -> zcash_primitives::transaction::builder::BuildResult {
9310    let build_config = BuildConfig::Coinbase { miner_data };
9311    let mut builder = Builder::new(*network, BlockHeight::from(target_height), build_config);
9312
9313    // Add transparent output to recipient
9314    builder.add_transparent_output(&recipient, value).unwrap();
9315
9316    // Build the transaction (coinbase transactions don't need provers)
9317    builder
9318        .build(
9319            // unused internally
9320            &TransparentSigningSet::new(),
9321            // unused internally
9322            &[],
9323            // unused internally
9324            &[],
9325            UnwrapErr(SysRng),
9326            &LocalTxProver::bundled(),
9327            &LocalTxProver::bundled(),
9328            // unused internally
9329            &StandardFeeRule::Zip317,
9330        )
9331        .unwrap()
9332}
9333
9334#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
9335/// Tests that immature coinbase outputs are excluded from note selection.
9336pub fn immature_coinbase_outputs_are_excluded_from_note_selection<T: ShieldedPoolTester>(
9337    dsf: impl DataStoreFactory,
9338    cache: impl TestCache,
9339) {
9340    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
9341
9342    // Get the default transparent address
9343    let (t_addr, _) = st.get_account().usk().default_transparent_address();
9344
9345    let coinbase_value = Zatoshis::const_from_u64(50000);
9346
9347    // Get the height where the coinbase tx will be mined
9348    let coinbase_height = st.sapling_activation_height();
9349
9350    // Construct the coinbase transaction and mine the block
9351    let coinbase_build_result = build_transparent_coinbase_tx(
9352        st.network(),
9353        TargetHeight::from(coinbase_height),
9354        coinbase_value,
9355        t_addr,
9356        None,
9357    );
9358    let coinbase_tx = coinbase_build_result.transaction();
9359    let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
9360    st.scan_cached_blocks(h, 1);
9361
9362    let params = *st.network();
9363    decrypt_and_store_transaction(&params, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
9364
9365    for i in 1..=99 {
9366        let latest_block_height = st.add_empty_blocks(1);
9367
9368        // Verify the coinbase UTXO is **not** spendable
9369        let spendable_utxos = st
9370            .wallet()
9371            .get_spendable_transparent_outputs(
9372                &t_addr,
9373                TargetHeight::from(h + i),
9374                ConfirmationsPolicy::default(),
9375                CoinbaseFilter::AllTransparentOutputs,
9376                LockFilter::Policy(&LockedInputPolicy::Exclude),
9377            )
9378            .unwrap();
9379        let confirmations = latest_block_height - h;
9380        assert!(
9381            spendable_utxos.is_empty(),
9382            "{i}: Immature coinbase output is spendable at blockheight {latest_block_height} \
9383            with {confirmations} confirmations \
9384            (should only be spendable at 100):\n \
9385            {spendable_utxos:#?}"
9386        );
9387    }
9388
9389    // Add the last block and ensure that the coinbase transaction is spendable
9390    let latest_height = st.add_empty_blocks(1);
9391    let confirmations = latest_height - h;
9392    let target_height = TargetHeight::from(latest_height + 1);
9393    let spendable_utxos = st
9394        .wallet()
9395        .get_spendable_transparent_outputs(
9396            &t_addr,
9397            target_height,
9398            ConfirmationsPolicy::default(),
9399            CoinbaseFilter::AllTransparentOutputs,
9400            LockFilter::Policy(&LockedInputPolicy::Exclude),
9401        )
9402        .unwrap();
9403    assert!(
9404        !spendable_utxos.is_empty(),
9405        "Coinbase output should be spendable at blockheight {latest_height} \
9406        with {confirmations} confirmations since the coinbase tx was mined (at {h})\n \
9407        target_height {target_height:?} - coinbase_tx.mined_height {h} = {}",
9408        u32::from(target_height) - u32::from(h)
9409    );
9410
9411    // Verify we can propose shielding the coinbase utxo
9412    let account = st.get_account().id();
9413    let _proposal = st
9414        .propose_shielding(
9415            &GreedyInputSelector::new(),
9416            &single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL),
9417            Zatoshis::from_u64(10000).unwrap(),
9418            &[t_addr],
9419            account,
9420            ConfirmationsPolicy::default(),
9421            CoinbaseFilter::AllTransparentOutputs,
9422        )
9423        .unwrap();
9424}
9425
9426#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
9427/// Tests that `CoinbaseFilter::CoinbaseOnly` excludes non-coinbase outputs and
9428/// `CoinbaseFilter::NonCoinbaseOnly` excludes coinbase outputs from UTXO selection and
9429/// shielding proposals, and that `CoinbaseOnly` still allows proposing shielding when only
9430/// coinbase UTXOs are available.
9431pub fn coinbase_only_filtering<T: ShieldedPoolTester, Dsf>(ds_factory: Dsf, cache: impl TestCache)
9432where
9433    Dsf: DataStoreFactory,
9434    <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
9435{
9436    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
9437    let (t_addr, _) = st.get_account().usk().default_transparent_address();
9438    let account = st.get_account().id();
9439
9440    // 1. Create a coinbase UTXO (50,000 zats)
9441    let coinbase_value = Zatoshis::const_from_u64(50000);
9442    let coinbase_height = st.sapling_activation_height();
9443    let coinbase_build_result = build_transparent_coinbase_tx(
9444        st.network(),
9445        TargetHeight::from(coinbase_height),
9446        coinbase_value,
9447        t_addr,
9448        None,
9449    );
9450    let coinbase_tx = coinbase_build_result.transaction();
9451    // The coinbase transaction has a single transparent output at index 0.
9452    let coinbase_outpoint = OutPoint::new(coinbase_tx.txid().into(), 0);
9453    let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
9454    st.scan_cached_blocks(h, 1);
9455    let params = *st.network();
9456    decrypt_and_store_transaction(&params, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
9457
9458    // 2. Create a non-coinbase UTXO (60,000 zats)
9459    // Inserted via put_received_transparent_utxo, which sets tx_index = NULL.
9460    // NULL tx_index is treated as non-coinbase by the filter.
9461    let non_coinbase_value = Zatoshis::const_from_u64(60000);
9462    let non_coinbase_outpoint = OutPoint::fake();
9463    let utxo = WalletTransparentOutput::from_parts(
9464        non_coinbase_outpoint.clone(),
9465        TxOut::new(non_coinbase_value, t_addr.script().into()),
9466        Some(h),
9467        Some(account),
9468        Some(TransparentKeyScope::EXTERNAL),
9469        None,
9470    )
9471    .unwrap();
9472    st.wallet_mut()
9473        .put_received_transparent_utxo(&utxo)
9474        .unwrap();
9475
9476    // 3. Wait for coinbase maturity (100 confirmations)
9477    st.add_empty_blocks(100);
9478    let target_height = TargetHeight::from(h + 101);
9479
9480    // 4. CoinbaseFilter::All returns both UTXOs
9481    let all_utxos = st
9482        .wallet()
9483        .get_spendable_transparent_outputs(
9484            &t_addr,
9485            target_height,
9486            ConfirmationsPolicy::default(),
9487            CoinbaseFilter::AllTransparentOutputs,
9488            LockFilter::Policy(&LockedInputPolicy::Exclude),
9489        )
9490        .unwrap();
9491    assert_eq!(
9492        all_utxos.len(),
9493        2,
9494        "Expected both coinbase and non-coinbase UTXOs with CoinbaseFilter::AllTransparentOutputs"
9495    );
9496    let all_utxos_value = all_utxos
9497        .iter()
9498        .map(|utxo| utxo.value().into_u64())
9499        .sum::<u64>();
9500    assert_eq!(
9501        all_utxos_value,
9502        coinbase_value.into_u64() + non_coinbase_value.into_u64(),
9503        "Unexpected total UTXO value when querying for all transparent transactions"
9504    );
9505
9506    // 5. CoinbaseFilter::CoinbaseOnly returns only the coinbase UTXO
9507    let coinbase_utxos = st
9508        .wallet()
9509        .get_spendable_transparent_outputs(
9510            &t_addr,
9511            target_height,
9512            ConfirmationsPolicy::default(),
9513            CoinbaseFilter::CoinbaseOnly,
9514            LockFilter::Policy(&LockedInputPolicy::Exclude),
9515        )
9516        .unwrap();
9517    assert_eq!(
9518        coinbase_utxos.len(),
9519        1,
9520        "Expected only the coinbase UTXO with CoinbaseFilter::CoinbaseOnly"
9521    );
9522    assert_eq!(coinbase_utxos[0].value(), coinbase_value);
9523    assert_eq!(coinbase_utxos[0].outpoint(), &coinbase_outpoint);
9524
9525    // 5b. CoinbaseFilter::NonCoinbaseOnly returns only the non-coinbase UTXO.
9526    // The non-coinbase UTXO was inserted with tx_index = NULL, which the filter treats as
9527    // non-coinbase, so it must be included here.
9528    let non_coinbase_utxos = st
9529        .wallet()
9530        .get_spendable_transparent_outputs(
9531            &t_addr,
9532            target_height,
9533            ConfirmationsPolicy::default(),
9534            CoinbaseFilter::NonCoinbaseOnly,
9535            LockFilter::Policy(&LockedInputPolicy::Exclude),
9536        )
9537        .unwrap();
9538    assert_eq!(
9539        non_coinbase_utxos.len(),
9540        1,
9541        "Expected only the non-coinbase UTXO with CoinbaseFilter::NonCoinbaseOnly"
9542    );
9543    assert_eq!(non_coinbase_utxos[0].value(), non_coinbase_value);
9544    assert_eq!(non_coinbase_utxos[0].outpoint(), &non_coinbase_outpoint);
9545
9546    // 6. propose_shielding with CoinbaseOnly includes only the coinbase input
9547    let proposal = st
9548        .propose_shielding(
9549            &GreedyInputSelector::new(),
9550            &single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL),
9551            Zatoshis::from_u64(10000).unwrap(),
9552            &[t_addr],
9553            account,
9554            ConfirmationsPolicy::default(),
9555            CoinbaseFilter::CoinbaseOnly,
9556        )
9557        .unwrap();
9558    let coinbase_inputs = proposal.steps().first().transparent_inputs();
9559    assert_eq!(
9560        coinbase_inputs.len(),
9561        1,
9562        "CoinbaseOnly proposal should contain exactly one transparent input"
9563    );
9564    assert_eq!(coinbase_inputs[0].value(), coinbase_value);
9565    assert_eq!(coinbase_inputs[0].outpoint(), &coinbase_outpoint);
9566
9567    // 6b. propose_shielding with NonCoinbaseOnly includes only the non-coinbase input
9568    let proposal_non_coinbase = st
9569        .propose_shielding(
9570            &GreedyInputSelector::new(),
9571            &single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL),
9572            Zatoshis::from_u64(10000).unwrap(),
9573            &[t_addr],
9574            account,
9575            ConfirmationsPolicy::default(),
9576            CoinbaseFilter::NonCoinbaseOnly,
9577        )
9578        .unwrap();
9579    let non_coinbase_inputs = proposal_non_coinbase.steps().first().transparent_inputs();
9580    assert_eq!(
9581        non_coinbase_inputs.len(),
9582        1,
9583        "NonCoinbaseOnly proposal should contain exactly one transparent input"
9584    );
9585    assert_eq!(non_coinbase_inputs[0].value(), non_coinbase_value);
9586    assert_eq!(non_coinbase_inputs[0].outpoint(), &non_coinbase_outpoint);
9587
9588    // 7. propose_shielding with All includes both inputs
9589    let proposal_all = st
9590        .propose_shielding(
9591            &GreedyInputSelector::new(),
9592            &single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL),
9593            Zatoshis::from_u64(10000).unwrap(),
9594            &[t_addr],
9595            account,
9596            ConfirmationsPolicy::default(),
9597            CoinbaseFilter::AllTransparentOutputs,
9598        )
9599        .unwrap();
9600    let all_inputs = proposal_all.steps().first().transparent_inputs();
9601    assert_eq!(
9602        all_inputs.len(),
9603        2,
9604        "All proposal should contain both transparent inputs"
9605    );
9606    // Input ordering is not guaranteed, so compare the set of outpoints.
9607    let all_outpoints = all_inputs
9608        .iter()
9609        .map(|input| input.outpoint().clone())
9610        .collect::<BTreeSet<_>>();
9611    assert_eq!(
9612        all_outpoints,
9613        BTreeSet::from([coinbase_outpoint, non_coinbase_outpoint]),
9614        "All proposal should contain both the coinbase and non-coinbase outpoints"
9615    );
9616}
9617
9618/// Verifies that `propose_shielding_coinbase` with a shielded destination produces
9619/// a proposal containing a single ZIP-321 payment to the supplied address for the
9620/// full available value (input total minus fee), with no change.
9621#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
9622pub fn propose_shielding_coinbase_succeeds<T: ShieldedPoolTester, Dsf>(
9623    ds_factory: Dsf,
9624    cache: impl TestCache,
9625) where
9626    Dsf: DataStoreFactory,
9627    <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
9628{
9629    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
9630    let (t_addr, _) = st.get_account().usk().default_transparent_address();
9631    let coinbase_value = Zatoshis::const_from_u64(50000);
9632    let coinbase_build_result = build_transparent_coinbase_tx(
9633        st.network(),
9634        TargetHeight::from(st.sapling_activation_height()),
9635        coinbase_value,
9636        t_addr,
9637        None,
9638    );
9639    let coinbase_tx = coinbase_build_result.transaction();
9640    let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
9641    st.scan_cached_blocks(h, 1);
9642    let params = *st.network();
9643    decrypt_and_store_transaction(&params, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
9644    // Coinbase outputs require 100 confirmations.
9645    st.add_empty_blocks(100);
9646
9647    // The destination is a shielded address controlled by a separate spending key
9648    // (i.e. potentially in a different wallet).
9649    let to_extsk = T::sk(&[0xab; 32]);
9650    let to_address = T::sk_default_address(&to_extsk).to_zcash_address(st.network());
9651
9652    let proposal = st
9653        .propose_shielding_coinbase(
9654            &GreedyInputSelector::new(),
9655            &StandardFeeRule::Zip317,
9656            Zatoshis::ZERO,
9657            &[t_addr],
9658            to_address.clone(),
9659            None,
9660            None,
9661        )
9662        .expect("propose_shielding_coinbase with a shielded destination should succeed");
9663
9664    let step = proposal.steps().first();
9665    assert_eq!(
9666        step.transparent_inputs().len(),
9667        1,
9668        "Expected exactly one coinbase transparent input"
9669    );
9670    let payments = step.transaction_request().payments();
9671    assert_eq!(
9672        payments.len(),
9673        1,
9674        "Expected exactly one payment in proposal"
9675    );
9676    let (idx, payment) = payments.iter().next().unwrap();
9677    assert_eq!(*idx, 0);
9678    assert_eq!(payment.recipient_address(), &to_address);
9679    assert_eq!(
9680        step.balance().proposed_change().len(),
9681        0,
9682        "Coinbase shielding must produce no change"
9683    );
9684
9685    let fee = step.balance().fee_required();
9686    let payment_amount = payment.amount().expect("payment must have an amount");
9687    assert_eq!(
9688        (payment_amount + fee).unwrap(),
9689        coinbase_value,
9690        "payment_amount + fee must equal coinbase input value"
9691    );
9692}
9693
9694/// A newly constructed shielding proposal preserves the checkpoint selected by the wallet, even
9695/// though it spends no shielded notes. A proposal serialized without the confirmations-policy
9696/// field (as an older library version would have produced) decodes using the default policy and,
9697/// because it still carries that real anchor, builds. Separately, a shielding step produces a
9698/// shielded bundle, so a proposal that encodes such a step with the zero anchor sentinel is
9699/// rejected at the parse boundary.
9700#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
9701pub fn proposal_without_confirmations_policy_builds<T: ShieldedPoolTester, Dsf>(
9702    ds_factory: Dsf,
9703    cache: impl TestCache,
9704) where
9705    Dsf: DataStoreFactory,
9706    <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
9707{
9708    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
9709    let (t_addr, _) = st.get_account().usk().default_transparent_address();
9710    let coinbase_value = Zatoshis::const_from_u64(50000);
9711    let coinbase_build_result = build_transparent_coinbase_tx(
9712        st.network(),
9713        TargetHeight::from(st.sapling_activation_height()),
9714        coinbase_value,
9715        t_addr,
9716        None,
9717    );
9718    let coinbase_tx = coinbase_build_result.transaction();
9719    let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
9720    st.scan_cached_blocks(h, 1);
9721    let params = *st.network();
9722    decrypt_and_store_transaction(&params, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
9723    // Coinbase outputs require 100 confirmations.
9724    st.add_empty_blocks(100);
9725
9726    let to_extsk = T::sk(&[0xab; 32]);
9727    let to_address = T::sk_default_address(&to_extsk).to_zcash_address(st.network());
9728
9729    let proposal = st
9730        .propose_shielding_coinbase(
9731            &GreedyInputSelector::new(),
9732            &StandardFeeRule::Zip317,
9733            Zatoshis::ZERO,
9734            &[t_addr],
9735            to_address,
9736            None,
9737            None,
9738        )
9739        .expect("coinbase shielding proposal should succeed");
9740
9741    // The shielding step keeps the checkpoint selected by input selection.
9742    let selected_anchor = proposal
9743        .steps()
9744        .first()
9745        .anchor_height()
9746        .expect("a shielding step must preserve its selected checkpoint");
9747
9748    let proto = crate::proto::proposal::Proposal::from_standard_proposal(&proposal);
9749    assert_eq!(
9750        proto.steps[0].anchor_height,
9751        u32::from(selected_anchor),
9752        "a shielding step must serialize its selected checkpoint",
9753    );
9754
9755    // The zero anchor is the wire sentinel for "no anchor". A shielding step produces a shielded
9756    // bundle, so decoding must reject a zero anchor at the parse boundary rather than accepting a
9757    // step whose dummy spends would commit to no real anchor. (Checked before building below, which
9758    // spends the input the proposal decodes against.)
9759    let mut zero_anchor = proto.clone();
9760    zero_anchor.steps[0].anchor_height = 0;
9761    assert_matches!(
9762        zero_anchor.try_into_standard_proposal(&params, st.wallet()),
9763        Err(crate::proto::ProposalDecodingError::MissingShieldedAnchor)
9764    );
9765
9766    // A proposal serialized before the confirmations-policy field existed omits it, so decoding
9767    // must fall back to the default policy. The real anchor is preserved, so the step still builds.
9768    let mut without_policy = proto;
9769    without_policy.confirmations_policy = None;
9770    let decoded = without_policy
9771        .try_into_standard_proposal(&params, st.wallet())
9772        .expect("a proposal without a confirmations policy must decode");
9773    assert_eq!(
9774        decoded.confirmations_policy(),
9775        ConfirmationsPolicy::default(),
9776        "a missing confirmations policy must decode as the default",
9777    );
9778    assert_eq!(
9779        decoded.steps().first().anchor_height(),
9780        Some(selected_anchor),
9781        "decoding must preserve the serialized anchor",
9782    );
9783    assert_eq!(
9784        decoded.min_target_height(),
9785        proposal.min_target_height(),
9786        "decoding must preserve the target height the proposal's fee was computed at",
9787    );
9788
9789    let usk = st.get_account().usk().clone();
9790    st.create_proposed_transactions::<Infallible, _, Infallible, _>(
9791        &usk,
9792        OvkPolicy::Sender,
9793        &decoded,
9794    )
9795    .expect("a proposal that carries its selected anchor must build");
9796}
9797
9798/// Verifies that `propose_shielding_coinbase` rejects a transparent destination
9799/// with [`ProposalError::ShieldingRequiresShieldedRecipient`].
9800#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
9801pub fn propose_shielding_coinbase_transparent_recipient_rejected<T: ShieldedPoolTester, Dsf>(
9802    ds_factory: Dsf,
9803    cache: impl TestCache,
9804) where
9805    Dsf: DataStoreFactory,
9806    <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
9807{
9808    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
9809    let (t_addr, _) = st.get_account().usk().default_transparent_address();
9810    let coinbase_value = Zatoshis::const_from_u64(50000);
9811    let coinbase_build_result = build_transparent_coinbase_tx(
9812        st.network(),
9813        TargetHeight::from(st.sapling_activation_height()),
9814        coinbase_value,
9815        t_addr,
9816        None,
9817    );
9818    let coinbase_tx = coinbase_build_result.transaction();
9819    let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
9820    st.scan_cached_blocks(h, 1);
9821    let params = *st.network();
9822    decrypt_and_store_transaction(&params, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
9823    st.add_empty_blocks(100);
9824
9825    let bad_to_address = Address::Transparent(TransparentAddress::PublicKeyHash([7; 20]))
9826        .to_zcash_address(st.network());
9827
9828    let result = st.propose_shielding_coinbase(
9829        &GreedyInputSelector::new(),
9830        &StandardFeeRule::Zip317,
9831        Zatoshis::ZERO,
9832        &[t_addr],
9833        bad_to_address,
9834        None,
9835        None,
9836    );
9837
9838    assert_matches!(
9839        result,
9840        Err(Error::Proposal(
9841            ProposalError::ShieldingRequiresShieldedRecipient
9842        ))
9843    );
9844}
9845
9846/// Verifies that `propose_shielding_coinbase` propagates the supplied `memo`
9847/// into the resulting payment's memo field.
9848#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
9849pub fn propose_shielding_coinbase_with_memo_succeeds<T: ShieldedPoolTester, Dsf>(
9850    ds_factory: Dsf,
9851    cache: impl TestCache,
9852) where
9853    Dsf: DataStoreFactory,
9854    <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
9855{
9856    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
9857    let (t_addr, _) = st.get_account().usk().default_transparent_address();
9858    let coinbase_value = Zatoshis::const_from_u64(50000);
9859    let coinbase_build_result = build_transparent_coinbase_tx(
9860        st.network(),
9861        TargetHeight::from(st.sapling_activation_height()),
9862        coinbase_value,
9863        t_addr,
9864        None,
9865    );
9866    let coinbase_tx = coinbase_build_result.transaction();
9867    let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
9868    st.scan_cached_blocks(h, 1);
9869    let params = *st.network();
9870    decrypt_and_store_transaction(&params, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
9871    st.add_empty_blocks(100);
9872
9873    let to_extsk = T::sk(&[0xcd; 32]);
9874    let to_address = T::sk_default_address(&to_extsk).to_zcash_address(st.network());
9875
9876    let memo_text = "shielding to external wallet";
9877    let memo_bytes = MemoBytes::from(memo_text.parse::<Memo>().unwrap());
9878
9879    let proposal = st
9880        .propose_shielding_coinbase(
9881            &GreedyInputSelector::new(),
9882            &StandardFeeRule::Zip317,
9883            Zatoshis::ZERO,
9884            &[t_addr],
9885            to_address,
9886            Some(memo_bytes.clone()),
9887            None,
9888        )
9889        .expect("propose_shielding_coinbase with memo should succeed");
9890
9891    let payments = proposal.steps().first().transaction_request().payments();
9892    let (_, payment) = payments.iter().next().unwrap();
9893    assert_eq!(payment.memo(), Some(&memo_bytes));
9894}
9895
9896/// Verifies that `propose_shielding_coinbase` with `limit = Some(n)` selects at
9897/// most `n` UTXOs, preferring the highest-value coinbase outputs.
9898#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
9899pub fn propose_shielding_coinbase_with_limit_truncates_inputs<T: ShieldedPoolTester, Dsf>(
9900    ds_factory: Dsf,
9901    cache: impl TestCache,
9902) where
9903    Dsf: DataStoreFactory,
9904    <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
9905{
9906    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
9907    let (t_addr, _) = st.get_account().usk().default_transparent_address();
9908
9909    // Mine three coinbase transactions to the same recipient at successive heights,
9910    // with distinct values so we can verify the highest-value-first selection.
9911    let values = [
9912        Zatoshis::const_from_u64(30000),
9913        Zatoshis::const_from_u64(70000),
9914        Zatoshis::const_from_u64(50000),
9915    ];
9916    let mut first_h = None;
9917    for v in values {
9918        let coinbase_height = if let Some(h) = first_h {
9919            h + values.len() as u32 // arbitrary; only first_h matters for maturity
9920        } else {
9921            st.sapling_activation_height()
9922        };
9923        let build = build_transparent_coinbase_tx(
9924            st.network(),
9925            TargetHeight::from(coinbase_height),
9926            v,
9927            t_addr,
9928            None,
9929        );
9930        let tx = build.transaction();
9931        let (h, _) = st.generate_next_block_from_tx(0, tx);
9932        st.scan_cached_blocks(h, 1);
9933        let params = *st.network();
9934        decrypt_and_store_transaction(&params, st.wallet_mut(), tx, Some(h)).unwrap();
9935        if first_h.is_none() {
9936            first_h = Some(h);
9937        }
9938    }
9939    // Mature all three.
9940    st.add_empty_blocks(100);
9941
9942    let to_extsk = T::sk(&[0x55; 32]);
9943    let to_address = T::sk_default_address(&to_extsk).to_zcash_address(st.network());
9944
9945    let proposal = st
9946        .propose_shielding_coinbase(
9947            &GreedyInputSelector::new(),
9948            &StandardFeeRule::Zip317,
9949            Zatoshis::ZERO,
9950            &[t_addr],
9951            to_address,
9952            None,
9953            Some(2),
9954        )
9955        .expect("propose_shielding_coinbase with limit=Some(2) should succeed");
9956
9957    let inputs = proposal.steps().first().transparent_inputs();
9958    assert_eq!(
9959        inputs.len(),
9960        2,
9961        "limit=Some(2) should select exactly 2 inputs"
9962    );
9963
9964    // The two highest-value coinbase UTXOs are 70000 and 50000.
9965    let mut selected_values: Vec<u64> = inputs.iter().map(|i| i.value().into_u64()).collect();
9966    selected_values.sort_unstable_by(|a, b| b.cmp(a));
9967    assert_eq!(selected_values, vec![70000, 50000]);
9968}
9969
9970/// Verifies that `propose_shielding_coinbase` with `limit = Some(0)` selects no
9971/// inputs, returning [`InputSelectorError::InsufficientFunds`].
9972///
9973/// [`InputSelectorError::InsufficientFunds`]: crate::data_api::wallet::input_selection::InputSelectorError::InsufficientFunds
9974#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
9975pub fn propose_shielding_coinbase_with_zero_limit_insufficient_funds<T: ShieldedPoolTester, Dsf>(
9976    ds_factory: Dsf,
9977    cache: impl TestCache,
9978) where
9979    Dsf: DataStoreFactory,
9980    <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
9981{
9982    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
9983    let (t_addr, _) = st.get_account().usk().default_transparent_address();
9984    let coinbase_value = Zatoshis::const_from_u64(50000);
9985    let coinbase_build_result = build_transparent_coinbase_tx(
9986        st.network(),
9987        TargetHeight::from(st.sapling_activation_height()),
9988        coinbase_value,
9989        t_addr,
9990        None,
9991    );
9992    let coinbase_tx = coinbase_build_result.transaction();
9993    let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
9994    st.scan_cached_blocks(h, 1);
9995    let params = *st.network();
9996    decrypt_and_store_transaction(&params, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
9997    st.add_empty_blocks(100);
9998
9999    let to_extsk = T::sk(&[0x66; 32]);
10000    let to_address = T::sk_default_address(&to_extsk).to_zcash_address(st.network());
10001
10002    let shielding_threshold = Zatoshis::const_from_u64(10000);
10003    let result = st.propose_shielding_coinbase(
10004        &GreedyInputSelector::new(),
10005        &StandardFeeRule::Zip317,
10006        shielding_threshold,
10007        &[t_addr],
10008        to_address,
10009        None,
10010        Some(0),
10011    );
10012
10013    // With no inputs selected, `payment_amount = input_total - fee` underflows
10014    // (input_total = 0, fee > 0), producing `Error::InsufficientFunds` with
10015    // `available: 0, required: fee`.
10016    assert_matches!(result, Err(Error::InsufficientFunds { .. }));
10017}
10018
10019/// Regression test for the propose-fee/build-fee mismatch fixed in #2376.
10020///
10021/// Both `sapling::builder::BundleType::DEFAULT` and
10022/// `orchard::builder::BundleType::DEFAULT` pad up to a minimum of 2
10023/// outputs/actions (`MIN_SHIELDED_OUTPUTS` / `MIN_ACTIONS`). Before the fix,
10024/// `propose_shielding_coinbase` hardcoded `(1, 0)` / `(0, 1)` when asking the
10025/// fee rule what fee to charge, so the proposal underestimated the fee by
10026/// exactly one ZIP-317 marginal unit (5000 zat). The proposal succeeded, but
10027/// `create_proposed_transactions` then failed at build time with
10028/// `Insufficient funds for transaction construction; need an additional ZatBalance(5000) zatoshis`.
10029///
10030/// This test verifies the propose-and-build round trip succeeds for both
10031/// Sapling and Orchard destinations (parameterized by `T`).
10032#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
10033pub fn propose_and_build_shielding_coinbase_succeeds<T: ShieldedPoolTester, Dsf>(
10034    ds_factory: Dsf,
10035    cache: impl TestCache,
10036) where
10037    Dsf: DataStoreFactory,
10038    <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
10039{
10040    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
10041    let account = st.get_account();
10042    let (t_addr, _) = account.usk().default_transparent_address();
10043    let coinbase_value = Zatoshis::const_from_u64(50000);
10044    let coinbase_build_result = build_transparent_coinbase_tx(
10045        st.network(),
10046        TargetHeight::from(st.sapling_activation_height()),
10047        coinbase_value,
10048        t_addr,
10049        None,
10050    );
10051    let coinbase_tx = coinbase_build_result.transaction();
10052    let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
10053    st.scan_cached_blocks(h, 1);
10054    let params = *st.network();
10055    decrypt_and_store_transaction(&params, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
10056    // Coinbase outputs require 100 confirmations.
10057    st.add_empty_blocks(COINBASE_MATURITY_BLOCKS as usize);
10058
10059    // The destination is a shielded address controlled by a separate spending key.
10060    let to_extsk = T::sk(&[0xcd; 32]);
10061    let to_address = T::sk_default_address(&to_extsk).to_zcash_address(st.network());
10062
10063    let proposal = st
10064        .propose_shielding_coinbase(
10065            &GreedyInputSelector::new(),
10066            &StandardFeeRule::Zip317,
10067            Zatoshis::ZERO,
10068            &[t_addr],
10069            to_address,
10070            None,
10071            None,
10072        )
10073        .expect("propose_shielding_coinbase should succeed");
10074
10075    // Prior to #2376 this would fail at build time with `Insufficient funds for transaction
10076    // construction; need an additional ZatBalance(5000) zatoshis` because the proposal-stage fee
10077    // was computed assuming N output/action slots but the builder materializes N+1 (after `MIN_*`
10078    // padding).
10079    let build_result = st.create_proposed_transactions::<Infallible, _, Infallible, _>(
10080        account.usk(),
10081        OvkPolicy::Sender,
10082        &proposal,
10083    );
10084    assert_matches!(
10085        &build_result,
10086        Ok(txids) if txids.len() == 1,
10087        "create_proposed_transactions must succeed for proposal {:?}",
10088        proposal,
10089    );
10090}
10091
10092/// Verifies that once Ironwood is active, `propose_shielding_coinbase` resolves a destination
10093/// with an Orchard receiver to the Ironwood pool — the payment is delivered to the Orchard
10094/// receiver via the Ironwood bundle — and that the proposed transaction builds.
10095#[cfg(all(feature = "orchard", feature = "pczt", feature = "transparent-inputs"))]
10096pub fn shielding_coinbase_to_orchard_receiver_delivers_via_ironwood<Dsf>(
10097    ds_factory: Dsf,
10098    cache: impl TestCache,
10099) where
10100    Dsf: DataStoreFactory,
10101    <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
10102{
10103    // A network on which Ironwood (NU6.3) is active from the Sapling activation height.
10104    let ironwood_active_network = {
10105        let activation = BlockHeight::from_u32(100_000);
10106        LocalNetwork {
10107            nu6: Some(activation),
10108            nu6_1: Some(activation),
10109            nu6_2: Some(activation),
10110            nu6_3: Some(activation),
10111            ..TestBuilder::<(), ()>::DEFAULT_NETWORK
10112        }
10113    };
10114
10115    let mut st = TestDsl::from(
10116        TestBuilder::new()
10117            .with_network(ironwood_active_network)
10118            .with_data_store_factory(ds_factory)
10119            .with_block_cache(cache)
10120            .with_account_from_sapling_activation(BlockHash([0; 32])),
10121    )
10122    .build::<OrchardPoolTester>();
10123    let account = st.get_account();
10124    let (t_addr, _) = account.usk().default_transparent_address();
10125    let coinbase_value = Zatoshis::const_from_u64(100000);
10126    let coinbase_build_result = build_transparent_coinbase_tx(
10127        st.network(),
10128        TargetHeight::from(st.sapling_activation_height()),
10129        coinbase_value,
10130        t_addr,
10131        None,
10132    );
10133    let coinbase_tx = coinbase_build_result.transaction();
10134    let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
10135    st.scan_cached_blocks(h, 1);
10136    let params = *st.network();
10137    decrypt_and_store_transaction(&params, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
10138    // Coinbase outputs require 100 confirmations.
10139    st.add_empty_blocks(COINBASE_MATURITY_BLOCKS as usize);
10140
10141    // The destination has an Orchard receiver controlled by a separate spending key.
10142    let to_extsk = OrchardPoolTester::sk(&[0xcd; 32]);
10143    let to_address =
10144        OrchardPoolTester::sk_default_address(&to_extsk).to_zcash_address(st.network());
10145
10146    let proposal = st
10147        .propose_shielding_coinbase(
10148            &GreedyInputSelector::new(),
10149            &StandardFeeRule::Zip317,
10150            Zatoshis::ZERO,
10151            &[t_addr],
10152            to_address,
10153            None,
10154            None,
10155        )
10156        .expect("propose_shielding_coinbase to an Orchard receiver should succeed post-NU6.3");
10157
10158    // The Orchard-receiver payment is represented as an Ironwood-pool output, matching the
10159    // bundle the builder will deliver it through; an Orchard-pool payment would violate the
10160    // Orchard turnstile.
10161    assert_eq!(
10162        proposal.steps().head.payment_pools().get(&0),
10163        Some(&PoolType::IRONWOOD),
10164    );
10165
10166    let build_result = st.create_proposed_transactions::<Infallible, _, Infallible, _>(
10167        account.usk(),
10168        OvkPolicy::Sender,
10169        &proposal,
10170    );
10171    assert_matches!(
10172        &build_result,
10173        Ok(txids) if txids.len() == 1,
10174        "create_proposed_transactions must succeed for proposal {:?}",
10175        proposal,
10176    );
10177    let sent_txid = build_result.unwrap().head;
10178
10179    // This transaction has a shielded bundle, but it is not observable by this wallet through
10180    // compact-block scanning: it has only transparent wallet inputs, its shielded output belongs
10181    // to another wallet, and it has no change. The sender therefore requires a txid-based status
10182    // request to learn its outcome.
10183    assert!(
10184        st.wallet()
10185            .transaction_data_requests()
10186            .unwrap()
10187            .contains(&TransactionDataRequest::GetStatus(sent_txid))
10188    );
10189
10190    let (mined_height, _) = st.generate_next_block_including(sent_txid);
10191    st.scan_cached_blocks(mined_height, 1);
10192    assert_eq!(
10193        st.get_tx_from_history(sent_txid)
10194            .unwrap()
10195            .expect("sent transaction is in history")
10196            .mined_height(),
10197        None,
10198        "compact scanning cannot detect an external shielding transaction",
10199    );
10200
10201    st.wallet_mut()
10202        .set_transaction_status(sent_txid, TransactionStatus::Mined(mined_height))
10203        .unwrap();
10204    assert_eq!(
10205        st.get_tx_from_history(sent_txid)
10206            .unwrap()
10207            .expect("sent transaction is in history")
10208            .mined_height(),
10209        Some(mined_height),
10210    );
10211    assert!(
10212        !st.wallet()
10213            .transaction_data_requests()
10214            .unwrap()
10215            .contains(&TransactionDataRequest::GetStatus(sent_txid)),
10216        "status intent is dormant while the transaction is mined",
10217    );
10218
10219    st.truncate_to_height(mined_height - 1);
10220    assert_eq!(
10221        st.get_tx_from_history(sent_txid)
10222            .unwrap()
10223            .expect("sent transaction is retained across the rewind")
10224            .mined_height(),
10225        None,
10226    );
10227    assert!(
10228        st.wallet()
10229            .transaction_data_requests()
10230            .unwrap()
10231            .contains(&TransactionDataRequest::GetStatus(sent_txid)),
10232        "rewinding the mined block reactivates the durable status intent",
10233    );
10234}
10235
10236/// After NU6.3 activation, a payment to an Orchard receiver must be delivered through the
10237/// Ironwood pool, which requires a version 6 transaction. Explicitly requesting a version 5
10238/// transaction — which has no Ironwood bundle — for such a payment must be rejected at proposal
10239/// time with [`ProposalError::OrchardReceiverRequiresIronwood`], rather than producing a proposal
10240/// that could only fail later at build time.
10241#[cfg(feature = "orchard")]
10242pub fn propose_v5_payment_to_orchard_receiver_is_rejected<Dsf>(
10243    ds_factory: Dsf,
10244    cache: impl TestCache,
10245) where
10246    Dsf: DataStoreFactory,
10247{
10248    // A network on which Ironwood (NU6.3) is active from the Sapling activation height.
10249    let ironwood_active_network = {
10250        let activation = BlockHeight::from_u32(100_000);
10251        LocalNetwork {
10252            nu6: Some(activation),
10253            nu6_1: Some(activation),
10254            nu6_2: Some(activation),
10255            nu6_3: Some(activation),
10256            ..TestBuilder::<(), ()>::DEFAULT_NETWORK
10257        }
10258    };
10259
10260    let mut st = TestDsl::from(
10261        TestBuilder::new()
10262            .with_network(ironwood_active_network)
10263            .with_data_store_factory(ds_factory)
10264            .with_block_cache(cache)
10265            .with_account_from_sapling_activation(BlockHash([0; 32])),
10266    )
10267    .build::<OrchardPoolTester>();
10268
10269    // Fund the wallet with a single spendable Orchard note.
10270    st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60_000));
10271
10272    // The destination has an Orchard receiver controlled by a separate spending key.
10273    let to_extsk = OrchardPoolTester::sk(&[0xf5; 32]);
10274    let to = OrchardPoolTester::sk_default_address(&to_extsk);
10275    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
10276        to.to_zcash_address(st.network()),
10277        Zatoshis::const_from_u64(10_000),
10278    )])
10279    .unwrap();
10280
10281    let change_strategy =
10282        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
10283    let input_selector = GreedyInputSelector::new();
10284
10285    let account = st.get_account();
10286    let network = *st.network();
10287    let result = propose_transfer::<_, _, _, _, Infallible>(
10288        st.wallet_mut(),
10289        &network,
10290        account.id(),
10291        &input_selector,
10292        &change_strategy,
10293        request,
10294        ConfirmationsPolicy::MIN,
10295        &SpendPolicy::default(),
10296        None,
10297        Some(TxVersion::V5),
10298    );
10299
10300    assert_matches!(
10301        result,
10302        Err(Error::Proposal(
10303            ProposalError::OrchardReceiverRequiresIronwood(TxVersion::V5)
10304        ))
10305    );
10306}
10307
10308/// PCZT construction supports the version 6 transaction format, including its Ironwood bundle.
10309/// After NU6.3 a payment to an Orchard receiver is delivered through the Ironwood pool, so
10310/// `create_pczt_from_proposal` realizes such a proposal as a version 6 PCZT that carries a
10311/// populated Ironwood bundle.
10312#[cfg(all(feature = "orchard", feature = "pczt"))]
10313pub fn create_pczt_supports_ironwood_output<Dsf>(ds_factory: Dsf, cache: impl TestCache)
10314where
10315    Dsf: DataStoreFactory,
10316    <Dsf as DataStoreFactory>::AccountId: serde::Serialize + serde::de::DeserializeOwned,
10317{
10318    // A network on which NU6.3 — the version 6 transaction format — is active from height 100_000.
10319    let ironwood_active_network = {
10320        let activation = BlockHeight::from_u32(100_000);
10321        LocalNetwork {
10322            nu6: Some(activation),
10323            nu6_1: Some(activation),
10324            nu6_2: Some(activation),
10325            nu6_3: Some(activation),
10326            ..TestBuilder::<(), ()>::DEFAULT_NETWORK
10327        }
10328    };
10329
10330    let mut st = TestDsl::from(
10331        TestBuilder::new()
10332            .with_network(ironwood_active_network)
10333            .with_data_store_factory(ds_factory)
10334            .with_block_cache(cache)
10335            .with_account_from_sapling_activation(BlockHash([0; 32])),
10336    )
10337    .build::<OrchardPoolTester>();
10338
10339    // Fund the wallet with a single spendable Orchard note.
10340    st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60_000));
10341
10342    // The destination has an Orchard receiver controlled by a separate spending key; post-NU6.3 the
10343    // payment is routed through the Ironwood pool.
10344    let to_extsk = OrchardPoolTester::sk(&[0xf5; 32]);
10345    let to = OrchardPoolTester::sk_default_address(&to_extsk);
10346    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
10347        to.to_zcash_address(st.network()),
10348        Zatoshis::const_from_u64(10_000),
10349    )])
10350    .unwrap();
10351
10352    let change_strategy =
10353        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
10354    let input_selector = GreedyInputSelector::new();
10355
10356    let account_id = st.get_account().id();
10357    let proposal = st
10358        .propose_transfer(
10359            account_id,
10360            &input_selector,
10361            &change_strategy,
10362            request,
10363            ConfirmationsPolicy::MIN,
10364        )
10365        .expect("proposal construction succeeds; the Orchard-receiver payment routes to Ironwood");
10366
10367    // The payment routes to the Ironwood pool, so the resulting PCZT must carry an Ironwood bundle.
10368    assert_eq!(
10369        proposal.steps().head.payment_pools().get(&0),
10370        Some(&PoolType::IRONWOOD),
10371    );
10372
10373    let pczt = st
10374        .create_pczt_from_proposal::<Infallible, _, Infallible>(
10375            account_id,
10376            OvkPolicy::Sender,
10377            &proposal,
10378            None,
10379        )
10380        .expect("an Ironwood-routed payment builds as a version 6 PCZT");
10381
10382    // The PCZT is a version 6 transaction carrying a populated Ironwood bundle.
10383    assert_eq!(
10384        *pczt.global().tx_version(),
10385        zcash_protocol::constants::V6_TX_VERSION,
10386    );
10387    assert!(
10388        !pczt.ironwood().actions().is_empty(),
10389        "the PCZT carries an Ironwood bundle for the Ironwood-routed payment",
10390    );
10391
10392    // The Ironwood output carries the wallet's recipient metadata (the only proprietary field set
10393    // on Ironwood outputs), confirming the bundle is populated during construction rather than left
10394    // as an empty shell.
10395    assert!(
10396        pczt.ironwood()
10397            .actions()
10398            .iter()
10399            .any(|action| !action.output().proprietary().is_empty()),
10400        "the Ironwood output carries recipient metadata",
10401    );
10402
10403    #[derive(Clone, Debug, PartialEq, Eq)]
10404    struct SpendState {
10405        has_fvk: bool,
10406        has_signature: bool,
10407        has_alpha: bool,
10408        has_derivation: bool,
10409        value: Option<u64>,
10410    }
10411
10412    fn spend_states(pczt: pczt::Pczt) -> (Vec<SpendState>, Vec<SpendState>) {
10413        fn for_bundle(bundle: &orchard::pczt::Bundle) -> Vec<SpendState> {
10414            bundle
10415                .actions()
10416                .iter()
10417                .map(|action| SpendState {
10418                    has_fvk: action.spend().fvk().is_some(),
10419                    has_signature: action.spend().spend_auth_sig().is_some(),
10420                    has_alpha: action.spend().alpha().is_some(),
10421                    has_derivation: action.spend().zip32_derivation().is_some(),
10422                    value: action.spend().value().as_ref().map(|value| value.inner()),
10423                })
10424                .collect()
10425        }
10426
10427        let mut orchard = vec![];
10428        let mut ironwood = vec![];
10429        pczt::roles::verifier::Verifier::new(pczt)
10430            .with_orchard::<Infallible, _>(|bundle| {
10431                orchard = for_bundle(bundle);
10432                Ok(())
10433            })
10434            .unwrap()
10435            .with_ironwood::<Infallible, _>(|bundle| {
10436                ironwood = for_bundle(bundle);
10437                Ok(())
10438            })
10439            .unwrap();
10440        (orchard, ironwood)
10441    }
10442
10443    let original_sighash = Signer::new(pczt.clone()).unwrap().shielded_sighash();
10444    let original_spend_states = spend_states(pczt.clone());
10445
10446    // Every action in both bundles is either already signed (a pre-signed protocol padding
10447    // dummy, cleared by the IO Finalizer) or carries ZIP 32 derivation metadata so that an
10448    // external Signer that matches by derivation path can identify and sign it. Real spends
10449    // and the wallet-controlled zero-value spends the builder pairs with vanilla-pool change
10450    // outputs (post-NU6.3 cross-address rule) both need the derivation; only the pre-signed
10451    // dummies are allowed to lack it.
10452    for state in original_spend_states
10453        .0
10454        .iter()
10455        .chain(original_spend_states.1.iter())
10456    {
10457        assert!(
10458            state.has_signature || state.has_derivation,
10459            "every action must be either pre-signed or identifiable by an external signer \
10460             via ZIP 32 derivation: {state:?}",
10461        );
10462    }
10463    // Confirm this scenario actually exercises a wallet-controlled zero-value spend: the
10464    // vanilla Orchard-pool bundle pairs a zero-value dummy spend (unsigned, carrying `alpha`)
10465    // with the change output, and it is this spend that regressed by being left unsignable.
10466    assert!(
10467        original_spend_states
10468            .0
10469            .iter()
10470            .any(|state| state.value == Some(0) && !state.has_signature),
10471        "expected at least one unsigned zero-value Orchard spend (the wallet-controlled \
10472         change-pairing dummy)",
10473    );
10474
10475    let original_len = pczt.clone().serialize().unwrap().len();
10476    let signer_view = redact_pczt_for_signer(&pczt, SignerView::Compact);
10477    let signer_view_bytes = signer_view.serialize().unwrap();
10478    assert!(signer_view_bytes.len() < original_len);
10479    let signer_view = pczt::Pczt::parse(&signer_view_bytes).unwrap();
10480    assert_eq!(spend_states(signer_view.clone()), original_spend_states);
10481
10482    // The backend metadata belongs to the authoritative wallet copy, not the
10483    // external Signer.
10484    assert!(
10485        signer_view
10486            .global()
10487            .proprietary()
10488            .get("zcash_client_backend:proposal_info")
10489            .is_none()
10490    );
10491    assert!(
10492        pczt.global()
10493            .proprietary()
10494            .contains_key("zcash_client_backend:proposal_info")
10495    );
10496
10497    // V6 signatures do not commit to shielded anchors. Orchard action fields
10498    // that resolve_fields can restore are omitted from the signer view.
10499    assert!(signer_view.sapling().anchor().is_none());
10500    assert!(signer_view.orchard().anchor().is_none());
10501    assert!(signer_view.ironwood().anchor().is_none());
10502
10503    let assert_redacted_bundle =
10504        |original: &pczt::orchard::Bundle, redacted: &pczt::orchard::Bundle| {
10505            assert_eq!(redacted.actions().len(), original.actions().len());
10506            let mut memo_plaintexts = 0;
10507            for (redacted, original) in redacted.actions().iter().zip(original.actions()) {
10508                assert!(redacted.cv_net().is_none());
10509                assert!(redacted.output().cmx().is_none());
10510                assert_eq!(redacted.spend().nullifier(), original.spend().nullifier());
10511                assert_eq!(redacted.spend().rk(), original.spend().rk());
10512                assert_eq!(
10513                    redacted.spend().spend_auth_sig(),
10514                    original.spend().spend_auth_sig()
10515                );
10516                assert_eq!(
10517                    redacted.output().ephemeral_key(),
10518                    original.output().ephemeral_key()
10519                );
10520                assert_eq!(
10521                    redacted.output().out_ciphertext(),
10522                    original.output().out_ciphertext()
10523                );
10524                assert_eq!(
10525                    redacted.output().user_address(),
10526                    original.output().user_address()
10527                );
10528                assert!(
10529                    redacted
10530                        .output()
10531                        .proprietary()
10532                        .get("zcash_client_backend:output_info")
10533                        .is_none()
10534                );
10535                if matches!(
10536                    redacted.output().enc_ciphertext(),
10537                    pczt::orchard::EncCiphertext::MemoPlaintext(_)
10538                ) {
10539                    memo_plaintexts += 1;
10540                }
10541            }
10542            memo_plaintexts
10543        };
10544
10545    let memo_plaintexts = assert_redacted_bundle(pczt.orchard(), signer_view.orchard())
10546        + assert_redacted_bundle(pczt.ironwood(), signer_view.ironwood());
10547    assert!(memo_plaintexts > 0);
10548
10549    // The full signer view (for receivers that predate the compact view) commits to
10550    // the same transaction effects and, unlike the compact view, retains v6 anchors.
10551    let full_view = redact_pczt_for_signer(&pczt, SignerView::Full);
10552    assert_eq!(
10553        Signer::new(full_view.clone()).unwrap().shielded_sighash(),
10554        original_sighash,
10555    );
10556    assert!(full_view.ironwood().actions().iter().all(|action| {
10557        action.spend().witness().is_none() && action.spend().dummy_sk().is_none()
10558    }));
10559    assert_eq!(full_view.ironwood().anchor(), pczt.ironwood().anchor());
10560    assert!(
10561        !full_view
10562            .global()
10563            .proprietary()
10564            .contains_key("zcash_client_backend:proposal_info")
10565    );
10566    for bundle in [full_view.orchard(), full_view.ironwood()] {
10567        assert!(bundle.actions().iter().all(|action| {
10568            !action
10569                .output()
10570                .proprietary()
10571                .contains_key("zcash_client_backend:output_info")
10572        }));
10573    }
10574    assert!(full_view.sapling().outputs().iter().all(|output| {
10575        !output
10576            .proprietary()
10577            .contains_key("zcash_client_backend:output_info")
10578    }));
10579    assert!(full_view.transparent().outputs().iter().all(|output| {
10580        !output
10581            .proprietary()
10582            .contains_key("zcash_client_backend:output_info")
10583    }));
10584
10585    let batch_view = redact_pczt_for_batch_signer(&pczt);
10586    let batch_view_bytes = batch_view.serialize().unwrap();
10587    assert!(batch_view_bytes.len() < signer_view_bytes.len());
10588    let batch_view = pczt::Pczt::parse(&batch_view_bytes).unwrap();
10589    let batch_spend_states = spend_states(batch_view.clone());
10590
10591    let mut preauthorized_actions = 0;
10592    let mut unsigned_zero_value_actions = 0;
10593    for (original_bundle, batch_bundle) in [
10594        (&original_spend_states.0, &batch_spend_states.0),
10595        (&original_spend_states.1, &batch_spend_states.1),
10596    ] {
10597        assert_eq!(batch_bundle.len(), original_bundle.len());
10598        for (original, batch) in original_bundle.iter().zip(batch_bundle) {
10599            assert!(!batch.has_fvk);
10600            assert!(!batch.has_signature);
10601            assert_eq!(
10602                batch.has_alpha,
10603                original.has_alpha && !original.has_signature
10604            );
10605
10606            if original.has_signature {
10607                preauthorized_actions += 1;
10608            } else if original.value == Some(0) && original.has_alpha {
10609                unsigned_zero_value_actions += 1;
10610            }
10611        }
10612    }
10613    assert!(preauthorized_actions > 0);
10614    assert!(unsigned_zero_value_actions > 0);
10615
10616    // Resolving either compact representation restores byte-identical effecting
10617    // fields and therefore the same shielded signature digest.
10618    for compact_view in [&signer_view, &batch_view] {
10619        let mut resolved = (*compact_view).clone();
10620        resolved.resolve_fields().unwrap();
10621        for (resolved_bundle, original_bundle) in [
10622            (resolved.orchard(), pczt.orchard()),
10623            (resolved.ironwood(), pczt.ironwood()),
10624        ] {
10625            for (resolved, original) in resolved_bundle
10626                .actions()
10627                .iter()
10628                .zip(original_bundle.actions())
10629            {
10630                assert_eq!(resolved.cv_net(), original.cv_net());
10631                assert_eq!(resolved.output().cmx(), original.output().cmx());
10632                assert_eq!(
10633                    resolved.output().enc_ciphertext(),
10634                    original.output().enc_ciphertext()
10635                );
10636            }
10637        }
10638        assert_eq!(
10639            Signer::new((*compact_view).clone())
10640                .unwrap()
10641                .shielded_sighash(),
10642            original_sighash,
10643        );
10644    }
10645
10646    let signable_indices = |states: &[SpendState]| {
10647        states
10648            .iter()
10649            .enumerate()
10650            .filter_map(|(index, state)| (!state.has_signature && state.has_alpha).then_some(index))
10651            .collect::<Vec<_>>()
10652    };
10653    let orchard_signable = signable_indices(&original_spend_states.0);
10654    let ironwood_signable = signable_indices(&original_spend_states.1);
10655    assert!(
10656        orchard_signable
10657            .iter()
10658            .any(|&index| original_spend_states.0[index].value == Some(0))
10659    );
10660
10661    // The transported request contains no existing signatures. The batch Signer
10662    // contributes signatures for every unsigned action, including the wallet
10663    // controlled zero value spend, and returns only those new signatures.
10664    let request = pczt::roles::signer::batch::BatchSignRequest::new(vec![batch_view]);
10665    let request =
10666        pczt::roles::signer::batch::BatchSignRequest::parse(&request.serialize().unwrap()).unwrap();
10667    assert_eq!(request.pczts().len(), 1);
10668    let transported_view = request.pczts()[0].clone();
10669    assert_eq!(spend_states(transported_view.clone()), batch_spend_states);
10670
10671    let usk = st.get_account().usk().clone();
10672    let ask = orchard::keys::SpendAuthorizingKey::from(OrchardPoolTester::usk_to_sk(&usk));
10673    let signed_view = pczt::roles::low_level_signer::Signer::new(transported_view)
10674        .sign_orchard_with::<pczt::roles::low_level_signer::OrchardParseError, _>(|_, bundle, _| {
10675            for &index in &orchard_signable {
10676                bundle.actions_mut()[index]
10677                    .sign(original_sighash, &ask, UnwrapErr(SysRng))
10678                    .unwrap();
10679            }
10680            Ok(())
10681        })
10682        .unwrap()
10683        .sign_ironwood_with::<pczt::roles::low_level_signer::OrchardParseError, _>(
10684            |_, bundle, _| {
10685                for &index in &ironwood_signable {
10686                    bundle.actions_mut()[index]
10687                        .sign(original_sighash, &ask, UnwrapErr(SysRng))
10688                        .unwrap();
10689                }
10690                Ok(())
10691            },
10692        )
10693        .unwrap()
10694        .finish();
10695
10696    let signatures = pczt::roles::signer::extract_orchard_spend_auth_signatures(&signed_view);
10697    let expected_signature_positions = orchard_signable
10698        .iter()
10699        .copied()
10700        .map(|index| (orchard::ValuePool::Orchard, index))
10701        .chain(
10702            ironwood_signable
10703                .iter()
10704                .copied()
10705                .map(|index| (orchard::ValuePool::Ironwood, index)),
10706        )
10707        .collect::<Vec<_>>();
10708    let signature_positions = signatures
10709        .iter()
10710        .map(|signature| (signature.value_pool(), signature.action_index()))
10711        .collect::<Vec<_>>();
10712    assert_eq!(signature_positions, expected_signature_positions);
10713
10714    let response = pczt::roles::signer::batch::BatchSignResponse::new(vec![signatures]);
10715    let response =
10716        pczt::roles::signer::batch::BatchSignResponse::parse(&response.serialize().unwrap())
10717            .unwrap();
10718    assert_eq!(response.signatures().len(), 1);
10719
10720    let mut signer = Signer::new(pczt.clone()).unwrap();
10721    for signature in &response.signatures()[0] {
10722        signer
10723            .apply_orchard_spend_auth_signature(signature)
10724            .unwrap();
10725    }
10726    let authorized = signer.finish();
10727    assert_eq!(
10728        authorized.global().proprietary(),
10729        pczt.global().proprietary()
10730    );
10731
10732    let authorized_spend_states = spend_states(authorized.clone());
10733    for (original_bundle, authorized_bundle) in [
10734        (&original_spend_states.0, &authorized_spend_states.0),
10735        (&original_spend_states.1, &authorized_spend_states.1),
10736    ] {
10737        for (original, authorized) in original_bundle.iter().zip(authorized_bundle) {
10738            assert_eq!(authorized.has_fvk, original.has_fvk);
10739            assert_eq!(authorized.has_alpha, original.has_alpha);
10740            assert!(authorized.has_signature);
10741        }
10742    }
10743    for (authorized, original) in authorized
10744        .orchard()
10745        .actions()
10746        .iter()
10747        .zip(pczt.orchard().actions())
10748        .chain(
10749            authorized
10750                .ironwood()
10751                .actions()
10752                .iter()
10753                .zip(pczt.ironwood().actions()),
10754        )
10755    {
10756        if original.spend().spend_auth_sig().is_some() {
10757            assert_eq!(
10758                authorized.spend().spend_auth_sig(),
10759                original.spend().spend_auth_sig()
10760            );
10761        }
10762        assert_eq!(
10763            authorized.output().proprietary(),
10764            original.output().proprietary()
10765        );
10766    }
10767
10768    // Prove both bundles — a single Orchard proving key governs both pools post-NU6.3, selected
10769    // by the circuit version the PCZT's consensus branch implies — then extract the final
10770    // transaction and store it. The stored record must carry the IRONWOOD payment output (the
10771    // payment itself, which post-NU6.3 travels in the Ironwood bundle) alongside the Orchard
10772    // change; the Ironwood outputs were previously dropped from the stored `SentTransaction`
10773    // entirely (issue #2890).
10774    let pczt_branch_id = consensus::BranchId::try_from(*authorized.global().consensus_branch_id())
10775        .expect("the PCZT carries a valid consensus branch ID");
10776    let orchard_pk = zcash_primitives::transaction::builder::cached_orchard_proving_key(
10777        zcash_primitives::transaction::components::orchard::bundle_version_for_branch(
10778            pczt_branch_id,
10779            ::orchard::ValuePool::Orchard,
10780        )
10781        .expect("the PCZT's consensus branch supports the Orchard pool")
10782        .circuit_version(),
10783    );
10784    let proven = Prover::new(authorized)
10785        .create_orchard_proof(UnwrapErr(SysRng), orchard_pk)
10786        .unwrap()
10787        .create_ironwood_proof(UnwrapErr(SysRng), orchard_pk)
10788        .unwrap()
10789        .finish();
10790
10791    let txid = st
10792        .extract_and_store_transaction_from_pczt(proven)
10793        .expect("extracts, verifies, and stores the finalized transaction");
10794
10795    // The Ironwood payment output is recorded among the transaction's sent outputs, carrying the
10796    // payment value and the external recipient address.
10797    let sent_outputs = st.wallet().get_sent_outputs(&txid).unwrap();
10798    assert!(
10799        sent_outputs.iter().any(|output| {
10800            output.value() == Zatoshis::const_from_u64(10_000)
10801                && output.external_recipient().is_some()
10802        }),
10803        "the Ironwood payment output is recorded among the sent outputs: {sent_outputs:?}",
10804    );
10805    assert!(
10806        !st.wallet()
10807            .get_sent_note_ids(&txid, ShieldedPool::Ironwood)
10808            .unwrap()
10809            .is_empty(),
10810        "the payment's sent-note record belongs to the Ironwood pool",
10811    );
10812}
10813
10814/// The transaction history entry for a payment funded from the Orchard pool and delivered
10815/// through the Ironwood pool reports the amount that left the account (payment plus fee) as
10816/// its balance delta, not the total value of the notes spent, which would ignore the change
10817/// returned to the wallet.
10818#[cfg(feature = "orchard")]
10819pub fn orchard_to_ironwood_payment_reports_net_value_delta<Dsf>(
10820    ds_factory: Dsf,
10821    cache: impl TestCache,
10822) where
10823    Dsf: DataStoreFactory,
10824{
10825    // A network on which NU6.3, the version 6 transaction format, is active from height 100_000.
10826    let ironwood_active_network = {
10827        let activation = BlockHeight::from_u32(100_000);
10828        LocalNetwork {
10829            nu6: Some(activation),
10830            nu6_1: Some(activation),
10831            nu6_2: Some(activation),
10832            nu6_3: Some(activation),
10833            ..TestBuilder::<(), ()>::DEFAULT_NETWORK
10834        }
10835    };
10836
10837    let mut st = TestDsl::from(
10838        TestBuilder::new()
10839            .with_network(ironwood_active_network)
10840            .with_data_store_factory(ds_factory)
10841            .with_block_cache(cache)
10842            .with_account_from_sapling_activation(BlockHash([0; 32])),
10843    )
10844    .build::<OrchardPoolTester>();
10845
10846    // Fund the wallet with a single spendable Orchard note.
10847    let note_value = Zatoshis::const_from_u64(60_000);
10848    st.add_a_single_note_checking_balance(note_value);
10849
10850    // The destination has an Orchard receiver controlled by a separate spending key; post-NU6.3 the
10851    // payment is routed through the Ironwood pool.
10852    let to_extsk = OrchardPoolTester::sk(&[0xf5; 32]);
10853    let to = OrchardPoolTester::sk_default_address(&to_extsk);
10854    let transfer_amount = Zatoshis::const_from_u64(10_000);
10855    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
10856        to.to_zcash_address(st.network()),
10857        transfer_amount,
10858    )])
10859    .unwrap();
10860
10861    let change_strategy =
10862        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
10863    let input_selector = GreedyInputSelector::new();
10864
10865    let account = st.get_account();
10866    let account_id = account.id();
10867    let usk = account.usk().clone();
10868    let proposal = st
10869        .propose_transfer(
10870            account_id,
10871            &input_selector,
10872            &change_strategy,
10873            request,
10874            ConfirmationsPolicy::MIN,
10875        )
10876        .expect("proposal construction succeeds; the Orchard-receiver payment routes to Ironwood");
10877
10878    // The payment crosses from the Orchard pool into the Ironwood pool.
10879    assert_eq!(
10880        proposal.steps().head.payment_pools().get(&0),
10881        Some(&PoolType::IRONWOOD),
10882    );
10883    let fee = proposal.steps().head.balance().fee_required();
10884    let expected_change = (note_value - transfer_amount - fee).unwrap();
10885
10886    let txids = st
10887        .create_proposed_transactions::<Infallible, _, Infallible, _>(
10888            &usk,
10889            OvkPolicy::Sender,
10890            &proposal,
10891        )
10892        .expect("an Ironwood-routed payment builds successfully");
10893    let txid = *txids.first();
10894
10895    // The amount that left the account is the payment plus the fee; the value of the change
10896    // note returned to the wallet must not be counted as spent.
10897    let expected_delta = -zcash_protocol::value::ZatBalance::from((transfer_amount + fee).unwrap());
10898    macro_rules! check_history {
10899        ($phase:literal) => {{
10900            let tx_history = st.wallet().get_tx_history().unwrap();
10901            let tx = tx_history
10902                .iter()
10903                .find(|tx| tx.txid() == txid)
10904                .expect("the created transaction appears in the transaction history");
10905            assert_eq!(
10906                tx.account_value_delta(),
10907                expected_delta,
10908                "account_value_delta ({}) reflects the payment plus fee",
10909                $phase,
10910            );
10911            assert_eq!(
10912                tx.total_spent(),
10913                note_value,
10914                "total_spent ({}) is the total value of the notes spent",
10915                $phase,
10916            );
10917            assert_eq!(
10918                tx.total_received(),
10919                expected_change,
10920                "total_received ({}) is the change returned to the wallet",
10921                $phase,
10922            );
10923            assert!(tx.has_change(), "the transaction has change ({})", $phase);
10924            // The payment has an external recipient, so it is not a pool crossing even though
10925            // its value moves from the Orchard pool into the Ironwood pool.
10926            assert_eq!(
10927                tx.pool_crossing_value(),
10928                None,
10929                "a payment to an external recipient is not a pool crossing ({})",
10930                $phase,
10931            );
10932        }};
10933    }
10934
10935    // The history entry is correct as soon as the transaction is stored...
10936    check_history!("before mining");
10937
10938    // ...and remains correct once the transaction is mined and scanned...
10939    let (h, _) = st.generate_next_block_including(txid);
10940    st.scan_cached_blocks(h, 1);
10941    check_history!("after mining");
10942
10943    // ...and remains correct after transaction enhancement, in which the wallet retrieves the
10944    // full transaction and re-stores it via `decrypt_and_store_transaction` (as the mobile
10945    // SDKs do to recover memos and fee information).
10946    let tx = st
10947        .wallet()
10948        .get_transaction(txid)
10949        .unwrap()
10950        .expect("the created transaction can be retrieved");
10951    let network = *st.network();
10952    decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, Some(h)).unwrap();
10953    check_history!("after enhancement");
10954}
10955
10956/// A migration of the wallet's own funds from the Orchard pool to the Ironwood pool, namely a
10957/// payment to the wallet's own external Orchard receiver delivered through the Ironwood pool, leaves
10958/// the account balance unchanged except for the fee. The payment output returned to the wallet
10959/// is not recorded at transaction-creation time (it is an address payment, which the wallet
10960/// expects to detect by scanning), so this exercises detection of the wallet's own Ironwood
10961/// outputs in the scanning path.
10962#[cfg(feature = "orchard")]
10963pub fn orchard_to_ironwood_self_migration_reports_fee_only_delta<Dsf>(
10964    ds_factory: Dsf,
10965    cache: impl TestCache,
10966) where
10967    Dsf: DataStoreFactory,
10968{
10969    // A network on which NU6.3, the version 6 transaction format, is active from height 100_000.
10970    let ironwood_active_network = {
10971        let activation = BlockHeight::from_u32(100_000);
10972        LocalNetwork {
10973            nu6: Some(activation),
10974            nu6_1: Some(activation),
10975            nu6_2: Some(activation),
10976            nu6_3: Some(activation),
10977            ..TestBuilder::<(), ()>::DEFAULT_NETWORK
10978        }
10979    };
10980
10981    let mut st = TestDsl::from(
10982        TestBuilder::new()
10983            .with_network(ironwood_active_network)
10984            .with_data_store_factory(ds_factory)
10985            .with_block_cache(cache)
10986            .with_account_from_sapling_activation(BlockHash([0; 32])),
10987    )
10988    .build::<OrchardPoolTester>();
10989
10990    // Fund the wallet with a single spendable Orchard note.
10991    let note_value = Zatoshis::const_from_u64(60_000);
10992    st.add_a_single_note_checking_balance(note_value);
10993
10994    // The payment destination is the wallet's own external Orchard receiver; post-NU6.3 the
10995    // payment is routed through the Ironwood pool.
10996    let own_fvk = OrchardPoolTester::test_account_fvk(&st);
10997    let own_address = OrchardPoolTester::fvk_default_address(&own_fvk);
10998    let transfer_amount = Zatoshis::const_from_u64(40_000);
10999    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
11000        own_address.to_zcash_address(st.network()),
11001        transfer_amount,
11002    )])
11003    .unwrap();
11004
11005    let change_strategy =
11006        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
11007    let input_selector = GreedyInputSelector::new();
11008
11009    let account = st.get_account();
11010    let account_id = account.id();
11011    let usk = account.usk().clone();
11012    let proposal = st
11013        .propose_transfer(
11014            account_id,
11015            &input_selector,
11016            &change_strategy,
11017            request,
11018            ConfirmationsPolicy::MIN,
11019        )
11020        .expect("proposal construction succeeds; the Orchard-receiver payment routes to Ironwood");
11021
11022    // The payment crosses from the Orchard pool into the Ironwood pool.
11023    assert_eq!(
11024        proposal.steps().head.payment_pools().get(&0),
11025        Some(&PoolType::IRONWOOD),
11026    );
11027    let fee = proposal.steps().head.balance().fee_required();
11028
11029    let txids = st
11030        .create_proposed_transactions::<Infallible, _, Infallible, _>(
11031            &usk,
11032            OvkPolicy::Sender,
11033            &proposal,
11034        )
11035        .expect("an Ironwood-routed payment builds successfully");
11036    let txid = *txids.first();
11037
11038    // Once the transaction is mined and scanned, every non-fee output has returned to the
11039    // wallet: the payment output via scanning, and the change output. The account has lost
11040    // only the fee.
11041    let (h, _) = st.generate_next_block_including(txid);
11042    st.scan_cached_blocks(h, 1);
11043
11044    macro_rules! check_history {
11045        ($phase:literal) => {{
11046            let tx_history = st.wallet().get_tx_history().unwrap();
11047            let tx = tx_history
11048                .iter()
11049                .find(|tx| tx.txid() == txid)
11050                .expect("the created transaction appears in the transaction history");
11051            assert_eq!(
11052                tx.total_spent(),
11053                note_value,
11054                "total_spent ({}) is the total value of the notes spent",
11055                $phase,
11056            );
11057            assert_eq!(
11058                tx.total_received(),
11059                (note_value - fee).unwrap(),
11060                "total_received ({}) covers both the migrated value and the change",
11061                $phase,
11062            );
11063            assert_eq!(
11064                tx.account_value_delta(),
11065                -zcash_protocol::value::ZatBalance::from(fee),
11066                "the migration ({}) reduces the account balance only by the fee",
11067                $phase,
11068            );
11069            // Once the wallet has observed the payment output returning to its own account
11070            // (the scanner marks such outputs as change), the transaction presents as a
11071            // wallet-internal transfer between pools, and is classified as a pool crossing
11072            // whose crossing value is the migrated payment amount, the quantity a wallet
11073            // should display for it.
11074            assert!(
11075                tx.is_pool_crossing(),
11076                "a mined payment to the wallet's own address is a pool crossing ({})",
11077                $phase,
11078            );
11079            assert_eq!(
11080                tx.pool_crossing_value(),
11081                Some(transfer_amount),
11082                "pool_crossing_value ({}) is the migrated payment amount",
11083                $phase,
11084            );
11085        }};
11086    }
11087
11088    check_history!("after mining");
11089    assert_eq!(
11090        st.get_total_balance(account_id),
11091        (note_value - fee).unwrap(),
11092        "the account retains all funds except the fee",
11093    );
11094
11095    // The history entry remains correct after transaction enhancement, in which the wallet
11096    // retrieves the full transaction and re-stores it via `decrypt_and_store_transaction`
11097    // (as the mobile SDKs do to recover memos and fee information).
11098    let tx = st
11099        .wallet()
11100        .get_transaction(txid)
11101        .unwrap()
11102        .expect("the created transaction can be retrieved");
11103    let network = *st.network();
11104    decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, Some(h)).unwrap();
11105    check_history!("after enhancement");
11106}
11107
11108/// The transaction version requested at proposal time is recorded on the proposal and preserved
11109/// across serialization, so that transaction building honors it. A proposal serialized without a
11110/// version request (as older serializers produced) decodes with no requested version and falls
11111/// back to the target-height version at build time.
11112#[cfg(feature = "orchard")]
11113pub fn proposal_records_and_serializes_proposed_version<Dsf>(ds_factory: Dsf, cache: impl TestCache)
11114where
11115    Dsf: DataStoreFactory,
11116{
11117    let mut st = TestDsl::from(
11118        TestBuilder::new()
11119            .with_data_store_factory(ds_factory)
11120            .with_block_cache(cache)
11121            .with_account_from_sapling_activation(BlockHash([0; 32])),
11122    )
11123    .build::<OrchardPoolTester>();
11124
11125    // Fund the wallet with a single spendable Orchard note.
11126    st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60_000));
11127
11128    let to_extsk = OrchardPoolTester::sk(&[0xf5; 32]);
11129    let to = OrchardPoolTester::sk_default_address(&to_extsk);
11130    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
11131        to.to_zcash_address(st.network()),
11132        Zatoshis::const_from_u64(10_000),
11133    )])
11134    .unwrap();
11135
11136    let change_strategy =
11137        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
11138    let input_selector = GreedyInputSelector::new();
11139
11140    let account_id = st.get_account().id();
11141    let network = *st.network();
11142    // The test network's most recent upgrade is NU5, so version 5 is a valid explicit request.
11143    let proposal = propose_transfer::<_, _, _, _, Infallible>(
11144        st.wallet_mut(),
11145        &network,
11146        account_id,
11147        &input_selector,
11148        &change_strategy,
11149        request,
11150        ConfirmationsPolicy::MIN,
11151        &SpendPolicy::default(),
11152        None,
11153        Some(TxVersion::V5),
11154    )
11155    .expect("proposal construction succeeds");
11156
11157    // The requested version is recorded on the proposal.
11158    assert_eq!(proposal.proposed_version(), Some(TxVersion::V5));
11159
11160    // ... and is preserved across a round-trip through the proposal's serialized (proto) form.
11161    let proto = crate::proto::proposal::Proposal::from_standard_proposal(&proposal);
11162    let decoded = proto
11163        .try_into_standard_proposal(&network, st.wallet())
11164        .expect("the serialized proposal decodes");
11165    assert_eq!(decoded.proposed_version(), Some(TxVersion::V5));
11166
11167    // A proposal serialized without the field (as an older serializer produced) decodes with no
11168    // requested version.
11169    let mut legacy_proto = crate::proto::proposal::Proposal::from_standard_proposal(&proposal);
11170    legacy_proto.proposed_version = None;
11171    let decoded_legacy = legacy_proto
11172        .try_into_standard_proposal(&network, st.wallet())
11173        .expect("a legacy proposal without a requested version must decode");
11174    assert_eq!(decoded_legacy.proposed_version(), None);
11175}
11176
11177/// A payment whose value is a canonical ZIP 318 denomination, fundable from a single Orchard note,
11178/// is proposed against a bucketed anchor and built with a single unpadded Ironwood action — the
11179/// shape of a ZIP 318 migration transfer. Everything else keeps the ordinary anchor and the
11180/// two-action floor.
11181#[cfg(feature = "orchard")]
11182pub fn canonical_crossing_is_bucketed_and_unpadded<Dsf: DataStoreFactory>(
11183    ds_factory: Dsf,
11184    cache: impl TestCache,
11185) {
11186    // A short grid, so the test need not mine 144 blocks to cross a boundary.
11187    let interval = AnchorBucketInterval::custom(NonZeroU32::new(12).expect("nonzero"));
11188    let activation = BlockHeight::from_u32(100_000);
11189    let ironwood_active_network = LocalNetwork {
11190        nu6: Some(activation),
11191        nu6_1: Some(activation),
11192        nu6_2: Some(activation),
11193        nu6_3: Some(activation),
11194        ..TestBuilder::<(), ()>::DEFAULT_NETWORK
11195    };
11196
11197    let mut st = TestDsl::from(
11198        TestBuilder::new()
11199            .with_network(ironwood_active_network)
11200            .with_data_store_factory(ds_factory)
11201            .with_block_cache(cache)
11202            .with_anchor_retention_interval(interval)
11203            .with_account_from_sapling_activation(BlockHash([0; 32])),
11204    )
11205    .build::<OrchardPoolTester>();
11206
11207    let account = st.test_account().cloned().unwrap();
11208    let fvk = OrchardPoolTester::test_account_fvk(&st);
11209    let recipient = OrchardPoolTester::fvk_default_address(&fvk).to_zcash_address(st.network());
11210
11211    // One Orchard note, comfortably larger than a canonical denomination plus fees.
11212    let note_value = Zatoshis::const_from_u64(10_000_000);
11213    let (received_height, _, _) = st.add_a_single_note_checking_balance(note_value);
11214
11215    // Mine well past the next boundary, so the note is spendable at the bucketed anchor and a
11216    // usable boundary exists at or below the ordinary anchor. This is a COUNTED loop over a
11217    // precomputed block count: `generate_next_block` appends to the block cache, whereas
11218    // `chain_height` reads the wallet and only advances on `scan_cached_blocks`, so looping until
11219    // the wallet's height reaches a target would never terminate.
11220    let received = u32::from(received_height);
11221    let interval_blocks = interval.block_count().get();
11222    // Deliberately OFF a boundary: the ordinary anchor must not be a grid boundary by accident,
11223    // or an assertion that a canonical crossing was bucketed would pass trivially.
11224    let tip = u32::from(anchor_grid(st.network(), interval).boundary_at_or_above(received_height))
11225        + 3 * interval_blocks
11226        + 5;
11227    let filler_count = tip - received;
11228
11229    // Fillers pay a non-wallet key, so each block adds a commitment (and thus a checkpoint)
11230    // without changing the wallet's spendable set.
11231    let not_our_fvk = OrchardPoolTester::sk_to_fvk(&OrchardPoolTester::sk(&[0xf5; 32]));
11232    for _ in 0..filler_count {
11233        st.generate_next_block(
11234            &not_our_fvk,
11235            AddressType::DefaultExternal,
11236            Zatoshis::const_from_u64(10_000),
11237        );
11238    }
11239    st.scan_cached_blocks(received_height + 1, filler_count as usize);
11240
11241    let input_selector = GreedyInputSelector::new();
11242    let change_strategy =
11243        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
11244
11245    let propose = |st: &mut TestState<_, _, _>, amount: Zatoshis| {
11246        let request =
11247            TransactionRequest::new(vec![Payment::without_memo(recipient.clone(), amount)])
11248                .unwrap();
11249        st.propose_transfer(
11250            account.id(),
11251            &input_selector,
11252            &change_strategy,
11253            request,
11254            ConfirmationsPolicy::MIN,
11255        )
11256    };
11257
11258    // (1) A canonical denomination: bucketed anchor, one Orchard input, one Ironwood action.
11259    let canonical = propose(&mut st, MAX_RESIDUAL_VALUE).expect("the wallet can fund this");
11260    assert_eq!(canonical.steps().len(), 1);
11261    let canonical_fee = crate::fees::canonical_crossing_fee(
11262        st.network(),
11263        BlockHeight::from(canonical.min_target_height()),
11264    )
11265    .expect("the canonical shape is a valid input to the ZIP 317 rule");
11266
11267    let step = canonical.steps().first();
11268    let anchor = step
11269        .anchor_height()
11270        .expect("a shielded step binds an anchor");
11271    assert!(
11272        anchor_grid(st.network(), interval).is_boundary(anchor),
11273        "a canonical crossing must anchor to a grid boundary, got {anchor:?}"
11274    );
11275    assert_eq!(step.input_count_in_pool(PoolType::ORCHARD), 1);
11276    assert_eq!(step.input_count_in_pool(PoolType::IRONWOOD), 0);
11277    assert!(step.is_canonical_crossing(
11278        &st.wallet().pool_migration_params(st.network()),
11279        canonical_fee
11280    ));
11281    assert_eq!(
11282        step.ironwood_action_count(
11283            step.ironwood_bundle_padding(),
11284            ::orchard::bundle::BundleVersion::ironwood_v3()
11285        ),
11286        Ok(1),
11287        "the Ironwood bundle must be a single unpadded action"
11288    );
11289
11290    // (2) One zatoshi off a canonical denomination: ordinary anchor, padded Ironwood bundle.
11291    let off_by_one = propose(
11292        &mut st,
11293        (MAX_RESIDUAL_VALUE + Zatoshis::const_from_u64(1)).unwrap(),
11294    )
11295    .unwrap();
11296    let step = off_by_one.steps().first();
11297    assert!(!step.is_canonical_crossing(
11298        &st.wallet().pool_migration_params(st.network()),
11299        canonical_fee
11300    ));
11301    assert_eq!(
11302        step.ironwood_action_count(
11303            step.ironwood_bundle_padding(),
11304            ::orchard::bundle::BundleVersion::ironwood_v3()
11305        ),
11306        Ok(2)
11307    );
11308    assert!(
11309        !anchor_grid(st.network(), interval).is_boundary(step.anchor_height().unwrap()),
11310        "a non-canonical payment must not pay for a bucketed anchor"
11311    );
11312
11313    // Building the canonical proposal is left until last: it spends the wallet's only note, so the
11314    // comparison above must be proposed while funds remain. The built transaction takes the ZIP 318
11315    // rolling expiry rather than the builder's per-transaction one — every crossing in the same
11316    // modulus period shares it, so it identifies nothing.
11317    // ROUND TRIP. The proposal records the exact dummy outputs costed by the fee model; the
11318    // builder reads that transaction shape back rather than deciding again.
11319    assert_eq!(
11320        canonical
11321            .steps()
11322            .first()
11323            .balance()
11324            .dummy_outputs()
11325            .expect("the fee model records dummy outputs")
11326            .ironwood(),
11327        0,
11328        "a canonical crossing has no Ironwood dummy output"
11329    );
11330    assert_eq!(
11331        canonical.steps().first().ironwood_bundle_padding(),
11332        BundlePadding::UNPADDED,
11333        "and the step must report the recorded value to the builder"
11334    );
11335
11336    // The proposal crosses the FFI boundary before it is built as a PCZT. Preserve all per-pool
11337    // dummy-output counts through that serialization round-trip.
11338    let proto = crate::proto::proposal::Proposal::from_standard_proposal(&canonical);
11339    let serialized_dummy_outputs = proto.steps[0]
11340        .balance
11341        .as_ref()
11342        .expect("a proposal step carries a balance")
11343        .dummy_outputs
11344        .as_ref()
11345        .expect("new proposals serialize their dummy outputs");
11346    assert_eq!(
11347        (
11348            serialized_dummy_outputs.sapling,
11349            serialized_dummy_outputs.orchard,
11350            serialized_dummy_outputs.ironwood,
11351        ),
11352        (0, 1, 0)
11353    );
11354    let canonical = proto
11355        .try_into_standard_proposal(st.network(), st.wallet())
11356        .expect("the canonical proposal must deserialize");
11357    assert_eq!(
11358        canonical
11359            .steps()
11360            .first()
11361            .balance()
11362            .dummy_outputs()
11363            .expect("dummy outputs survive proposal decoding")
11364            .ironwood(),
11365        0,
11366        "the PCZT proposal round-trip must preserve the Ironwood dummy-output count"
11367    );
11368
11369    let txids = st.create_proposed_expecting(&canonical, 1);
11370    let built = st
11371        .wallet()
11372        .get_transaction(txids[0])
11373        .unwrap()
11374        .expect("the transaction was stored");
11375    assert_eq!(
11376        built
11377            .ironwood_bundle()
11378            .expect("a crossing carries an Ironwood bundle")
11379            .actions()
11380            .len(),
11381        1,
11382        "the BUILT Ironwood bundle must have the single action the fee was charged for"
11383    );
11384
11385    let tx = st.get_tx_from_history(txids[0]).unwrap().unwrap();
11386    assert_eq!(
11387        tx.expiry_height(),
11388        Some(zcash_protocol::zip318::expiry_height(
11389            &zcash_protocol::zip318::BlockSpacing::for_network(st.network()),
11390            BlockHeight::from(canonical.min_target_height())
11391        )),
11392        "a canonical crossing must carry the ZIP 318 rolling expiry"
11393    );
11394    assert_eq!(
11395        tx.fee_paid(),
11396        Some(canonical_fee),
11397        "and the canonical ZIP 317 fee that shape costs"
11398    );
11399}
11400
11401/// A canonical crossing whose bucketed anchor falls on a block with no shielded outputs must
11402/// still build. Note eligibility at the bucketed anchor is a height comparison, so the proposal
11403/// selects and anchors there regardless; unless the boundary checkpoint was ensured at scan time
11404/// — the boundary block itself contributed no note commitment to create one — building would
11405/// fail attempting to construct witnesses at a checkpoint that does not exist.
11406#[cfg(feature = "orchard")]
11407pub fn canonical_crossing_builds_at_empty_boundary_block<Dsf: DataStoreFactory>(
11408    ds_factory: Dsf,
11409    cache: impl TestCache,
11410) {
11411    // A short grid, so the test need not mine 144 blocks to cross a boundary.
11412    let interval = AnchorRetentionInterval::custom(NonZeroU32::new(12).expect("nonzero"));
11413    let activation = BlockHeight::from_u32(100_000);
11414    let ironwood_active_network = LocalNetwork {
11415        nu6: Some(activation),
11416        nu6_1: Some(activation),
11417        nu6_2: Some(activation),
11418        nu6_3: Some(activation),
11419        ..TestBuilder::<(), ()>::DEFAULT_NETWORK
11420    };
11421
11422    let mut st = TestDsl::from(
11423        TestBuilder::new()
11424            .with_network(ironwood_active_network)
11425            .with_data_store_factory(ds_factory)
11426            .with_block_cache(cache)
11427            .with_anchor_retention_interval(interval)
11428            .with_account_from_sapling_activation(BlockHash([0; 32])),
11429    )
11430    .build::<OrchardPoolTester>();
11431
11432    let account = st.test_account().cloned().unwrap();
11433    let fvk = OrchardPoolTester::test_account_fvk(&st);
11434    let recipient = OrchardPoolTester::fvk_default_address(&fvk).to_zcash_address(st.network());
11435
11436    // One Orchard note, comfortably larger than a canonical denomination plus fees.
11437    let note_value = Zatoshis::const_from_u64(10_000_000);
11438    let (received_height, _, _) = st.add_a_single_note_checking_balance(note_value);
11439    let received = u32::from(received_height);
11440    let interval_blocks = interval.block_count().get();
11441
11442    // Mine well past the next boundary, deliberately ending OFF a boundary, exactly as in
11443    // `canonical_crossing_is_bucketed_and_unpadded` — but here every BOUNDARY block is generated
11444    // empty, while the other fillers pay a non-wallet key. The bucketed anchor the proposal picks
11445    // is a boundary, and every boundary in the range is an empty block, so the anchor necessarily
11446    // lands on one.
11447    let tip = u32::from(anchor_grid(st.network(), interval).boundary_at_or_above(received_height))
11448        + 3 * interval_blocks
11449        + 5;
11450    let not_our_fvk = OrchardPoolTester::sk_to_fvk(&OrchardPoolTester::sk(&[0xf5; 32]));
11451    let mut empty_heights = Vec::new();
11452    for height in (received + 1)..=tip {
11453        if anchor_grid(st.network(), interval).is_boundary(BlockHeight::from_u32(height)) {
11454            let (h, _) = st.generate_empty_block();
11455            empty_heights.push(h);
11456        } else {
11457            st.generate_next_block(
11458                &not_our_fvk,
11459                AddressType::DefaultExternal,
11460                Zatoshis::const_from_u64(10_000),
11461            );
11462        }
11463    }
11464    // One batch: block-by-block scanning would checkpoint every height via batch frontiers,
11465    // masking the missing-boundary-checkpoint condition this test exercises.
11466    st.scan_cached_blocks(received_height + 1, (tip - received) as usize);
11467
11468    let input_selector = GreedyInputSelector::new();
11469    let change_strategy =
11470        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
11471    let request = TransactionRequest::new(vec![Payment::without_memo(
11472        recipient.clone(),
11473        MAX_RESIDUAL_VALUE,
11474    )])
11475    .unwrap();
11476    let canonical = st
11477        .propose_transfer(
11478            account.id(),
11479            &input_selector,
11480            &change_strategy,
11481            request,
11482            ConfirmationsPolicy::MIN,
11483        )
11484        .expect("the wallet can fund this");
11485
11486    let canonical_fee = crate::fees::canonical_crossing_fee(
11487        st.network(),
11488        BlockHeight::from(canonical.min_target_height()),
11489    )
11490    .expect("the canonical shape is a valid input to the ZIP 317 rule");
11491    let step = canonical.steps().first();
11492    let anchor = step
11493        .anchor_height()
11494        .expect("a shielded step binds an anchor");
11495    assert!(
11496        step.is_canonical_crossing(
11497            &st.wallet().pool_migration_params(st.network()),
11498            canonical_fee
11499        ),
11500        "the payment must be recognized as a canonical crossing"
11501    );
11502    assert!(
11503        empty_heights.contains(&anchor),
11504        "the bucketed anchor {anchor:?} must be one of the empty boundary blocks {empty_heights:?}"
11505    );
11506
11507    // Building must succeed: the anchor's checkpoint was ensured when the batch was scanned, even
11508    // though the boundary block itself contributed no commitment.
11509    let txids = st.create_proposed_expecting(&canonical, 1);
11510    let built = st
11511        .wallet()
11512        .get_transaction(txids[0])
11513        .unwrap()
11514        .expect("the transaction was stored");
11515    assert_eq!(
11516        built
11517            .ironwood_bundle()
11518            .expect("a crossing carries an Ironwood bundle")
11519            .actions()
11520            .len(),
11521        1,
11522        "the BUILT Ironwood bundle must have the single action of the canonical shape"
11523    );
11524}
11525
11526/// A canonical amount that cannot be funded from a single Orchard note is NOT a canonical
11527/// crossing, and must not pay for a bucketed anchor it gains nothing from.
11528///
11529/// A migration transfer spends exactly one note, so a multi-input transaction resembles none. The
11530/// decision is therefore made before the proposal is kept: had it been made by falling back only
11531/// on insufficient funds, this transaction would have funded perfectly well from several notes and
11532/// been left carrying an anchor up to a full interval older than necessary, for no benefit.
11533#[cfg(feature = "orchard")]
11534pub fn multi_note_crossing_is_not_bucketed<Dsf: DataStoreFactory>(
11535    ds_factory: Dsf,
11536    cache: impl TestCache,
11537) {
11538    let interval = AnchorBucketInterval::custom(NonZeroU32::new(12).expect("nonzero"));
11539    let activation = BlockHeight::from_u32(100_000);
11540    let network = LocalNetwork {
11541        nu6: Some(activation),
11542        nu6_1: Some(activation),
11543        nu6_2: Some(activation),
11544        nu6_3: Some(activation),
11545        ..TestBuilder::<(), ()>::DEFAULT_NETWORK
11546    };
11547
11548    let mut st = TestDsl::from(
11549        TestBuilder::new()
11550            .with_network(network)
11551            .with_data_store_factory(ds_factory)
11552            .with_block_cache(cache)
11553            .with_anchor_retention_interval(interval)
11554            .with_account_from_sapling_activation(BlockHash([0; 32])),
11555    )
11556    .build::<OrchardPoolTester>();
11557
11558    let account = st.test_account().cloned().unwrap();
11559    let fvk = OrchardPoolTester::test_account_fvk(&st);
11560    let recipient = OrchardPoolTester::fvk_default_address(&fvk).to_zcash_address(st.network());
11561
11562    // Three notes, none individually able to cover the payment plus its fee.
11563    let note_value = Zatoshis::const_from_u64(400_000);
11564    let (first_height, _, _) = st.add_a_single_note_checking_balance(note_value);
11565    for _ in 0..2 {
11566        st.generate_next_block(&fvk, AddressType::DefaultExternal, note_value);
11567    }
11568    st.scan_cached_blocks(first_height + 1, 2);
11569
11570    let interval_blocks = interval.block_count().get();
11571    let tip = u32::from(anchor_grid(st.network(), interval).boundary_at_or_above(first_height))
11572        + 3 * interval_blocks
11573        + 5;
11574    let not_our_fvk = OrchardPoolTester::sk_to_fvk(&OrchardPoolTester::sk(&[0xf5; 32]));
11575    let filler_count = tip - u32::from(first_height) - 2;
11576    for _ in 0..filler_count {
11577        st.generate_next_block(
11578            &not_our_fvk,
11579            AddressType::DefaultExternal,
11580            Zatoshis::const_from_u64(10_000),
11581        );
11582    }
11583    st.scan_cached_blocks(first_height + 3, filler_count as usize);
11584
11585    let input_selector = GreedyInputSelector::new();
11586    let change_strategy =
11587        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
11588    let request =
11589        TransactionRequest::new(vec![Payment::without_memo(recipient, MAX_RESIDUAL_VALUE)])
11590            .unwrap();
11591
11592    let proposal = st
11593        .propose_transfer(
11594            account.id(),
11595            &input_selector,
11596            &change_strategy,
11597            request,
11598            ConfirmationsPolicy::MIN,
11599        )
11600        .expect("three notes together can fund the payment");
11601
11602    let step = proposal.steps().first();
11603    let zip318 = st.wallet().pool_migration_params(st.network());
11604    let canonical_fee = crate::fees::canonical_crossing_fee(
11605        st.network(),
11606        BlockHeight::from(proposal.min_target_height()),
11607    )
11608    .expect("the canonical shape is a valid input to the ZIP 317 rule");
11609    assert!(
11610        step.input_count_in_pool(PoolType::ORCHARD) > 1,
11611        "this scenario is only meaningful if funding needs several notes"
11612    );
11613    assert!(!step.is_canonical_crossing(&zip318, canonical_fee));
11614    assert!(
11615        !anchor_grid(st.network(), interval).is_boundary(step.anchor_height().unwrap()),
11616        "a multi-input transaction must not pay for a bucketed anchor"
11617    );
11618    assert_eq!(
11619        step.ironwood_action_count(
11620            step.ironwood_bundle_padding(),
11621            ::orchard::bundle::BundleVersion::ironwood_v3()
11622        ),
11623        Ok(2)
11624    );
11625}
11626
11627/// A canonical payment is funded from the single oldest covering note even when accumulation
11628/// would have reached the target through several smaller notes first.
11629///
11630/// Oldest-first accumulation crosses the target through small notes whenever the oldest notes
11631/// are small, funding the payment while losing the single-input canonical shape. The canonical
11632/// attempt therefore PREFERS single-note funding ([`NoteSelection::PreferSingle`]): when any
11633/// single eligible note covers the payment and its fee, that note is chosen and the transaction
11634/// takes the migration shape. Ordinary (non-canonical) payments keep accumulating.
11635///
11636/// [`NoteSelection::PreferSingle`]:
11637///     crate::data_api::wallet::input_selection::NoteSelection::PreferSingle
11638#[cfg(feature = "orchard")]
11639pub fn canonical_crossing_prefers_single_note<Dsf: DataStoreFactory>(
11640    ds_factory: Dsf,
11641    cache: impl TestCache,
11642) {
11643    let interval = AnchorRetentionInterval::custom(NonZeroU32::new(12).expect("nonzero"));
11644    let activation = BlockHeight::from_u32(100_000);
11645    let network = LocalNetwork {
11646        nu6: Some(activation),
11647        nu6_1: Some(activation),
11648        nu6_2: Some(activation),
11649        nu6_3: Some(activation),
11650        ..TestBuilder::<(), ()>::DEFAULT_NETWORK
11651    };
11652
11653    let mut st = TestDsl::from(
11654        TestBuilder::new()
11655            .with_network(network)
11656            .with_data_store_factory(ds_factory)
11657            .with_block_cache(cache)
11658            .with_anchor_retention_interval(interval)
11659            .with_account_from_sapling_activation(BlockHash([0; 32])),
11660    )
11661    .build::<OrchardPoolTester>();
11662
11663    let account = st.test_account().cloned().unwrap();
11664    let fvk = OrchardPoolTester::test_account_fvk(&st);
11665    let recipient = OrchardPoolTester::fvk_default_address(&fvk).to_zcash_address(st.network());
11666
11667    // Two OLDER notes that together cover the payment, then one LARGER note that covers it
11668    // alone. Accumulation reaches the target at the second note and never touches the third,
11669    // so which shape the proposal takes distinguishes the two selection behaviors.
11670    let small_value = Zatoshis::const_from_u64(600_000);
11671    let large_value = Zatoshis::const_from_u64(1_200_000);
11672    let (first_height, _, _) = st.add_a_single_note_checking_balance(small_value);
11673    st.generate_next_block(&fvk, AddressType::DefaultExternal, small_value);
11674    st.generate_next_block(&fvk, AddressType::DefaultExternal, large_value);
11675    st.scan_cached_blocks(first_height + 1, 2);
11676
11677    let interval_blocks = interval.block_count().get();
11678    let tip = u32::from(anchor_grid(st.network(), interval).boundary_at_or_above(first_height))
11679        + 3 * interval_blocks
11680        + 5;
11681    let not_our_fvk = OrchardPoolTester::sk_to_fvk(&OrchardPoolTester::sk(&[0xf5; 32]));
11682    let filler_count = tip - u32::from(first_height) - 2;
11683    for _ in 0..filler_count {
11684        st.generate_next_block(
11685            &not_our_fvk,
11686            AddressType::DefaultExternal,
11687            Zatoshis::const_from_u64(10_000),
11688        );
11689    }
11690    st.scan_cached_blocks(first_height + 3, filler_count as usize);
11691
11692    let input_selector = GreedyInputSelector::new();
11693    let change_strategy =
11694        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
11695    let propose = |st: &mut TestState<_, _, _>, amount: Zatoshis| {
11696        let request =
11697            TransactionRequest::new(vec![Payment::without_memo(recipient.clone(), amount)])
11698                .unwrap();
11699        st.propose_transfer(
11700            account.id(),
11701            &input_selector,
11702            &change_strategy,
11703            request,
11704            ConfirmationsPolicy::MIN,
11705        )
11706    };
11707
11708    // The canonical payment takes the single-note shape, spending the LARGE note.
11709    let canonical = propose(&mut st, MAX_RESIDUAL_VALUE).expect("the wallet can fund this");
11710    let step = canonical.steps().first();
11711    let zip318 = st.wallet().pool_migration_params(st.network());
11712    let canonical_fee = crate::fees::canonical_crossing_fee(
11713        st.network(),
11714        BlockHeight::from(canonical.min_target_height()),
11715    )
11716    .expect("the canonical shape is a valid input to the ZIP 317 rule");
11717    assert_eq!(
11718        step.input_count_in_pool(PoolType::ORCHARD),
11719        1,
11720        "the canonical payment must be funded from a single note"
11721    );
11722    assert!(step.is_canonical_crossing(&zip318, canonical_fee));
11723    let spent = step
11724        .shielded_inputs()
11725        .expect("a shielded step spends notes")
11726        .notes()
11727        .first()
11728        .note()
11729        .value();
11730    assert_eq!(
11731        spent, large_value,
11732        "the single covering note funds the payment, not the older small notes"
11733    );
11734
11735    // An ordinary payment of a NON-canonical amount still accumulates the oldest notes.
11736    let ordinary = propose(
11737        &mut st,
11738        (MAX_RESIDUAL_VALUE + Zatoshis::const_from_u64(1)).unwrap(),
11739    )
11740    .expect("the wallet can fund this too");
11741    let step = ordinary.steps().first();
11742    assert!(
11743        step.input_count_in_pool(PoolType::ORCHARD) > 1,
11744        "single-note preference must not leak into ordinary selection"
11745    );
11746}
11747
11748/// A canonical payment whose bucketed anchor checkpoint is MISSING from the wallet falls back to
11749/// an ordinary crossing instead of failing at build time.
11750///
11751/// A wallet that scanned past NU6.3 activation before boundary checkpointing was repaired is
11752/// permanently missing the grid boundaries whose blocks carried no shielded outputs, and the
11753/// holes cannot be backfilled from local state: the tree prunes node data that no retained
11754/// checkpoint references, so reconstruction would require refetching subtree data from a light
11755/// wallet server. Note eligibility at the bucketed anchor is a height comparison, so without a
11756/// checkpoint-existence gate the canonical proposal is kept and the BUILD fails with
11757/// `ProposalError::AnchorNotFound` — a hard send failure where every other miss in the canonical
11758/// path degrades gracefully.
11759///
11760/// `remove_checkpoint` deletes the wallet's checkpoint records at the given height, simulating
11761/// the legacy wallet state; it is supplied by the backend-specific caller because corrupting
11762/// stored state is necessarily a backend-level operation.
11763#[cfg(feature = "orchard")]
11764pub fn canonical_crossing_abandoned_without_anchor_checkpoint<Dsf, TC>(
11765    ds_factory: Dsf,
11766    cache: TC,
11767    remove_checkpoint: impl FnOnce(&mut TestState<TC, Dsf::DataStore, LocalNetwork>, BlockHeight),
11768) where
11769    Dsf: DataStoreFactory,
11770    TC: TestCache,
11771{
11772    let interval = AnchorRetentionInterval::custom(NonZeroU32::new(12).expect("nonzero"));
11773    let activation = BlockHeight::from_u32(100_000);
11774    let network = LocalNetwork {
11775        nu6: Some(activation),
11776        nu6_1: Some(activation),
11777        nu6_2: Some(activation),
11778        nu6_3: Some(activation),
11779        ..TestBuilder::<(), ()>::DEFAULT_NETWORK
11780    };
11781
11782    let mut st = TestDsl::from(
11783        TestBuilder::new()
11784            .with_network(network)
11785            .with_data_store_factory(ds_factory)
11786            .with_block_cache(cache)
11787            .with_anchor_retention_interval(interval)
11788            .with_account_from_sapling_activation(BlockHash([0; 32])),
11789    )
11790    .build::<OrchardPoolTester>();
11791
11792    let account = st.test_account().cloned().unwrap();
11793    let fvk = OrchardPoolTester::test_account_fvk(&st);
11794    let recipient = OrchardPoolTester::fvk_default_address(&fvk).to_zcash_address(st.network());
11795
11796    // One Orchard note, comfortably larger than a canonical denomination plus fees, mined well
11797    // before the bucketed anchor.
11798    let (received_height, _, _) =
11799        st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(10_000_000));
11800    let received = u32::from(received_height);
11801    let interval_blocks = interval.block_count().get();
11802    let tip = u32::from(anchor_grid(st.network(), interval).boundary_at_or_above(received_height))
11803        + 3 * interval_blocks
11804        + 5;
11805    let not_our_fvk = OrchardPoolTester::sk_to_fvk(&OrchardPoolTester::sk(&[0xf5; 32]));
11806    let filler_count = tip - received;
11807    for _ in 0..filler_count {
11808        st.generate_next_block(
11809            &not_our_fvk,
11810            AddressType::DefaultExternal,
11811            Zatoshis::const_from_u64(10_000),
11812        );
11813    }
11814    st.scan_cached_blocks(received_height + 1, filler_count as usize);
11815
11816    let input_selector = GreedyInputSelector::new();
11817    let change_strategy =
11818        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
11819    let propose = |st: &mut TestState<_, _, _>| {
11820        let request = TransactionRequest::new(vec![Payment::without_memo(
11821            recipient.clone(),
11822            MAX_RESIDUAL_VALUE,
11823        )])
11824        .unwrap();
11825        st.propose_transfer(
11826            account.id(),
11827            &input_selector,
11828            &change_strategy,
11829            request,
11830            ConfirmationsPolicy::MIN,
11831        )
11832        .expect("the wallet can fund this")
11833    };
11834
11835    // With the checkpoint intact the payment is canonical; the anchor it binds is the boundary
11836    // whose checkpoint the second half of the test removes. Reading it off the proposal keeps
11837    // the test's idea of "the bucketed anchor" identical to production's, rather than
11838    // reimplementing the arithmetic.
11839    let canonical = propose(&mut st);
11840    let step = canonical.steps().first();
11841    let zip318 = st.wallet().pool_migration_params(st.network());
11842    let canonical_fee = crate::fees::canonical_crossing_fee(
11843        st.network(),
11844        BlockHeight::from(canonical.min_target_height()),
11845    )
11846    .expect("the canonical shape is a valid input to the ZIP 317 rule");
11847    assert!(step.is_canonical_crossing(&zip318, canonical_fee));
11848    let boundary = step
11849        .anchor_height()
11850        .expect("a shielded step binds an anchor");
11851    assert!(
11852        st.wallet()
11853            .anchor_computable(ShieldedPool::Orchard, boundary)
11854            .unwrap(),
11855        "an anchor is computable at the boundary before removal"
11856    );
11857
11858    // Simulate the legacy wallet: the boundary's checkpoint records are gone.
11859    remove_checkpoint(&mut st, boundary);
11860    assert!(
11861        !st.wallet()
11862            .anchor_computable(ShieldedPool::Orchard, boundary)
11863            .unwrap(),
11864        "no anchor is computable at the boundary after removal"
11865    );
11866
11867    // The payment now falls back to an ordinary crossing: proposed against the ordinary anchor,
11868    // padded, and — decisively — BUILDABLE. Without the gate the canonical proposal would be
11869    // kept and building would fail with `AnchorNotFound`.
11870    let fallback = propose(&mut st);
11871    let step = fallback.steps().first();
11872    assert!(
11873        !step.is_canonical_crossing(&zip318, canonical_fee),
11874        "the attempt must be abandoned when its anchor cannot be proved"
11875    );
11876    assert_ne!(
11877        step.anchor_height()
11878            .expect("a shielded step binds an anchor"),
11879        boundary,
11880        "the fallback anchors at the ordinary height, not the unprovable boundary"
11881    );
11882    st.create_proposed_expecting(&fallback, 1);
11883}
11884
11885/// Self-migration does not stall once the wallet holds Ironwood notes.
11886///
11887/// A user moving their own funds across the turnstile sends themselves canonical amounts
11888/// repeatedly. After the first crossing the wallet holds an Ironwood note, and the ordinary
11889/// selector — which prefers to avoid crossing pools — would fund the next Ironwood-destined
11890/// payment from Ironwood, crossing nothing and capping the total that can ever be migrated. The
11891/// canonical path selects from Orchard only, so each transfer keeps moving value across.
11892#[cfg(feature = "orchard")]
11893pub fn self_migration_keeps_spending_orchard<Dsf: DataStoreFactory>(
11894    ds_factory: Dsf,
11895    cache: impl TestCache,
11896) {
11897    let interval = AnchorBucketInterval::custom(NonZeroU32::new(12).expect("nonzero"));
11898    let activation = BlockHeight::from_u32(100_000);
11899    let network = LocalNetwork {
11900        nu6: Some(activation),
11901        nu6_1: Some(activation),
11902        nu6_2: Some(activation),
11903        nu6_3: Some(activation),
11904        ..TestBuilder::<(), ()>::DEFAULT_NETWORK
11905    };
11906
11907    let mut st = TestDsl::from(
11908        TestBuilder::new()
11909            .with_network(network)
11910            .with_data_store_factory(ds_factory)
11911            .with_block_cache(cache)
11912            .with_anchor_retention_interval(interval)
11913            .with_account_from_sapling_activation(BlockHash([0; 32])),
11914    )
11915    .build::<OrchardPoolTester>();
11916
11917    let account = st.test_account().cloned().unwrap();
11918    let fvk = OrchardPoolTester::test_account_fvk(&st);
11919    let recipient = OrchardPoolTester::fvk_default_address(&fvk).to_zcash_address(st.network());
11920
11921    let (received_height, _, _) =
11922        st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(10_000_000));
11923
11924    let interval_blocks = interval.block_count().get();
11925    let not_our_fvk = OrchardPoolTester::sk_to_fvk(&OrchardPoolTester::sk(&[0xf5; 32]));
11926    let advance = |st: &mut TestState<_, _, _>, from: BlockHeight, count: u32| {
11927        for _ in 0..count {
11928            st.generate_next_block(
11929                &not_our_fvk,
11930                AddressType::DefaultExternal,
11931                Zatoshis::const_from_u64(10_000),
11932            );
11933        }
11934        st.scan_cached_blocks(from, count as usize);
11935    };
11936
11937    let tip = u32::from(anchor_grid(st.network(), interval).boundary_at_or_above(received_height))
11938        + 3 * interval_blocks
11939        + 5;
11940    advance(
11941        &mut st,
11942        received_height + 1,
11943        tip - u32::from(received_height),
11944    );
11945
11946    let input_selector = GreedyInputSelector::new();
11947    let change_strategy =
11948        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
11949    let zip318 = st.wallet().pool_migration_params(st.network());
11950
11951    // First crossing: funded from the original Orchard note.
11952    let request = TransactionRequest::new(vec![Payment::without_memo(
11953        recipient.clone(),
11954        MAX_RESIDUAL_VALUE,
11955    )])
11956    .unwrap();
11957    let first = st
11958        .propose_transfer(
11959            account.id(),
11960            &input_selector,
11961            &change_strategy,
11962            request,
11963            ConfirmationsPolicy::MIN,
11964        )
11965        .expect("the wallet can fund the first crossing");
11966    let canonical_fee = crate::fees::canonical_crossing_fee(
11967        st.network(),
11968        BlockHeight::from(first.min_target_height()),
11969    )
11970    .expect("the canonical shape is a valid input to the ZIP 317 rule");
11971    assert!(
11972        first
11973            .steps()
11974            .first()
11975            .is_canonical_crossing(&zip318, canonical_fee)
11976    );
11977
11978    // Mine it, so the wallet now holds an Ironwood note alongside its Orchard change.
11979    let txids = st.create_proposed_expecting(&first, 1);
11980    let (mined_height, _) = st.generate_next_block_including(txids[0]);
11981    st.scan_cached_blocks(mined_height, 1);
11982
11983    // Advance past another boundary so a bucketed anchor is available for the second crossing.
11984    advance(&mut st, mined_height + 1, 2 * interval_blocks + 1);
11985
11986    // The precondition this test exists to exercise: the wallet really does hold an Ironwood note
11987    // now, so the assertion below that none is spent is not vacuously true.
11988    let summary = st
11989        .get_wallet_summary(ConfirmationsPolicy::MIN)
11990        .expect("the wallet is synced");
11991    let balances = summary
11992        .account_balances()
11993        .get(&account.id())
11994        .expect("the account is known");
11995    assert!(
11996        balances.ironwood_balance().total().is_positive(),
11997        "the first crossing must have left an Ironwood note for the selector to prefer"
11998    );
11999    assert!(
12000        balances.orchard_balance().total().is_positive(),
12001        "and Orchard change to fund the second crossing from"
12002    );
12003
12004    // Second crossing: the wallet now holds Ironwood, which the ordinary selector would prefer.
12005    let request =
12006        TransactionRequest::new(vec![Payment::without_memo(recipient, MAX_RESIDUAL_VALUE)])
12007            .unwrap();
12008    let second = st
12009        .propose_transfer(
12010            account.id(),
12011            &input_selector,
12012            &change_strategy,
12013            request,
12014            ConfirmationsPolicy::MIN,
12015        )
12016        .expect("the wallet can fund the second crossing");
12017
12018    let step = second.steps().first();
12019    assert_eq!(
12020        step.input_count_in_pool(PoolType::IRONWOOD),
12021        0,
12022        "the Ironwood note must be left alone, or self-migration stalls here"
12023    );
12024    assert_eq!(step.input_count_in_pool(PoolType::ORCHARD), 1);
12025    assert!(
12026        step.is_canonical_crossing(&zip318, canonical_fee),
12027        "the second crossing must still be canonical"
12028    );
12029}
12030
12031/// Tests that payment construction enforces the ZIP 316 Revision 2 address expiration
12032/// rules: a payment to an address whose expiry height conflicts with the transaction's
12033/// expiry height is refused, a payment to an address whose expiry time has passed is
12034/// refused (for any recipient of a multi-recipient transaction), and a payment to an
12035/// address with unexpired metadata succeeds.
12036pub fn create_to_address_respects_recipient_expiry<T: ShieldedPoolTester>(
12037    dsf: impl DataStoreFactory,
12038    cache: impl TestCache,
12039) {
12040    let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
12041
12042    // Add funds to the wallet: one note for each payment expected to succeed. The
12043    // payments expected to be refused are checked first, while every note is unspent.
12044    st.add_notes_checking_balance([
12045        [Zatoshis::const_from_u64(100_000)],
12046        [Zatoshis::const_from_u64(100_000)],
12047        [Zatoshis::const_from_u64(100_000)],
12048    ]);
12049
12050    let account = st.test_account().cloned().unwrap();
12051    let birthday = account.birthday().height();
12052    let chain_tip = st.wallet().chain_height().unwrap().unwrap();
12053
12054    // Construct recipient addresses carrying expiry metadata from the account's own
12055    // default address, so that every receiver is valid for the active pool set.
12056    let (default_addr, _) = account
12057        .usk()
12058        .to_unified_full_viewing_key()
12059        .default_address(UnifiedAddressRequest::AllAvailableKeys)
12060        .unwrap();
12061    let with_expiry = |expiry_height: Option<BlockHeight>, expiry_time: Option<u64>| {
12062        UnifiedAddress::from_receivers(
12063            #[cfg(feature = "orchard")]
12064            default_addr.orchard().copied(),
12065            default_addr.sapling().copied(),
12066            default_addr.transparent().copied(),
12067            expiry_height,
12068            expiry_time,
12069        )
12070        .expect("the default address has at least one receiver")
12071    };
12072
12073    let payment_value = Zatoshis::const_from_u64(20_000);
12074    let change_strategy =
12075        single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
12076    let input_selector = GreedyInputSelector::new();
12077
12078    // An address is expired only once the chain has advanced *past* its expiry height,
12079    // so one expiring at exactly the chain tip is not yet expired. It is refused because
12080    // the transaction's default expiry height lies beyond it.
12081    let expired_by_height = with_expiry(Some(chain_tip), None);
12082    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
12083        Address::from(expired_by_height.clone()).to_zcash_address(st.network()),
12084        payment_value,
12085    )])
12086    .unwrap();
12087    let proposal = st
12088        .propose_transfer(
12089            account.id(),
12090            &input_selector,
12091            &change_strategy,
12092            request,
12093            ConfirmationsPolicy::MIN,
12094        )
12095        .unwrap();
12096    assert_matches!(
12097        st.create_proposed_transactions::<Infallible, _, Infallible, _>(
12098            account.usk(),
12099            OvkPolicy::Sender,
12100            &proposal
12101        ),
12102        Err(Error::RecipientAddressExpiry {
12103            payment_index: 0,
12104            error: AddressExpiryError::ExpiryHeightConflict { .. },
12105        })
12106    );
12107
12108    // An expiry time before the current time makes the address expired; the constraint
12109    // applies to every recipient of a multi-recipient transaction.
12110    /// One second past the Unix epoch, long before the test clock's current time.
12111    const EXPIRY_TIME_IN_PAST: u64 = 1;
12112    let valid_far_future = with_expiry(
12113        Some(birthday + 10_000),
12114        Some(super::TEST_CLOCK_EPOCH_OFFSET.as_secs() + 10_000),
12115    );
12116    let expired_by_time = with_expiry(None, Some(EXPIRY_TIME_IN_PAST));
12117    let request = zip321::TransactionRequest::new(vec![
12118        Payment::without_memo(
12119            Address::from(valid_far_future.clone()).to_zcash_address(st.network()),
12120            payment_value,
12121        ),
12122        Payment::without_memo(
12123            Address::from(expired_by_time.clone()).to_zcash_address(st.network()),
12124            payment_value,
12125        ),
12126    ])
12127    .unwrap();
12128    let proposal = st
12129        .propose_transfer(
12130            account.id(),
12131            &input_selector,
12132            &change_strategy,
12133            request,
12134            ConfirmationsPolicy::MIN,
12135        )
12136        .unwrap();
12137    assert_matches!(
12138        st.create_proposed_transactions::<Infallible, _, Infallible, _>(
12139            account.usk(),
12140            OvkPolicy::Sender,
12141            &proposal
12142        ),
12143        Err(Error::RecipientAddressExpiry {
12144            payment_index: 1,
12145            error: AddressExpiryError::TimeExpired { .. },
12146        })
12147    );
12148
12149    // A payment to an address with unexpired metadata succeeds.
12150    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
12151        Address::from(valid_far_future.clone()).to_zcash_address(st.network()),
12152        payment_value,
12153    )])
12154    .unwrap();
12155    let proposal = st
12156        .propose_transfer(
12157            account.id(),
12158            &input_selector,
12159            &change_strategy,
12160            request,
12161            ConfirmationsPolicy::MIN,
12162        )
12163        .unwrap();
12164    assert_matches!(
12165        st.create_proposed_transactions::<Infallible, _, Infallible, _>(
12166            account.usk(),
12167            OvkPolicy::Sender,
12168            &proposal
12169        ),
12170        Ok(_)
12171    );
12172
12173    // One block below the tip, the chain has advanced past the address's expiry height, so
12174    // the address is expired and the payment is refused on that ground rather than for a
12175    // transaction-expiry conflict.
12176    let recipient = with_expiry(Some(chain_tip - 1), None);
12177    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
12178        Address::from(recipient).to_zcash_address(st.network()),
12179        payment_value,
12180    )])
12181    .unwrap();
12182    let proposal = st
12183        .propose_transfer(
12184            account.id(),
12185            &input_selector,
12186            &change_strategy,
12187            request,
12188            ConfirmationsPolicy::MIN,
12189        )
12190        .unwrap();
12191    assert_matches!(
12192        st.create_proposed_transactions::<Infallible, _, Infallible, _>(
12193            account.usk(),
12194            OvkPolicy::Sender,
12195            &proposal
12196        ),
12197        Err(Error::RecipientAddressExpiry {
12198            payment_index: 0,
12199            error: AddressExpiryError::HeightExpired { .. },
12200        })
12201    );
12202
12203    // The transaction's expiry height may equal the address's expiry height; only a
12204    // transaction expiry strictly greater than the address's is forbidden. The default
12205    // transaction expiry is the target height plus the default expiry delta for the
12206    // consensus branch in effect there, and the target height is the block after the chain tip.
12207    let target_height = chain_tip + 1;
12208    let default_expiry_height =
12209        target_height + default_tx_expiry_delta(BranchId::for_height(st.network(), target_height));
12210    let recipient = with_expiry(Some(default_expiry_height), None);
12211    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
12212        Address::from(recipient).to_zcash_address(st.network()),
12213        payment_value,
12214    )])
12215    .unwrap();
12216    let proposal = st
12217        .propose_transfer(
12218            account.id(),
12219            &input_selector,
12220            &change_strategy,
12221            request,
12222            ConfirmationsPolicy::MIN,
12223        )
12224        .unwrap();
12225    assert_matches!(
12226        st.create_proposed_transactions::<Infallible, _, Infallible, _>(
12227            account.usk(),
12228            OvkPolicy::Sender,
12229            &proposal
12230        ),
12231        Ok(_)
12232    );
12233
12234    // An address carrying only an expiry time is expired only once the current time is
12235    // *after* it, so one expiring at exactly the current time is still valid.
12236    let recipient = with_expiry(None, Some(super::TEST_CLOCK_EPOCH_OFFSET.as_secs()));
12237    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
12238        Address::from(recipient).to_zcash_address(st.network()),
12239        payment_value,
12240    )])
12241    .unwrap();
12242    let proposal = st
12243        .propose_transfer(
12244            account.id(),
12245            &input_selector,
12246            &change_strategy,
12247            request,
12248            ConfirmationsPolicy::MIN,
12249        )
12250        .unwrap();
12251    assert_matches!(
12252        st.create_proposed_transactions::<Infallible, _, Infallible, _>(
12253            account.usk(),
12254            OvkPolicy::Sender,
12255            &proposal
12256        ),
12257        Ok(_)
12258    );
12259}
12260
12261/// The number of blocks between Sapling activation and NU7 activation on the network used by the
12262/// NU7 default-expiry tests. It leaves room for the funding blocks below NU7 activation.
12263const NU7_ACTIVATION_OFFSET: u32 = 10;
12264
12265/// Returns a test network on which every upgrade through NU6.3 activates at Sapling activation,
12266/// and NU7 activates [`NU7_ACTIVATION_OFFSET`] blocks later. On a regtest network the fee
12267/// reduction of [ZIP 2009] takes effect at the NU7 activation height.
12268///
12269/// [ZIP 2009]: https://zips.z.cash/zip-2009
12270pub(crate) fn nu7_activating_network() -> LocalNetwork {
12271    let activation = TestBuilder::<(), ()>::DEFAULT_NETWORK
12272        .sapling
12273        .expect("the default test network activates Sapling");
12274    LocalNetwork {
12275        nu6: Some(activation),
12276        nu6_1: Some(activation),
12277        nu6_2: Some(activation),
12278        nu6_3: Some(activation),
12279        nu7: Some(activation + NU7_ACTIVATION_OFFSET),
12280        ..TestBuilder::<(), ()>::DEFAULT_NETWORK
12281    }
12282}
12283
12284/// Builds a wallet on [`nu7_activating_network`] that holds two spendable notes, with its chain
12285/// tip two blocks below NU7 activation. The next transaction then targets the block before
12286/// activation.
12287fn nu7_default_expiry_scenario<T: ShieldedPoolTester, Cache: TestCache, Dsf: DataStoreFactory>(
12288    dsf: Dsf,
12289    cache: Cache,
12290) -> (TestDsl<TestScenario<T, Cache, Dsf>>, BlockHeight) {
12291    let network = nu7_activating_network();
12292    let nu7_activation = network
12293        .activation_height(NetworkUpgrade::Nu7)
12294        .expect("the test network activates NU7");
12295    let mut st = TestDsl::from(
12296        TestBuilder::new()
12297            .with_network(network)
12298            .with_data_store_factory(dsf)
12299            .with_block_cache(cache)
12300            .with_account_from_sapling_activation(BlockHash([0; 32])),
12301    )
12302    .build::<T>();
12303
12304    st.add_notes_checking_balance([
12305        [Zatoshis::const_from_u64(100_000)],
12306        [Zatoshis::const_from_u64(100_000)],
12307    ]);
12308    let tip = st.wallet().chain_height().unwrap().unwrap();
12309    let blocks_to_add = u32::from(nu7_activation) - 2 - u32::from(tip);
12310    st.add_empty_blocks(usize::try_from(blocks_to_add).expect("block count fits in a usize"));
12311    (st, nu7_activation)
12312}
12313
12314/// Tests that a transaction that the wallet creates with no explicit expiry height expires after
12315/// the default expiry delta for its target height: 40 blocks before NU7 activation, and 120 blocks
12316/// from NU7 activation onward.
12317pub fn create_proposed_transactions_uses_nu7_default_expiry<T: ShieldedPoolTester>(
12318    dsf: impl DataStoreFactory,
12319    cache: impl TestCache,
12320) {
12321    let (mut st, nu7_activation) = nu7_default_expiry_scenario::<T, _, _>(dsf, cache);
12322    let recipient = T::fvk_default_address(&T::sk_to_fvk(&T::sk(&[0xf5; 32])));
12323    let payment_value = Zatoshis::const_from_u64(20_000);
12324
12325    for (expected_target_height, expected_delta) in [
12326        (nu7_activation - 1, BLOSSOM_DEFAULT_TX_EXPIRY_DELTA),
12327        (nu7_activation, NU7_DEFAULT_TX_EXPIRY_DELTA),
12328    ] {
12329        let proposal = st.propose_transfer_to(&recipient, payment_value);
12330        let target_height = BlockHeight::from(proposal.min_target_height());
12331        assert_eq!(target_height, expected_target_height);
12332
12333        let txids = st.create_proposed_expecting(&proposal, 1);
12334        let tx = st
12335            .wallet()
12336            .get_transaction(txids[0])
12337            .unwrap()
12338            .expect("the created transaction is stored");
12339        assert_eq!(
12340            tx.expiry_height(),
12341            target_height + expected_delta,
12342            "default expiry height for target height {target_height}",
12343        );
12344
12345        st.add_empty_blocks(1);
12346    }
12347}
12348
12349/// Tests that a PCZT that the wallet creates with no explicit expiry height expires after the
12350/// default expiry delta for its target height: 40 blocks before NU7 activation, and 120 blocks
12351/// from NU7 activation onward.
12352///
12353/// The test network's heights lie in the ZIP 212 grace period, in which the wallet cannot create a
12354/// PCZT with Sapling outputs. `T` must therefore not be the Sapling pool.
12355#[cfg(feature = "pczt")]
12356pub fn create_pczt_uses_nu7_default_expiry<T: ShieldedPoolTester, Dsf>(
12357    dsf: Dsf,
12358    cache: impl TestCache,
12359) where
12360    Dsf: DataStoreFactory,
12361    <Dsf as DataStoreFactory>::AccountId: serde::Serialize + serde::de::DeserializeOwned,
12362{
12363    let (mut st, nu7_activation) = nu7_default_expiry_scenario::<T, _, _>(dsf, cache);
12364    let account_id = st.get_account().id();
12365    let recipient = T::fvk_default_address(&T::sk_to_fvk(&T::sk(&[0xf5; 32])));
12366    let payment_value = Zatoshis::const_from_u64(20_000);
12367
12368    for (expected_target_height, expected_delta) in [
12369        (nu7_activation - 1, BLOSSOM_DEFAULT_TX_EXPIRY_DELTA),
12370        (nu7_activation, NU7_DEFAULT_TX_EXPIRY_DELTA),
12371    ] {
12372        let proposal = st.propose_transfer_to(&recipient, payment_value);
12373        let target_height = BlockHeight::from(proposal.min_target_height());
12374        assert_eq!(target_height, expected_target_height);
12375
12376        let pczt = st
12377            .create_pczt_from_proposal::<Infallible, _, Infallible>(
12378                account_id,
12379                OvkPolicy::Sender,
12380                &proposal,
12381                None,
12382            )
12383            .unwrap();
12384        assert_eq!(
12385            *pczt.global().expiry_height(),
12386            u32::from(target_height + expected_delta),
12387            "default expiry height for target height {target_height}",
12388        );
12389
12390        st.add_empty_blocks(1);
12391    }
12392}
12393
12394/// A proposal's fee is the ZIP 317 fee in effect at its target height, and the transaction built
12395/// from it pays that fee even when the chain crosses the fee reduction height of [ZIP 2009]
12396/// between proposal and build; a proposal made from that height onward pays the reduced fee.
12397///
12398/// [ZIP 2009]: https://zips.z.cash/zip-2009
12399pub fn proposal_fee_is_fixed_at_its_target_height_across_fee_reduction<T: ShieldedPoolTester>(
12400    dsf: impl DataStoreFactory,
12401    cache: impl TestCache,
12402) {
12403    let (mut st, nu7_activation) = nu7_default_expiry_scenario::<T, _, _>(dsf, cache);
12404    // On a regtest network the fee reduction takes effect at NU7 activation.
12405    let reduction_height = nu7_activation;
12406    let recipient = T::fvk_default_address(&T::sk_to_fvk(&T::sk(&[0xf5; 32])));
12407    let payment_value = Zatoshis::const_from_u64(20_000);
12408
12409    // Proposed with the block before the reduction as its target: a whole number of the marginal
12410    // fees in effect there. The number of logical actions charged depends on the pool's bundle
12411    // shape, so it is read from this proposal; the proposal made after the reduction below has
12412    // the same shape (one input, the payment and change).
12413    let proposal = st.propose_transfer_to(&recipient, payment_value);
12414    let target_height = BlockHeight::from(proposal.min_target_height());
12415    assert_eq!(target_height, reduction_height - 1);
12416    let pre_reduction_fee = proposal.steps().first().balance().fee_required();
12417    let logical_actions =
12418        u64::from(pre_reduction_fee) / u64::from(marginal_fee(st.network(), target_height));
12419    assert_eq!(
12420        (marginal_fee(st.network(), target_height) * logical_actions).unwrap(),
12421        pre_reduction_fee
12422    );
12423
12424    // The chain crosses the reduction height before the proposal is built. The built transaction
12425    // pays the fee the proposal was priced at, not the fee in effect at the new tip.
12426    let tip = st.add_empty_blocks(2);
12427    assert!(tip >= reduction_height);
12428    let txids = st.create_proposed_expecting(&proposal, 1);
12429    let tx = st
12430        .get_tx_from_history(txids[0])
12431        .unwrap()
12432        .expect("the built transaction is in the history");
12433    assert_eq!(tx.fee_paid(), Some(pre_reduction_fee));
12434
12435    // A proposal of the same shape made from the reduction height onward charges the same
12436    // logical actions at the reduced marginal fee.
12437    let proposal = st.propose_transfer_to(&recipient, payment_value);
12438    let target_height = BlockHeight::from(proposal.min_target_height());
12439    assert!(target_height >= reduction_height);
12440    let reduced_fee = proposal.steps().first().balance().fee_required();
12441    assert_eq!(
12442        reduced_fee,
12443        (marginal_fee(st.network(), target_height) * logical_actions).unwrap()
12444    );
12445    assert!(reduced_fee < pre_reduction_fee);
12446}
12447
12448/// The wallet classifies a note as uneconomic by the ZIP 317 marginal fee in effect at the target
12449/// height: a note worth the marginal fee before the fee reduction height of [ZIP 2009] is reported
12450/// as uneconomic and left out of selection and proposals while the target height is below that
12451/// height, and is spendable and selected from it.
12452///
12453/// [ZIP 2009]: https://zips.z.cash/zip-2009
12454pub fn dust_threshold_follows_marginal_fee_at_target_height<T, Dsf>(dsf: Dsf, cache: impl TestCache)
12455where
12456    T: ShieldedPoolTester,
12457    Dsf: DataStoreFactory,
12458{
12459    let network = nu7_activating_network();
12460    // On a regtest network the fee reduction takes effect at NU7 activation.
12461    let reduction_height = network
12462        .activation_height(NetworkUpgrade::Nu7)
12463        .expect("the test network activates NU7");
12464    let mut st = TestDsl::from(
12465        TestBuilder::new()
12466            .with_network(network)
12467            .with_data_store_factory(dsf)
12468            .with_block_cache(cache)
12469            .with_account_from_sapling_activation(BlockHash([0; 32])),
12470    )
12471    .build::<T>();
12472    let account_id = st.get_account().id();
12473    let recipient = T::fvk_default_address(&T::sk_to_fvk(&T::sk(&[0xf5; 32])));
12474    let policy = ConfirmationsPolicy::MIN;
12475
12476    // A note worth one coin, then a note worth exactly the marginal fee before the reduction: at
12477    // the threshold there, and above the reduced one. It is received second, so that accumulation
12478    // draws on the large note first and reaches it only when the large note does not suffice.
12479    let large_value = Zatoshis::const_from_u64(COIN);
12480    let small_value = marginal_fee(st.network(), reduction_height - 1);
12481    assert!(small_value > marginal_fee(st.network(), reduction_height));
12482    st.add_notes_checking_balance([[large_value], [small_value]]);
12483
12484    // The summary buckets and both selection paths (every spendable note, and accumulation
12485    // towards a value) at the target height of a transaction built at the current tip.
12486    macro_rules! assert_classified {
12487        ($uneconomic:expr, $spendable:expr) => {{
12488            let tip = st
12489                .wallet()
12490                .chain_height()
12491                .unwrap()
12492                .expect("the chain tip is known");
12493            let target_height = TargetHeight::from(tip + 1);
12494            let balance = st
12495                .get_account_balance(policy)
12496                .expect("the wallet has scanned blocks");
12497            assert_eq!(balance.uneconomic_value(), $uneconomic);
12498            assert_eq!(balance.spendable_value(), $spendable);
12499            for target_value in [
12500                TargetValue::AllFunds(MaxSpendMode::MaxSpendable),
12501                TargetValue::AtLeast(Zatoshis::const_from_u64(MAX_MONEY)),
12502            ] {
12503                let selected = T::select_spendable_notes(
12504                    &st,
12505                    account_id,
12506                    target_value,
12507                    target_height,
12508                    policy,
12509                    &[],
12510                )
12511                .unwrap()
12512                .iter()
12513                .map(|note| T::note_value(note.note()))
12514                .try_fold(Zatoshis::ZERO, |sum, value| sum + value)
12515                .expect("the selected value is in range");
12516                assert_eq!(
12517                    selected, $spendable,
12518                    "{target_value:?} at {target_height:?}"
12519                );
12520            }
12521        }};
12522    }
12523
12524    // Advance the tip to two blocks below the reduction, so that the next transaction targets the
12525    // block before it.
12526    let tip = st
12527        .wallet()
12528        .chain_height()
12529        .unwrap()
12530        .expect("the chain tip is known");
12531    let blocks_to_add = u32::from(reduction_height) - 2 - u32::from(tip);
12532    let tip =
12533        st.add_empty_blocks(usize::try_from(blocks_to_add).expect("block count fits in a usize"));
12534    assert_eq!(tip, reduction_height - 2);
12535
12536    // Below the reduction, the small note is uneconomic: a payment of the large note's whole
12537    // value, whose fee only the small note could cover, cannot be funded.
12538    assert_classified!(small_value, large_value);
12539    assert_matches!(
12540        st.propose_standard_transfer::<Infallible>(
12541            account_id,
12542            StandardFeeRule::Zip317,
12543            policy,
12544            &recipient,
12545            large_value,
12546            None,
12547            None,
12548            T::SHIELDED_PROTOCOL,
12549        ),
12550        Err(Error::InsufficientFunds { available, .. }) if available == large_value
12551    );
12552
12553    // From the reduction height, the small note is spendable, and that payment spends both notes.
12554    st.add_empty_blocks(1);
12555    assert_classified!(Zatoshis::ZERO, (large_value + small_value).unwrap());
12556    let proposal = st.propose_transfer_to(&recipient, large_value);
12557    assert_eq!(
12558        BlockHeight::from(proposal.min_target_height()),
12559        reduction_height
12560    );
12561    let mut input_values = proposal
12562        .steps()
12563        .first()
12564        .shielded_inputs()
12565        .expect("the payment is funded from shielded notes")
12566        .notes()
12567        .iter()
12568        .map(|note| note.note().value())
12569        .collect::<Vec<_>>();
12570    input_values.sort();
12571    assert_eq!(input_values, vec![small_value, large_value]);
12572}
12573
12574/// A canonical ZIP 318 crossing pays the canonical fee in effect at its target height
12575/// ([`fees::canonical_crossing_fee`]): the fee before the fee reduction height of [ZIP 2009]
12576/// when it targets the block before it, even if built after the chain has crossed it, and the
12577/// reduced fee from it.
12578///
12579/// [ZIP 2009]: https://zips.z.cash/zip-2009
12580#[cfg(feature = "orchard")]
12581pub fn canonical_crossing_fee_follows_marginal_fee_at_target_height<Dsf: DataStoreFactory>(
12582    ds_factory: Dsf,
12583    cache: impl TestCache,
12584) {
12585    // A short grid, so the test need not mine 144 blocks to cross a boundary.
12586    let interval = AnchorBucketInterval::custom(NonZeroU32::new(12).expect("nonzero"));
12587    /// One block per Orchard funding note.
12588    const FUNDING_BLOCKS: u32 = 2;
12589    let nu5_activation = TestBuilder::<(), ()>::DEFAULT_NETWORK
12590        .nu5
12591        .expect("the default test network activates NU5");
12592    let ironwood_activation = nu5_activation + FUNDING_BLOCKS;
12593    let ironwood_active_network = LocalNetwork {
12594        nu6: Some(nu5_activation),
12595        nu6_1: Some(nu5_activation),
12596        nu6_2: Some(nu5_activation),
12597        nu6_3: Some(ironwood_activation),
12598        ..TestBuilder::<(), ()>::DEFAULT_NETWORK
12599    };
12600
12601    // The Orchard funding notes are received from NU5 activation until NU6.2, before NU6.3
12602    // activates Ironwood, and the tip is then set well past the next grid boundary and deliberately OFF a boundary, as in
12603    // `canonical_crossing_is_bucketed_and_unpadded`, so that a bucketed anchor exists. The grid
12604    // is uniform below the fee reduction height, so it can be computed before that height is
12605    // chosen: two blocks above this tip, so that the first proposal targets the block before it.
12606    // On a regtest network the fee reduction height is the NU7 activation height.
12607    let interval_blocks = interval.block_count().get();
12608    let pre_reduction_tip = anchor_grid(&ironwood_active_network, interval)
12609        .boundary_at_or_above(ironwood_activation)
12610        + (3 * interval_blocks + 5);
12611    let reduction_height = pre_reduction_tip + 2;
12612    let network = LocalNetwork {
12613        nu7: Some(reduction_height),
12614        ..ironwood_active_network
12615    };
12616
12617    let mut st = TestDsl::from(
12618        TestBuilder::new()
12619            .with_network(network)
12620            .with_data_store_factory(ds_factory)
12621            .with_block_cache(cache)
12622            .with_anchor_retention_interval(interval)
12623            .with_account_from_sapling_activation(BlockHash([0; 32])),
12624    )
12625    .build::<OrchardPoolTester>();
12626
12627    let account = st.test_account().cloned().unwrap();
12628    let fvk = OrchardPoolTester::test_account_fvk(&st);
12629    let recipient = OrchardPoolTester::fvk_default_address(&fvk).to_zcash_address(st.network());
12630    let zip318 = st.wallet().pool_migration_params(st.network());
12631
12632    let pre_reduction_fee = fees::canonical_crossing_fee(st.network(), reduction_height - 1)
12633        .expect("the canonical shape is a valid input to the ZIP 317 rule");
12634    let reduced_fee = fees::canonical_crossing_fee(st.network(), reduction_height)
12635        .expect("the canonical shape is a valid input to the ZIP 317 rule");
12636    assert!(reduced_fee < pre_reduction_fee);
12637
12638    // Two notes comfortably larger than a canonical denomination plus fees, one per crossing.
12639    let note_value = Zatoshis::const_from_u64(10_000_000);
12640    let funded = st.add_notes_checking_balance([[note_value], [note_value]]);
12641    assert_eq!(funded.first_block_height(), Some(nu5_activation));
12642    let funded_height = funded.block_height().expect("blocks were added");
12643    assert!(funded_height < ironwood_activation);
12644
12645    // Fillers pay a non-wallet key, so each block adds a commitment (and thus a checkpoint)
12646    // without changing the wallet's spendable set.
12647    let not_our_fvk = OrchardPoolTester::sk_to_fvk(&OrchardPoolTester::sk(&[0xf5; 32]));
12648    let filler_count = u32::from(pre_reduction_tip) - u32::from(funded_height);
12649    for _ in 0..filler_count {
12650        st.generate_next_block(
12651            &not_our_fvk,
12652            AddressType::DefaultExternal,
12653            Zatoshis::const_from_u64(10_000),
12654        );
12655    }
12656    st.scan_cached_blocks(funded_height + 1, filler_count as usize);
12657    assert_eq!(st.wallet().chain_height().unwrap(), Some(pre_reduction_tip));
12658
12659    let input_selector = GreedyInputSelector::new();
12660    let change_strategy =
12661        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
12662    let propose = |st: &mut TestState<_, _, _>| {
12663        let request = TransactionRequest::new(vec![Payment::without_memo(
12664            recipient.clone(),
12665            MAX_RESIDUAL_VALUE,
12666        )])
12667        .unwrap();
12668        st.propose_transfer(
12669            account.id(),
12670            &input_selector,
12671            &change_strategy,
12672            request,
12673            ConfirmationsPolicy::MIN,
12674        )
12675        .expect("the wallet can fund this")
12676    };
12677    // The proposal is canonical at `$fee`, and the transaction built from it keeps the single
12678    // unpadded Ironwood action of the canonical shape and pays `$fee`.
12679    macro_rules! assert_canonical_built {
12680        ($proposal:expr, $fee:expr) => {{
12681            assert_eq!($proposal.steps().len(), 1);
12682            let step = $proposal.steps().first();
12683            assert_eq!(step.balance().fee_required(), $fee);
12684            assert!(
12685                step.is_canonical_crossing(&zip318, $fee),
12686                "the payment must be recognized as a canonical crossing"
12687            );
12688            let txids = st.create_proposed_expecting(&$proposal, 1);
12689            let built = st
12690                .wallet()
12691                .get_transaction(txids[0])
12692                .unwrap()
12693                .expect("the transaction was stored");
12694            assert_eq!(
12695                built
12696                    .ironwood_bundle()
12697                    .expect("a crossing carries an Ironwood bundle")
12698                    .actions()
12699                    .len(),
12700                1,
12701                "the BUILT Ironwood bundle must have the single action of the canonical shape"
12702            );
12703            let tx = st.get_tx_from_history(txids[0]).unwrap().unwrap();
12704            assert_eq!(tx.fee_paid(), Some($fee));
12705        }};
12706    }
12707
12708    // Targeting the block before the reduction: the canonical fee in effect there, kept by the
12709    // transaction built after the chain has crossed the reduction height.
12710    let pre_reduction_proposal = propose(&mut st);
12711    assert_eq!(
12712        BlockHeight::from(pre_reduction_proposal.min_target_height()),
12713        reduction_height - 1
12714    );
12715    let tip = st.add_empty_blocks(2);
12716    assert_eq!(tip, reduction_height);
12717    assert_canonical_built!(pre_reduction_proposal, pre_reduction_fee);
12718
12719    // Targeting a height from the reduction onward: the reduced canonical fee.
12720    let reduced_proposal = propose(&mut st);
12721    assert!(BlockHeight::from(reduced_proposal.min_target_height()) >= reduction_height);
12722    assert_canonical_built!(reduced_proposal, reduced_fee);
12723}
12724
12725/// A block downloaded for a height the wallet has already scanned, carrying a different hash,
12726/// is a chain reorg. Scanning must report it as a continuity error before any wallet state is
12727/// written, so that the sync loop rewinds, rather than surface it from the storage layer as a
12728/// conflict the loop cannot classify.
12729pub fn reorg_below_scanned_height_is_a_continuity_error<T, Dsf>(
12730    ds_factory: Dsf,
12731    cache: impl TestCache,
12732) where
12733    T: ShieldedPoolTester,
12734    Dsf: DataStoreFactory,
12735    <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
12736{
12737    use crate::data_api::chain::error::Error as ChainError;
12738
12739    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
12740    let (note_height, _, _) =
12741        st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(500_000));
12742    let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
12743    let filler_value = Zatoshis::const_from_u64(1000);
12744
12745    const SCANNED_BLOCKS: u32 = 10;
12746    for _ in 0..SCANNED_BLOCKS {
12747        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, filler_value);
12748    }
12749    st.scan_cached_blocks(note_height + 1, SCANNED_BLOCKS as usize);
12750    let scanned_tip = st
12751        .wallet()
12752        .chain_height()
12753        .unwrap()
12754        .expect("chain tip is known");
12755
12756    // Replace the three blocks above the fork with different ones, leaving the wallet's rows
12757    // for those heights in place.
12758    const REORG_DEPTH: u32 = 3;
12759    let fork_height = scanned_tip - REORG_DEPTH;
12760    st.truncate_cache_to_height(fork_height);
12761    for _ in 0..REORG_DEPTH {
12762        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, filler_value);
12763    }
12764    let stored_hash = st
12765        .wallet()
12766        .block_metadata(fork_height + 1)
12767        .unwrap()
12768        .expect("the block above the fork was scanned")
12769        .block_hash();
12770
12771    let result = st.try_scan_cached_blocks(fork_height + 1, REORG_DEPTH as usize);
12772    assert_matches!(
12773        result,
12774        Err(ChainError::Scan(ref err)) if err.is_continuity_error() && err.at_height() == fork_height + 1
12775    );
12776
12777    // Nothing was written: the recorded tip and the stored block are as before.
12778    assert_eq!(st.wallet().chain_height().unwrap(), Some(scanned_tip));
12779    assert_eq!(
12780        st.wallet()
12781            .block_metadata(fork_height + 1)
12782            .unwrap()
12783            .map(|meta| meta.block_hash()),
12784        Some(stored_hash),
12785    );
12786}