Skip to main content

zcash_client_backend/data_api/testing/
transparent.rs

1use std::{
2    collections::{BTreeMap, HashSet},
3    convert::Infallible,
4};
5
6use assert_matches::assert_matches;
7
8use nonempty::NonEmpty;
9use sapling::zip32::ExtendedSpendingKey;
10use subtle::ConditionallySelectable;
11use transparent::{
12    address::{Script, TransparentAddress},
13    bundle::{Authorized, Bundle, OutPoint, TxIn, TxOut},
14};
15use zcash_keys::{
16    address::Address,
17    keys::{
18        UnifiedAddressRequest,
19        transparent::{NonHardenedChildIndex, TransparentKeyScope, gap_limits::GapLimits},
20    },
21};
22use zcash_primitives::{
23    block::{Block, BlockHash, BlockHeaderData},
24    transaction::{
25        Transaction, TransactionData, TxVersion, builder::NU7_DEFAULT_TX_EXPIRY_DELTA, fees::zip317,
26    },
27};
28use zcash_protocol::{
29    consensus::{BlockHeight, BranchId, COINBASE_MATURITY_BLOCKS, NetworkUpgrade, Parameters},
30    local_consensus::LocalNetwork,
31    value::Zatoshis,
32};
33use zip321::{Payment, TransactionRequest};
34
35#[cfg(feature = "transparent-key-import")]
36use {
37    crate::{
38        data_api::{
39            AccountBirthday,
40            wallet::{self, SpendingKeys},
41        },
42        wallet::TransparentAddressSource,
43    },
44    rand::{rand_core::UnwrapErr, rngs::SysRng},
45    secp256k1::SecretKey,
46    secrecy::Secret,
47    std::collections::HashMap,
48    zcash_script::{descriptor::sh, pattern::check_multisig, script},
49};
50
51use super::TestAccount;
52use crate::{
53    data_api::{
54        Account as _, AccountBalance, Balance, BlockMetadata, CoinbaseFilter, InputSource as _,
55        MaxSpendMode, ScannedBlock, TargetValue, WalletRead, WalletTest as _, WalletWrite,
56        chain::ChainState,
57        testing::{
58            AddressType, DataStoreFactory, ShieldedPool, TestBuilder, TestCache, TestState,
59            single_output_change_strategy,
60        },
61        wallet::{
62            ConfirmationsPolicy, TargetHeight, decrypt_and_store_transaction,
63            input_selection::{
64                GreedyInputSelector, LockFilter, LockedInputPolicy, SpendPolicy,
65                TransparentSpendPolicy,
66            },
67        },
68    },
69    fees::{ChangeValue, StandardFeeRule, TransparentChangePolicy},
70    scanning::{
71        ScanningKeys, SpendIdentifiers,
72        full::{decrypt_block, scan_block},
73    },
74    wallet::{Exposure, OvkPolicy, WalletTransparentOutput},
75};
76
77pub use super::pool::locking::transparent_note_locking;
78
79/// Checks whether the transparent balance of the given test `account` is as `expected`
80/// considering the `confirmations_policy`.
81fn check_balance<DSF>(
82    st: &TestState<impl TestCache, <DSF as DataStoreFactory>::DataStore, LocalNetwork>,
83    account: &TestAccount<<DSF as DataStoreFactory>::Account>,
84    taddr: &TransparentAddress,
85    confirmations_policy: ConfirmationsPolicy,
86    expected: &Balance,
87) where
88    DSF: DataStoreFactory,
89{
90    // Check the wallet summary returns the expected transparent balance.
91    let summary = st
92        .wallet()
93        .get_wallet_summary(confirmations_policy)
94        .unwrap()
95        .unwrap();
96    let balance = summary.account_balances().get(&account.id()).unwrap();
97
98    #[allow(deprecated)]
99    let old_unshielded_value = balance.unshielded();
100    assert_eq!(old_unshielded_value, expected.total());
101    assert_eq!(balance.unshielded_regular_balance(), expected);
102    assert_eq!(balance.unshielded_coinbase_balance(), &Balance::ZERO);
103    assert_eq!(balance.unshielded_balance(), *expected);
104
105    // Check the older APIs for consistency.
106    let target_height = TargetHeight::from(st.wallet().chain_height().unwrap().unwrap() + 1);
107    assert_eq!(
108        st.wallet()
109            .get_transparent_balances(account.id(), target_height, confirmations_policy)
110            .unwrap()
111            .get(taddr)
112            .cloned()
113            .map_or(Zatoshis::ZERO, |(_, b)| b.spendable_value()),
114        expected.total(),
115    );
116    assert_eq!(
117        st.wallet()
118            .get_spendable_transparent_outputs(
119                taddr,
120                target_height,
121                confirmations_policy,
122                CoinbaseFilter::AllTransparentOutputs,
123                LockFilter::Policy(&LockedInputPolicy::Exclude),
124            )
125            .unwrap()
126            .into_iter()
127            .map(|utxo| utxo.value())
128            .sum::<Option<Zatoshis>>(),
129        Some(expected.spendable_value()),
130    );
131}
132
133pub fn put_received_transparent_utxo<DSF>(dsf: DSF)
134where
135    DSF: DataStoreFactory,
136    <<DSF as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug + PartialEq,
137{
138    let mut st = TestBuilder::new()
139        .with_data_store_factory(dsf)
140        .with_account_from_sapling_activation(BlockHash([0; 32]))
141        .build();
142
143    let birthday = st.test_account().unwrap().birthday().height();
144    let account_id = st.test_account().unwrap().id();
145    let uaddr = st
146        .wallet()
147        .get_last_generated_address_matching(account_id, UnifiedAddressRequest::AllAvailableKeys)
148        .unwrap()
149        .unwrap();
150    let taddr = uaddr.transparent().unwrap();
151
152    let height_1 = birthday + 12345;
153    st.wallet_mut().update_chain_tip(height_1).unwrap();
154
155    let bal_absent = st
156        .wallet()
157        .get_transparent_balances(
158            account_id,
159            TargetHeight::from(height_1 + 1),
160            ConfirmationsPolicy::MIN,
161        )
162        .unwrap();
163    assert!(bal_absent.is_empty());
164
165    // Create a fake transparent output.
166    let value = Zatoshis::const_from_u64(100000);
167    let outpoint = OutPoint::fake();
168    let txout = TxOut::new(value, taddr.script().into());
169
170    // Pretend the output's transaction was mined at `height_1`.
171    let utxo = WalletTransparentOutput::from_parts(
172        outpoint.clone(),
173        txout.clone(),
174        Some(height_1),
175        Some(account_id),
176        Some(TransparentKeyScope::EXTERNAL),
177        None,
178    )
179    .unwrap();
180    let res0 = st.wallet_mut().put_received_transparent_utxo(&utxo);
181    assert_matches!(res0, Ok(_));
182
183    let target_height = TargetHeight::from(height_1 + 1);
184    // Confirm that we see the output unspent as of `height_1`.
185    assert_matches!(
186        st.wallet().get_spendable_transparent_outputs(
187            taddr,
188            target_height,
189            ConfirmationsPolicy::MIN,
190            CoinbaseFilter::AllTransparentOutputs,
191            LockFilter::Policy(&LockedInputPolicy::Exclude),
192        ).as_deref(),
193        Ok([ret])
194        if (ret.outpoint(), ret.txout(), ret.mined_height()) == (utxo.outpoint(), utxo.txout(), Some(height_1))
195    );
196    assert_matches!(
197        st.wallet()
198            .get_unspent_transparent_output(utxo.outpoint(), target_height),
199        Ok(Some(ret))
200        if (ret.outpoint(), ret.txout(), ret.mined_height()) == (utxo.outpoint(), utxo.txout(), Some(height_1))
201    );
202
203    // Change the mined height of the UTXO and upsert; we should get back
204    // the same `UtxoId`.
205    let height_2 = birthday + 34567;
206    st.wallet_mut().update_chain_tip(height_2).unwrap();
207    let utxo2 = WalletTransparentOutput::from_parts(
208        outpoint,
209        txout,
210        Some(height_2),
211        Some(account_id),
212        Some(TransparentKeyScope::EXTERNAL),
213        None,
214    )
215    .unwrap();
216    let res1 = st.wallet_mut().put_received_transparent_utxo(&utxo2);
217    assert_matches!(res1, Ok(id) if id == res0.unwrap());
218
219    // Confirm that we no longer see any unspent outputs as of `height_1`.
220    assert_matches!(
221        st.wallet()
222            .get_spendable_transparent_outputs(
223                taddr,
224                target_height,
225                ConfirmationsPolicy::MIN,
226                CoinbaseFilter::AllTransparentOutputs,
227                LockFilter::Policy(&LockedInputPolicy::Exclude)
228            )
229            .as_deref(),
230        Ok(&[])
231    );
232
233    // We can still look up the specific output, and it has the expected height.
234    assert_matches!(
235        st.wallet()
236            .get_unspent_transparent_output(utxo2.outpoint(), target_height),
237        Ok(Some(ret))
238        if (ret.outpoint(), ret.txout(), ret.mined_height()) == (utxo2.outpoint(), utxo2.txout(), Some(height_2))
239    );
240
241    // If we include `height_2` then the output is returned.
242    assert_matches!(
243        st.wallet()
244            .get_spendable_transparent_outputs(taddr, TargetHeight::from(height_2 + 1), ConfirmationsPolicy::MIN, CoinbaseFilter::AllTransparentOutputs, LockFilter::Policy(&LockedInputPolicy::Exclude))
245            .as_deref(),
246        Ok([ret]) if (ret.outpoint(), ret.txout(), ret.mined_height()) == (utxo.outpoint(), utxo.txout(), Some(height_2))
247    );
248
249    assert_matches!(
250        st.wallet().get_transparent_balances(
251            account_id,
252            TargetHeight::from(height_2 + 1),
253            ConfirmationsPolicy::MIN
254        ),
255        Ok(h) if h.get(taddr).map(|(_, b)| b.spendable_value()) == Some(value)
256    );
257}
258
259/// Tests that an unmined UTXO received when the chain tip is one block below NU7 activation is
260/// assumed to expire after the default expiry delta for the mempool height, which is the NU7
261/// activation height.
262pub fn put_received_unmined_utxo_uses_mempool_height_expiry_delta<DSF>(dsf: DSF)
263where
264    DSF: DataStoreFactory,
265{
266    /// The number of blocks between Sapling activation and NU7 activation on the test network.
267    const NU7_ACTIVATION_OFFSET: u32 = 10;
268
269    let sapling_activation = TestBuilder::<(), ()>::DEFAULT_NETWORK
270        .sapling
271        .expect("the default test network activates Sapling");
272    let nu7_activation = sapling_activation + NU7_ACTIVATION_OFFSET;
273    let mut st = TestBuilder::new()
274        .with_network(LocalNetwork {
275            nu6: Some(sapling_activation),
276            nu6_1: Some(sapling_activation),
277            nu6_2: Some(sapling_activation),
278            nu6_3: Some(sapling_activation),
279            nu7: Some(nu7_activation),
280            ..TestBuilder::<(), ()>::DEFAULT_NETWORK
281        })
282        .with_data_store_factory(dsf)
283        .with_account_from_sapling_activation(BlockHash([0; 32]))
284        .build();
285
286    let account_id = st.test_account().unwrap().id();
287    let uaddr = st
288        .wallet()
289        .get_last_generated_address_matching(account_id, UnifiedAddressRequest::AllAvailableKeys)
290        .unwrap()
291        .unwrap();
292    let taddr = uaddr.transparent().unwrap();
293
294    st.wallet_mut()
295        .update_chain_tip(nu7_activation - 1)
296        .unwrap();
297
298    let outpoint = OutPoint::fake();
299    let utxo = WalletTransparentOutput::from_parts(
300        outpoint.clone(),
301        TxOut::new(Zatoshis::const_from_u64(100000), taddr.script().into()),
302        None,
303        Some(account_id),
304        Some(TransparentKeyScope::EXTERNAL),
305        None,
306    )
307    .unwrap();
308    st.wallet_mut()
309        .put_received_transparent_utxo(&utxo)
310        .unwrap();
311
312    // The output is unexpired at every target height up to the NU7 activation height plus the
313    // NU7 default expiry delta, and expired above it.
314    let last_unexpired_height = nu7_activation + NU7_DEFAULT_TX_EXPIRY_DELTA;
315    assert_matches!(
316        st.wallet()
317            .get_transparent_output(&outpoint, Some(TargetHeight::from(last_unexpired_height))),
318        Ok(Some(_))
319    );
320    assert_matches!(
321        st.wallet().get_transparent_output(
322            &outpoint,
323            Some(TargetHeight::from(last_unexpired_height + 1))
324        ),
325        Ok(None)
326    );
327}
328
329pub fn transparent_balance_across_shielding<DSF>(dsf: DSF, cache: impl TestCache)
330where
331    DSF: DataStoreFactory,
332{
333    let mut st = TestBuilder::new()
334        .with_data_store_factory(dsf)
335        .with_block_cache(cache)
336        .with_account_from_sapling_activation(BlockHash([0; 32]))
337        .build();
338
339    let account = st.test_account().cloned().unwrap();
340    let uaddr = st
341        .wallet()
342        .get_last_generated_address_matching(account.id(), UnifiedAddressRequest::AllAvailableKeys)
343        .unwrap()
344        .unwrap();
345    let taddr = uaddr.transparent().unwrap();
346
347    // Initialize the wallet with chain data that has no shielded notes for us.
348    let not_our_key = ExtendedSpendingKey::master(&[])
349        .expect("the derivation path yields a valid key")
350        .to_diversifiable_full_viewing_key();
351    let not_our_value = Zatoshis::const_from_u64(10000);
352    let (start_height, _, _) =
353        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
354    for _ in 1..10 {
355        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
356    }
357    st.scan_cached_blocks(start_height, 10);
358
359    // The wallet starts out with zero balance.
360    check_balance::<DSF>(
361        &st,
362        &account,
363        taddr,
364        ConfirmationsPolicy::MIN,
365        &Balance::ZERO,
366    );
367
368    // Create a fake transparent output.
369    let value = Zatoshis::from_u64(100000).unwrap();
370    let txout = TxOut::new(value, taddr.script().into());
371
372    // Pretend the output was received in the chain tip.
373    let height = st.wallet().chain_height().unwrap().unwrap();
374    let utxo = WalletTransparentOutput::from_parts(
375        OutPoint::fake(),
376        txout,
377        Some(height),
378        Some(account.id()),
379        Some(TransparentKeyScope::EXTERNAL),
380        None,
381    )
382    .unwrap();
383    st.wallet_mut()
384        .put_received_transparent_utxo(&utxo)
385        .unwrap();
386
387    // The wallet should detect the balance as available
388    let mut zero_or_one_conf_value = Balance::ZERO;
389
390    // add the spendable value to the expected balance
391    zero_or_one_conf_value.add_spendable_value(value).unwrap();
392
393    check_balance::<DSF>(
394        &st,
395        &account,
396        taddr,
397        ConfirmationsPolicy::MIN,
398        &zero_or_one_conf_value,
399    );
400
401    // Shield the output.
402    let input_selector = GreedyInputSelector::new();
403    let change_strategy =
404        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling);
405    let txid = st
406        .shield_transparent_funds(
407            &input_selector,
408            &change_strategy,
409            value,
410            account.usk(),
411            &[*taddr],
412            account.id(),
413            ConfirmationsPolicy::MIN,
414        )
415        .unwrap()[0];
416
417    // The wallet should have zero transparent balance, because the shielding
418    // transaction can be mined.
419    check_balance::<DSF>(
420        &st,
421        &account,
422        taddr,
423        ConfirmationsPolicy::MIN,
424        &Balance::ZERO,
425    );
426
427    // Mine the shielding transaction.
428    let (mined_height, _) = st.generate_next_block_including(txid);
429    st.scan_cached_blocks(mined_height, 1);
430
431    // The wallet should still have zero transparent balance.
432    check_balance::<DSF>(
433        &st,
434        &account,
435        taddr,
436        ConfirmationsPolicy::MIN,
437        &Balance::ZERO,
438    );
439
440    // Unmine the shielding transaction via a reorg.
441    st.wallet_mut()
442        .truncate_to_height(mined_height - 1)
443        .unwrap();
444    assert_eq!(st.wallet().chain_height().unwrap(), Some(mined_height - 1));
445
446    // The wallet should still have zero transparent balance.
447    check_balance::<DSF>(
448        &st,
449        &account,
450        taddr,
451        ConfirmationsPolicy::MIN,
452        &Balance::ZERO,
453    );
454
455    // Expire the shielding transaction.
456    let expiry_height = st
457        .wallet()
458        .get_transaction(txid)
459        .unwrap()
460        .expect("Transaction exists in the wallet.")
461        .expiry_height();
462    st.wallet_mut().update_chain_tip(expiry_height).unwrap();
463
464    check_balance::<DSF>(
465        &st,
466        &account,
467        taddr,
468        ConfirmationsPolicy::MIN,
469        &zero_or_one_conf_value,
470    );
471}
472
473/// Regression test for [PRO-291]: shielding a transparent balance composed of many P2PKH
474/// UTXOs must not fail with `ChangeRequired` due to fee disagreement between the proposal
475/// and builder layers.
476///
477/// At 150 P2PKH inputs the proposal-time fee computation (which uses
478/// `STANDARD_P2PKH = 150` bytes per input) starts to diverge from the builder-time
479/// fee computation (which historically used the actual serialized size, 149 bytes per
480/// input) due to the `ceildiv(t_in_total_size, 150)` term in the ZIP 317 fee formula.
481/// The discrepancy grows by one logical action (5000 zats) for every additional 150
482/// inputs.
483///
484/// [PRO-291]: https://linear.app/zodl/issue/PRO-291
485pub fn shielding_many_transparent_utxos<DSF>(dsf: DSF, cache: impl TestCache)
486where
487    DSF: DataStoreFactory,
488{
489    // Choose enough UTXOs to cross the first ceildiv(_, 150) boundary.
490    const NUM_UTXOS: usize = 160;
491    // Per-UTXO value comfortably above the marginal fee so none are treated as dust.
492    const PER_UTXO: u64 = 100_000;
493
494    let mut st = TestBuilder::new()
495        .with_data_store_factory(dsf)
496        .with_block_cache(cache)
497        .with_account_from_sapling_activation(BlockHash([0; 32]))
498        .build();
499
500    let account = st.test_account().cloned().unwrap();
501    let uaddr = st
502        .wallet()
503        .get_last_generated_address_matching(account.id(), UnifiedAddressRequest::AllAvailableKeys)
504        .unwrap()
505        .unwrap();
506    let taddr = uaddr.transparent().unwrap();
507
508    // Initialize the wallet with chain data that has no shielded notes for us.
509    let not_our_key = ExtendedSpendingKey::master(&[])
510        .expect("the derivation path yields a valid key")
511        .to_diversifiable_full_viewing_key();
512    let not_our_value = Zatoshis::const_from_u64(10_000);
513    let (start_height, _, _) =
514        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
515    for _ in 1..10 {
516        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
517    }
518    st.scan_cached_blocks(start_height, 10);
519
520    // Add many distinct P2PKH UTXOs to the wallet, all at the same transparent address.
521    let value = Zatoshis::const_from_u64(PER_UTXO);
522    let txout = TxOut::new(value, taddr.script().into());
523    let height = st.wallet().chain_height().unwrap().unwrap();
524    for i in 0..NUM_UTXOS {
525        let mut hash = [0u8; 32];
526        hash[..4].copy_from_slice(&(i as u32).to_le_bytes());
527        let outpoint = OutPoint::new(hash, 0);
528        let utxo = WalletTransparentOutput::from_parts(
529            outpoint,
530            txout.clone(),
531            Some(height),
532            Some(account.id()),
533            Some(TransparentKeyScope::EXTERNAL),
534            None,
535        )
536        .unwrap();
537        st.wallet_mut()
538            .put_received_transparent_utxo(&utxo)
539            .unwrap();
540    }
541
542    // Shield the transparent balance.
543    let input_selector = GreedyInputSelector::new();
544    let change_strategy =
545        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling);
546    let txids = st
547        .shield_transparent_funds(
548            &input_selector,
549            &change_strategy,
550            value,
551            account.usk(),
552            &[*taddr],
553            account.id(),
554            ConfirmationsPolicy::MIN,
555        )
556        .expect("shielding many P2PKH UTXOs should succeed");
557    assert_eq!(txids.len(), 1);
558
559    // After shielding, the transparent balance should be zero.
560    check_balance::<DSF>(
561        &st,
562        &account,
563        taddr,
564        ConfirmationsPolicy::MIN,
565        &Balance::ZERO,
566    );
567}
568
569/// Verifies that `InputSource::get_spendable_transparent_outputs_for_addresses` returns the
570/// spendable outputs for a *set* of addresses in a single call, equivalent to the union of
571/// per-address queries, and honours subset and empty requests.
572pub fn get_spendable_transparent_outputs_for_addresses<DSF>(dsf: DSF)
573where
574    DSF: DataStoreFactory,
575{
576    let mut st = TestBuilder::new()
577        .with_data_store_factory(dsf)
578        .with_account_from_sapling_activation(BlockHash([0; 32]))
579        .build();
580
581    let account_id = st.test_account().unwrap().id();
582    let birthday = st.test_account().unwrap().birthday().height();
583
584    let height_1 = birthday + 12345;
585    st.wallet_mut().update_chain_tip(height_1).unwrap();
586
587    // Obtain three distinct transparent receivers for the account.
588    let mut taddrs = Vec::new();
589    while taddrs.len() < 3 {
590        let (ua, _) = st
591            .wallet_mut()
592            .get_next_available_address(account_id, UnifiedAddressRequest::AllAvailableKeys)
593            .unwrap()
594            .expect("an address should be available within the gap limit");
595        if let Some(taddr) = ua.transparent() {
596            taddrs.push(*taddr);
597        }
598    }
599
600    // Place one distinct UTXO at each address.
601    let value = Zatoshis::const_from_u64(100_000);
602    for (i, taddr) in taddrs.iter().enumerate() {
603        let mut hash = [0u8; 32];
604        hash[..4].copy_from_slice(&(i as u32).to_le_bytes());
605        let utxo = WalletTransparentOutput::from_parts(
606            OutPoint::new(hash, 0),
607            TxOut::new(value, taddr.script().into()),
608            Some(height_1),
609            Some(account_id),
610            Some(TransparentKeyScope::EXTERNAL),
611            None,
612        )
613        .unwrap();
614        st.wallet_mut()
615            .put_received_transparent_utxo(&utxo)
616            .unwrap();
617    }
618
619    let target_height = TargetHeight::from(height_1 + 1);
620    let sorted = |mut v: Vec<TransparentAddress>| {
621        v.sort();
622        v
623    };
624
625    // The batched query over all three addresses returns one output per address.
626    let all = st
627        .wallet()
628        .get_spendable_transparent_outputs_for_addresses(
629            &taddrs,
630            target_height,
631            ConfirmationsPolicy::MIN,
632            CoinbaseFilter::AllTransparentOutputs,
633            LockFilter::Policy(&LockedInputPolicy::Exclude),
634        )
635        .unwrap();
636    assert_eq!(all.len(), 3);
637    assert_eq!(
638        sorted(all.iter().map(|u| *u.recipient_address()).collect()),
639        sorted(taddrs.clone()),
640    );
641
642    // It is equivalent to the union of per-address queries.
643    let mut per_address = Vec::new();
644    for taddr in &taddrs {
645        per_address.extend(
646            st.wallet()
647                .get_spendable_transparent_outputs(
648                    taddr,
649                    target_height,
650                    ConfirmationsPolicy::MIN,
651                    CoinbaseFilter::AllTransparentOutputs,
652                    LockFilter::Policy(&LockedInputPolicy::Exclude),
653                )
654                .unwrap(),
655        );
656    }
657    assert_eq!(
658        sorted(all.iter().map(|u| *u.recipient_address()).collect()),
659        sorted(per_address.iter().map(|u| *u.recipient_address()).collect()),
660    );
661
662    // A subset request returns only the requested address's output.
663    let subset = st
664        .wallet()
665        .get_spendable_transparent_outputs_for_addresses(
666            &taddrs[..1],
667            target_height,
668            ConfirmationsPolicy::MIN,
669            CoinbaseFilter::AllTransparentOutputs,
670            LockFilter::Policy(&LockedInputPolicy::Exclude),
671        )
672        .unwrap();
673    assert_eq!(subset.len(), 1);
674    assert_eq!(subset[0].recipient_address(), &taddrs[0]);
675
676    // An empty request returns no outputs.
677    assert!(
678        st.wallet()
679            .get_spendable_transparent_outputs_for_addresses(
680                &[],
681                target_height,
682                ConfirmationsPolicy::MIN,
683                CoinbaseFilter::AllTransparentOutputs,
684                LockFilter::Policy(&LockedInputPolicy::Exclude),
685            )
686            .unwrap()
687            .is_empty()
688    );
689}
690
691/// Verifies that a shielding proposal caps the number of transparent inputs in a single
692/// transaction to the selector's configured fraction of block space, selecting the highest-value
693/// UTXOs first and leaving the remainder unspent.
694pub fn shielding_transparent_input_cap<DSF>(dsf: DSF, cache: impl TestCache)
695where
696    DSF: DataStoreFactory,
697{
698    // At 1% of block space the cap is (2_000_000 * 1 / 100) / 150 = 133 inputs.
699    const BLOCK_SPACE_PERCENT: u32 = 1;
700    const CAP: usize = 133;
701    const NUM_UTXOS: usize = CAP + 7; // 140; the 7 smallest must be dropped.
702    const BASE: u64 = 100_000;
703    const STEP: u64 = 1_000;
704
705    let mut st = TestBuilder::new()
706        .with_data_store_factory(dsf)
707        .with_block_cache(cache)
708        .with_account_from_sapling_activation(BlockHash([0; 32]))
709        .build();
710
711    let account = st.test_account().cloned().unwrap();
712    let uaddr = st
713        .wallet()
714        .get_last_generated_address_matching(account.id(), UnifiedAddressRequest::AllAvailableKeys)
715        .unwrap()
716        .unwrap();
717    let taddr = uaddr.transparent().unwrap();
718
719    // Initialize the wallet with chain data that has no shielded notes for us.
720    let not_our_key = ExtendedSpendingKey::master(&[])
721        .expect("the derivation path yields a valid key")
722        .to_diversifiable_full_viewing_key();
723    let not_our_value = Zatoshis::const_from_u64(10_000);
724    let (start_height, _, _) =
725        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
726    for _ in 1..10 {
727        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
728    }
729    st.scan_cached_blocks(start_height, 10);
730
731    // Add `NUM_UTXOS` distinct-value P2PKH UTXOs at the same transparent address, so that
732    // largest-first selection is unambiguous.
733    let height = st.wallet().chain_height().unwrap().unwrap();
734    for i in 0..NUM_UTXOS {
735        let value = Zatoshis::const_from_u64(BASE + (i as u64) * STEP);
736        let mut hash = [0u8; 32];
737        hash[..4].copy_from_slice(&(i as u32).to_le_bytes());
738        let utxo = WalletTransparentOutput::from_parts(
739            OutPoint::new(hash, 0),
740            TxOut::new(value, taddr.script().into()),
741            Some(height),
742            Some(account.id()),
743            Some(TransparentKeyScope::EXTERNAL),
744            None,
745        )
746        .unwrap();
747        st.wallet_mut()
748            .put_received_transparent_utxo(&utxo)
749            .unwrap();
750    }
751
752    // Propose shielding with a 1%-of-block-space input cap.
753    let input_selector =
754        GreedyInputSelector::new().with_shielding_block_space_percent(BLOCK_SPACE_PERCENT);
755    let change_strategy =
756        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling);
757    let proposal = st
758        .propose_shielding(
759            &input_selector,
760            &change_strategy,
761            Zatoshis::const_from_u64(BASE),
762            &[*taddr],
763            account.id(),
764            ConfirmationsPolicy::MIN,
765            CoinbaseFilter::AllTransparentOutputs,
766        )
767        .expect("shielding proposal should succeed");
768
769    let inputs = proposal.steps().first().transparent_inputs();
770    assert_eq!(
771        inputs.len(),
772        CAP,
773        "the number of transparent inputs should be capped",
774    );
775
776    // The selected inputs must be the `CAP` highest-value UTXOs: the `NUM_UTXOS - CAP` smallest
777    // are dropped, so the smallest selected value is `BASE + (NUM_UTXOS - CAP) * STEP`.
778    let min_selected = inputs.iter().map(|u| u.value()).min().unwrap();
779    assert_eq!(
780        min_selected,
781        Zatoshis::const_from_u64(BASE + ((NUM_UTXOS - CAP) as u64) * STEP),
782        "the lowest-value UTXOs should be the ones left unspent",
783    );
784}
785
786/// This test attempts to verify that transparent funds spendability is
787/// accounted for properly given the different minimum confirmations values
788/// that can be set when querying for balances.
789pub fn transparent_balance_spendability<DSF>(dsf: DSF, cache: impl TestCache)
790where
791    DSF: DataStoreFactory,
792{
793    let mut st = TestBuilder::new()
794        .with_data_store_factory(dsf)
795        .with_block_cache(cache)
796        .with_account_from_sapling_activation(BlockHash([0; 32]))
797        .build();
798
799    let account = st.test_account().cloned().unwrap();
800    let uaddr = st
801        .wallet()
802        .get_last_generated_address_matching(account.id(), UnifiedAddressRequest::AllAvailableKeys)
803        .unwrap()
804        .unwrap();
805    let taddr = uaddr.transparent().unwrap();
806
807    // Initialize the wallet with chain data that has no shielded notes for us.
808    let not_our_key = ExtendedSpendingKey::master(&[])
809        .expect("the derivation path yields a valid key")
810        .to_diversifiable_full_viewing_key();
811    let not_our_value = Zatoshis::const_from_u64(10000);
812    let (start_height, _, _) =
813        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
814    for _ in 1..10 {
815        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
816    }
817    st.scan_cached_blocks(start_height, 10);
818
819    // The wallet starts out with zero balance.
820    check_balance::<DSF>(
821        &st as &TestState<_, DSF::DataStore, _>,
822        &account,
823        taddr,
824        ConfirmationsPolicy::MIN,
825        &Balance::ZERO,
826    );
827
828    // Create a fake transparent output.
829    let value = Zatoshis::from_u64(100000).unwrap();
830    let txout = TxOut::new(value, taddr.script().into());
831
832    // Pretend the output was received in the chain tip.
833    let height = st.wallet().chain_height().unwrap().unwrap();
834    let utxo = WalletTransparentOutput::from_parts(
835        OutPoint::fake(),
836        txout,
837        Some(height),
838        Some(account.id()),
839        Some(TransparentKeyScope::EXTERNAL),
840        None,
841    )
842    .unwrap();
843    st.wallet_mut()
844        .put_received_transparent_utxo(&utxo)
845        .unwrap();
846
847    // The wallet should detect the balance as available
848    let mut zero_or_one_conf_value = Balance::ZERO;
849
850    // add the spendable value to the expected balance
851    zero_or_one_conf_value.add_spendable_value(value).unwrap();
852
853    check_balance::<DSF>(
854        &st,
855        &account,
856        taddr,
857        ConfirmationsPolicy::MIN,
858        &zero_or_one_conf_value,
859    );
860
861    // now if we increase the number of confirmations our spendable balance should
862    // be zero and the total balance equal to `value`
863    let mut not_confirmed_yet_value = Balance::ZERO;
864
865    not_confirmed_yet_value
866        .add_pending_spendable_value(value)
867        .unwrap();
868
869    check_balance::<DSF>(
870        &st,
871        &account,
872        taddr,
873        ConfirmationsPolicy::new_symmetrical_unchecked(2, false),
874        &not_confirmed_yet_value,
875    );
876
877    // Add one extra block
878    st.generate_empty_block();
879
880    // Scan that block
881    st.scan_cached_blocks(height, 1);
882
883    // now we generate one more block and the balance should be the same as when the
884    // check_balance function was called with zero or one confirmation.
885    st.generate_empty_block();
886    st.scan_cached_blocks(height + 1, 1);
887
888    check_balance::<DSF>(
889        &st,
890        &account,
891        taddr,
892        ConfirmationsPolicy::new_symmetrical_unchecked(2, true),
893        &zero_or_one_conf_value,
894    );
895}
896
897/// Constructs a fake transparent-only coinbase transaction paying `value` to `taddr`.
898///
899/// The result is a structurally valid coinbase transaction (a single input spending the null
900/// outpoint), which causes the receiving wallet to classify it as coinbase when it is stored
901/// via [`decrypt_and_store_transaction`]. The `lock_time` parameter has no consensus meaning
902/// here; distinct values may be used to give otherwise-identical coinbase transactions
903/// distinct txids.
904fn fake_transparent_coinbase_tx(
905    lock_time: u32,
906    value: Zatoshis,
907    taddr: &TransparentAddress,
908) -> Transaction {
909    let coinbase_bundle = Bundle {
910        vin: vec![TxIn::from_parts(
911            OutPoint::NULL,
912            Script::default(),
913            u32::MAX,
914        )],
915        vout: vec![TxOut::new(value, taddr.script().into())],
916        authorization: Authorized,
917    };
918
919    TransactionData::<zcash_primitives::transaction::Authorized>::from_parts(
920        TxVersion::V5,
921        BranchId::Nu5,
922        lock_time,
923        // Coinbase transactions do not expire.
924        BlockHeight::from(0),
925        // Coinbase transactions burn nothing.
926        Some(coinbase_bundle),
927        None,
928        None,
929        None,
930    )
931    .freeze()
932    .unwrap()
933}
934
935/// Retrieves the [`AccountBalance`] for the given test account from the wallet summary.
936fn get_account_balance<DSF>(
937    st: &TestState<impl TestCache, <DSF as DataStoreFactory>::DataStore, LocalNetwork>,
938    account: &TestAccount<<DSF as DataStoreFactory>::Account>,
939    confirmations_policy: ConfirmationsPolicy,
940) -> AccountBalance
941where
942    DSF: DataStoreFactory,
943{
944    let summary = st
945        .wallet()
946        .get_wallet_summary(confirmations_policy)
947        .unwrap()
948        .unwrap();
949    *summary.account_balances().get(&account.id()).unwrap()
950}
951
952/// Verifies that transparent funds are reported in the correct `AccountBalance` bucket
953/// (regular vs. coinbase), that immature coinbase value is reported as pending rather than
954/// spendable, and that it becomes spendable upon reaching coinbase maturity.
955pub fn transparent_coinbase_balance_split<DSF>(ds_factory: DSF, cache: impl TestCache)
956where
957    DSF: DataStoreFactory,
958{
959    let mut st = TestBuilder::new()
960        .with_data_store_factory(ds_factory)
961        .with_block_cache(cache)
962        .with_account_from_sapling_activation(BlockHash([0; 32]))
963        .build();
964
965    let account = st.test_account().cloned().unwrap();
966    let uaddr = st
967        .wallet()
968        .get_last_generated_address_matching(account.id(), UnifiedAddressRequest::AllAvailableKeys)
969        .unwrap()
970        .unwrap();
971    let taddr = uaddr.transparent().unwrap();
972
973    // Mine a coinbase output paying the wallet's transparent address at tx index 0.
974    let coinbase_value = Zatoshis::const_from_u64(625_000_000);
975    let coinbase_tx = fake_transparent_coinbase_tx(0, coinbase_value, taddr);
976    let (h, _) = st.generate_next_block_from_tx(0, &coinbase_tx);
977    st.scan_cached_blocks(h, 1);
978    let params = *st.network();
979    decrypt_and_store_transaction(&params, st.wallet_mut(), &coinbase_tx, Some(h)).unwrap();
980
981    // Immature coinbase: the value is pending spendability in the coinbase bucket, not
982    // spendable; the regular bucket is untouched.
983    let balance = get_account_balance::<DSF>(&st, &account, ConfirmationsPolicy::MIN);
984    assert_eq!(
985        balance.unshielded_coinbase_balance().spendable_value(),
986        Zatoshis::ZERO
987    );
988    assert_eq!(
989        balance
990            .unshielded_coinbase_balance()
991            .value_pending_spendability(),
992        coinbase_value
993    );
994    assert_eq!(balance.unshielded_regular_balance(), &Balance::ZERO);
995
996    // The same holds when the confirmations policy itself is not yet satisfied (the coinbase
997    // output has only one confirmation here), which exercises the pending-balance query.
998    let balance = get_account_balance::<DSF>(
999        &st,
1000        &account,
1001        ConfirmationsPolicy::new_symmetrical_unchecked(2, false),
1002    );
1003    assert_eq!(
1004        balance.unshielded_coinbase_balance().spendable_value(),
1005        Zatoshis::ZERO
1006    );
1007    assert_eq!(
1008        balance
1009            .unshielded_coinbase_balance()
1010            .value_pending_spendability(),
1011        coinbase_value
1012    );
1013    assert_eq!(balance.unshielded_regular_balance(), &Balance::ZERO);
1014
1015    // Receive a regular (non-coinbase) UTXO. This output's transaction has no known tx_index,
1016    // so it must be classified as regular (non-coinbase) funds.
1017    let regular_value = Zatoshis::const_from_u64(100_000);
1018    let utxo = WalletTransparentOutput::from_parts(
1019        OutPoint::fake(),
1020        TxOut::new(regular_value, taddr.script().into()),
1021        Some(h),
1022        Some(account.id()),
1023        Some(TransparentKeyScope::EXTERNAL),
1024        None,
1025    )
1026    .unwrap();
1027    st.wallet_mut()
1028        .put_received_transparent_utxo(&utxo)
1029        .unwrap();
1030
1031    // Mixed state: the regular value is spendable, the coinbase value remains pending, and the
1032    // combined accessors report the sums of the two buckets.
1033    let balance = get_account_balance::<DSF>(&st, &account, ConfirmationsPolicy::MIN);
1034    assert_eq!(
1035        balance.unshielded_regular_balance().spendable_value(),
1036        regular_value
1037    );
1038    assert_eq!(
1039        balance
1040            .unshielded_coinbase_balance()
1041            .value_pending_spendability(),
1042        coinbase_value
1043    );
1044    assert_eq!(
1045        balance.unshielded_balance(),
1046        (*balance.unshielded_regular_balance() + *balance.unshielded_coinbase_balance()).unwrap()
1047    );
1048    #[allow(deprecated)]
1049    let unshielded = balance.unshielded();
1050    assert_eq!(unshielded, (regular_value + coinbase_value).unwrap());
1051    assert_eq!(balance.total(), (regular_value + coinbase_value).unwrap());
1052
1053    // Once the coinbase output reaches maturity, its value moves from pending to spendable.
1054    for _ in 0..COINBASE_MATURITY_BLOCKS {
1055        st.generate_empty_block();
1056    }
1057    st.scan_cached_blocks(h + 1, COINBASE_MATURITY_BLOCKS as usize);
1058
1059    let balance = get_account_balance::<DSF>(&st, &account, ConfirmationsPolicy::MIN);
1060    assert_eq!(
1061        balance.unshielded_coinbase_balance().spendable_value(),
1062        coinbase_value
1063    );
1064    assert_eq!(
1065        balance
1066            .unshielded_coinbase_balance()
1067            .value_pending_spendability(),
1068        Zatoshis::ZERO
1069    );
1070    assert_eq!(
1071        balance.unshielded_regular_balance().spendable_value(),
1072        regular_value
1073    );
1074    assert_eq!(balance.total(), (regular_value + coinbase_value).unwrap());
1075}
1076
1077/// Verifies that dust-valued (uneconomic) transparent outputs are reported in the
1078/// `uneconomic_value` field of the correct `AccountBalance` bucket (regular vs. coinbase).
1079pub fn transparent_coinbase_balance_dust<DSF>(ds_factory: DSF, cache: impl TestCache)
1080where
1081    DSF: DataStoreFactory,
1082{
1083    let dust_value = Zatoshis::const_from_u64(1000);
1084    let mut st = TestBuilder::new()
1085        .with_data_store_factory(ds_factory)
1086        .with_block_cache(cache)
1087        .with_account_from_sapling_activation(BlockHash([0; 32]))
1088        .build();
1089
1090    let account = st.test_account().cloned().unwrap();
1091    assert!(dust_value <= zip317::marginal_fee(st.network(), account.birthday().height() + 1));
1092    let uaddr = st
1093        .wallet()
1094        .get_last_generated_address_matching(account.id(), UnifiedAddressRequest::AllAvailableKeys)
1095        .unwrap()
1096        .unwrap();
1097    let taddr = uaddr.transparent().unwrap();
1098
1099    // Mine a dust coinbase output paying the wallet's transparent address at tx index 0.
1100    let coinbase_tx = fake_transparent_coinbase_tx(0, dust_value, taddr);
1101    let (h, _) = st.generate_next_block_from_tx(0, &coinbase_tx);
1102    st.scan_cached_blocks(h, 1);
1103    let params = *st.network();
1104    decrypt_and_store_transaction(&params, st.wallet_mut(), &coinbase_tx, Some(h)).unwrap();
1105
1106    // Receive a dust regular (non-coinbase) UTXO.
1107    let utxo = WalletTransparentOutput::from_parts(
1108        OutPoint::fake(),
1109        TxOut::new(dust_value, taddr.script().into()),
1110        Some(h),
1111        Some(account.id()),
1112        Some(TransparentKeyScope::EXTERNAL),
1113        None,
1114    )
1115    .unwrap();
1116    st.wallet_mut()
1117        .put_received_transparent_utxo(&utxo)
1118        .unwrap();
1119
1120    // Each dust output lands in the uneconomic value of its own bucket, and contributes to
1121    // neither spendable nor pending value.
1122    let balance = get_account_balance::<DSF>(&st, &account, ConfirmationsPolicy::MIN);
1123    assert_eq!(
1124        balance.unshielded_regular_balance().uneconomic_value(),
1125        dust_value
1126    );
1127    assert_eq!(
1128        balance.unshielded_coinbase_balance().uneconomic_value(),
1129        dust_value
1130    );
1131    assert_eq!(
1132        balance.uneconomic_value(),
1133        (dust_value + dust_value).unwrap()
1134    );
1135    assert_eq!(
1136        balance.unshielded_balance().spendable_value(),
1137        Zatoshis::ZERO
1138    );
1139    assert_eq!(
1140        balance.unshielded_balance().value_pending_spendability(),
1141        Zatoshis::ZERO
1142    );
1143    assert_eq!(balance.total(), Zatoshis::ZERO);
1144
1145    // Dust classification takes precedence over coinbase maturity: after the coinbase output
1146    // matures, its value remains uneconomic rather than becoming spendable.
1147    for _ in 0..COINBASE_MATURITY_BLOCKS {
1148        st.generate_empty_block();
1149    }
1150    st.scan_cached_blocks(h + 1, COINBASE_MATURITY_BLOCKS as usize);
1151
1152    let balance = get_account_balance::<DSF>(&st, &account, ConfirmationsPolicy::MIN);
1153    assert_eq!(
1154        balance.unshielded_coinbase_balance().uneconomic_value(),
1155        dust_value
1156    );
1157    assert_eq!(
1158        balance.unshielded_coinbase_balance().spendable_value(),
1159        Zatoshis::ZERO
1160    );
1161}
1162
1163/// The wallet classifies a transparent output as uneconomic by the ZIP 317 marginal fee in effect
1164/// at the target height: an output worth the marginal fee before the fee reduction height of
1165/// [ZIP 2009] is reported as uneconomic and left out of selection while the target height is
1166/// below that height, and is spendable from it.
1167///
1168/// [ZIP 2009]: https://zips.z.cash/zip-2009
1169pub fn transparent_dust_threshold_follows_marginal_fee_at_target_height<DSF>(
1170    ds_factory: DSF,
1171    cache: impl TestCache,
1172) where
1173    DSF: DataStoreFactory,
1174{
1175    let network = super::pool::nu7_activating_network();
1176    // On a regtest network the fee reduction takes effect at NU7 activation.
1177    let reduction_height = network
1178        .activation_height(NetworkUpgrade::Nu7)
1179        .expect("the test network activates NU7");
1180    let value = zip317::marginal_fee(&network, reduction_height - 1);
1181    assert!(value > zip317::marginal_fee(&network, reduction_height));
1182
1183    let mut st = TestBuilder::new()
1184        .with_network(network)
1185        .with_data_store_factory(ds_factory)
1186        .with_block_cache(cache)
1187        .with_account_from_sapling_activation(BlockHash([0; 32]))
1188        .build();
1189
1190    let account = st.test_account().cloned().unwrap();
1191    let uaddr = st
1192        .wallet()
1193        .get_last_generated_address_matching(account.id(), UnifiedAddressRequest::AllAvailableKeys)
1194        .unwrap()
1195        .unwrap();
1196    let taddr = uaddr.transparent().unwrap();
1197
1198    // Receive the output in the first block, well below the reduction height.
1199    let received_height = st.generate_and_scan_empty_blocks(1);
1200    let utxo = WalletTransparentOutput::from_parts(
1201        OutPoint::fake(),
1202        TxOut::new(value, taddr.script().into()),
1203        Some(received_height),
1204        Some(account.id()),
1205        Some(TransparentKeyScope::EXTERNAL),
1206        None,
1207    )
1208    .unwrap();
1209    st.wallet_mut()
1210        .put_received_transparent_utxo(&utxo)
1211        .unwrap();
1212
1213    // Advance the tip to two blocks below the reduction, so that the next transaction targets the
1214    // block before it.
1215    let blocks_to_add = u32::from(reduction_height) - 2 - u32::from(received_height);
1216    let tip = st.generate_and_scan_empty_blocks(
1217        usize::try_from(blocks_to_add).expect("block count fits in a usize"),
1218    );
1219    assert_eq!(tip, reduction_height - 2);
1220
1221    macro_rules! assert_classified {
1222        ($uneconomic:expr, $spendable:expr) => {{
1223            let policy = ConfirmationsPolicy::MIN;
1224            let tip = st.wallet().chain_height().unwrap().unwrap();
1225            let target_height = TargetHeight::from(tip + 1);
1226            let balance = get_account_balance::<DSF>(&st, &account, policy);
1227            assert_eq!(
1228                balance.unshielded_regular_balance().uneconomic_value(),
1229                $uneconomic
1230            );
1231            assert_eq!(
1232                balance.unshielded_regular_balance().spendable_value(),
1233                $spendable
1234            );
1235            let address_balance = st
1236                .wallet()
1237                .get_transparent_balances(account.id(), target_height, policy)
1238                .unwrap()
1239                .get(taddr)
1240                .cloned()
1241                .map(|(_, balance)| balance);
1242            assert_eq!(
1243                address_balance.map_or(Zatoshis::ZERO, |b| b.uneconomic_value()),
1244                $uneconomic
1245            );
1246            assert_eq!(
1247                address_balance.map_or(Zatoshis::ZERO, |b| b.spendable_value()),
1248                $spendable
1249            );
1250            assert_eq!(
1251                st.wallet()
1252                    .get_spendable_transparent_outputs(
1253                        taddr,
1254                        target_height,
1255                        policy,
1256                        CoinbaseFilter::AllTransparentOutputs,
1257                        LockFilter::Policy(&LockedInputPolicy::Exclude),
1258                    )
1259                    .unwrap()
1260                    .into_iter()
1261                    .map(|utxo| utxo.value())
1262                    .sum::<Option<Zatoshis>>(),
1263                Some($spendable),
1264            );
1265            assert_eq!(
1266                st.wallet()
1267                    .select_spendable_transparent_outputs(
1268                        account.id(),
1269                        target_height,
1270                        policy,
1271                        CoinbaseFilter::AllTransparentOutputs,
1272                        None,
1273                        TargetValue::AllFunds(MaxSpendMode::MaxSpendable),
1274                        usize::MAX,
1275                        &StandardFeeRule::Zip317,
1276                        LockFilter::Policy(&LockedInputPolicy::Exclude),
1277                    )
1278                    .unwrap()
1279                    .into_iter()
1280                    .map(|utxo| utxo.value())
1281                    .sum::<Option<Zatoshis>>(),
1282                Some($spendable),
1283            );
1284        }};
1285    }
1286
1287    // Below the reduction height, the output is uneconomic.
1288    assert_classified!(value, Zatoshis::ZERO);
1289
1290    // From the reduction height, it is spendable.
1291    let tip = st.generate_and_scan_empty_blocks(1);
1292    assert_eq!(tip, reduction_height - 1);
1293    assert_classified!(Zatoshis::ZERO, value);
1294}
1295
1296pub fn gap_limits<DSF>(ds_factory: DSF, cache: impl TestCache, gap_limits: GapLimits)
1297where
1298    DSF: DataStoreFactory,
1299    <DSF as DataStoreFactory>::AccountId: std::fmt::Debug,
1300{
1301    let mut st = TestBuilder::new()
1302        .with_data_store_factory(ds_factory)
1303        .with_block_cache(cache)
1304        .with_gap_limits(gap_limits)
1305        .with_account_from_sapling_activation(BlockHash([0; 32]))
1306        .build();
1307
1308    let test_account = st.test_account().cloned().unwrap();
1309    let account_uuid = test_account.account().id();
1310    let ufvk = test_account.account().ufvk().unwrap().clone();
1311
1312    let external_taddrs = st
1313        .wallet()
1314        .get_transparent_receivers(account_uuid, false, true)
1315        .unwrap();
1316    assert_eq!(
1317        u32::try_from(external_taddrs.len()).unwrap(),
1318        gap_limits.external()
1319    );
1320    let internal_taddrs = st
1321        .wallet()
1322        .get_transparent_receivers(account_uuid, true, false)
1323        .unwrap();
1324    assert_eq!(
1325        u32::try_from(internal_taddrs.len()).unwrap(),
1326        gap_limits.external() + gap_limits.internal()
1327    );
1328    let ephemeral_taddrs = st
1329        .wallet()
1330        .get_known_ephemeral_addresses(account_uuid, None)
1331        .unwrap();
1332    assert_eq!(
1333        u32::try_from(ephemeral_taddrs.len()).unwrap(),
1334        gap_limits.ephemeral()
1335    );
1336
1337    // Add some funds to the wallet
1338    let (h0, _, _) = st.generate_next_block(
1339        &ufvk.sapling().unwrap(),
1340        AddressType::DefaultExternal,
1341        Zatoshis::const_from_u64(1000000),
1342    );
1343    st.scan_cached_blocks(h0, 1);
1344
1345    // The previous operation was shielded-only, but unified address usage within the
1346    // valid transparent child index range still count towards the gap limit, so this
1347    // updates the gap limit by the index of the default Sapling receiver
1348    let external_taddrs = st
1349        .wallet()
1350        .get_transparent_receivers(account_uuid, false, true)
1351        .unwrap();
1352    assert_eq!(
1353        u32::try_from(external_taddrs.len()).unwrap(),
1354        gap_limits.external()
1355            + (u32::try_from(ufvk.sapling().unwrap().default_address().0).unwrap() + 1)
1356    );
1357
1358    // Pick an address half way through the set of external taddrs
1359    let external_taddrs_sorted = external_taddrs
1360        .into_iter()
1361        .filter_map(|(addr, meta)| meta.address_index().map(|i| (i, addr)))
1362        .collect::<BTreeMap<_, _>>();
1363    let to = Address::from(
1364        *external_taddrs_sorted
1365            .get(&NonHardenedChildIndex::from_index(4).unwrap())
1366            .expect("An address exists at index 4."),
1367    )
1368    .to_zcash_address(st.network());
1369
1370    // Create a transaction & scan the block. Since the txid corresponds to one our wallet
1371    // generated, this should cause the gap limit to be bumped (generating addresses with index
1372    // 10..15)
1373    let txids = st
1374        .create_standard_transaction(&test_account, to, Zatoshis::const_from_u64(20000))
1375        .unwrap();
1376    let (h1, _) = st.generate_next_block_including(txids.head);
1377
1378    // At this point, the transaction has been created, but since it has not been mined it does
1379    // not cause an update to the gap limit; we have to wait for the transaction to actually be
1380    // mined or we could bump the gap limit too soon and start generating addresses that will
1381    // never be inspected on wallet recovery.
1382    let external_taddrs = st
1383        .wallet()
1384        .get_transparent_receivers(account_uuid, false, true)
1385        .unwrap();
1386    assert_eq!(
1387        u32::try_from(external_taddrs.len()).unwrap(),
1388        gap_limits.external()
1389            + (u32::try_from(ufvk.sapling().unwrap().default_address().0).unwrap() + 1)
1390    );
1391
1392    // Mine the block, then use `decrypt_and_store_transaction` to ensure that the wallet sees
1393    // the transaction as mined (since transparent handling doesn't get this from
1394    // `scan_cached_blocks`)
1395    st.scan_cached_blocks(h1, 1);
1396    let tx = st.wallet().get_transaction(txids.head).unwrap().unwrap();
1397    decrypt_and_store_transaction(&st.network().clone(), st.wallet_mut(), &tx, Some(h1)).unwrap();
1398
1399    // Now that the transaction has been mined, the gap limit should have increased.
1400    let external_taddrs = st
1401        .wallet()
1402        .get_transparent_receivers(account_uuid, false, true)
1403        .unwrap();
1404    assert_eq!(
1405        u32::try_from(external_taddrs.len()).unwrap(),
1406        gap_limits.external() + 5
1407    );
1408
1409    // The utxo query height should be equal to the minimum mined height among transactions
1410    // sent to any of the set of {addresses in the gap limit range | address prior to the gap}.
1411    let query_height = st.wallet().utxo_query_height(account_uuid).unwrap();
1412    assert_eq!(query_height, h0);
1413}
1414
1415/// Builds a test 1-of-1 multisig redeem script from a single keypair.
1416#[cfg(feature = "transparent-key-import")]
1417fn build_test_redeem_script() -> (script::Redeem, secp256k1::SecretKey) {
1418    let secret_key = SecretKey::from_secret_bytes([1u8; 32]).expect("valid secret key");
1419    let pubkey = secret_key.public_key();
1420    let redeem_script = script::Component(
1421        check_multisig(1, &[&pubkey.serialize()], false)
1422            .unwrap()
1423            .into_iter()
1424            .collect(),
1425    );
1426    (redeem_script, secret_key)
1427}
1428
1429/// Tests that importing standalone transparent addresses without key material succeeds and
1430/// the addresses appear in `get_transparent_receivers` with the
1431/// [`TransparentAddressSource::StandaloneAddress`] source.
1432#[cfg(feature = "transparent-key-import")]
1433pub fn import_standalone_transparent_address<DSF>(dsf: DSF)
1434where
1435    DSF: DataStoreFactory,
1436{
1437    let mut st = TestBuilder::new()
1438        .with_data_store_factory(dsf)
1439        .with_account_from_sapling_activation(BlockHash([0; 32]))
1440        .build();
1441
1442    let account_id = st.test_account().unwrap().id();
1443
1444    // A P2PKH address, imported without its pubkey.
1445    let secret_key = SecretKey::from_secret_bytes([1u8; 32]).expect("valid secret key");
1446    let p2pkh_addr = TransparentAddress::from_pubkey(&secret_key.public_key());
1447    assert_matches!(
1448        st.wallet_mut()
1449            .import_standalone_transparent_address(account_id, p2pkh_addr),
1450        Ok(_)
1451    );
1452
1453    // A P2SH address, imported without its redeem script.
1454    let (redeem_script, _) = build_test_redeem_script();
1455    let p2sh_addr =
1456        TransparentAddress::from_script_pubkey(&sh(&redeem_script)).expect("valid P2SH address");
1457    assert_matches!(
1458        st.wallet_mut()
1459            .import_standalone_transparent_address(account_id, p2sh_addr),
1460        Ok(_)
1461    );
1462
1463    let receivers = st
1464        .wallet()
1465        .get_transparent_receivers(account_id, false, true)
1466        .unwrap();
1467    for addr in [p2pkh_addr, p2sh_addr] {
1468        let metadata = receivers.get(&addr).expect("address should be present");
1469        assert!(matches!(
1470            metadata.source(),
1471            TransparentAddressSource::StandaloneAddress
1472        ));
1473    }
1474}
1475
1476/// Tests that importing the same standalone address twice to the same account is idempotent.
1477#[cfg(feature = "transparent-key-import")]
1478pub fn import_standalone_transparent_address_idempotent<DSF>(dsf: DSF)
1479where
1480    DSF: DataStoreFactory,
1481{
1482    let mut st = TestBuilder::new()
1483        .with_data_store_factory(dsf)
1484        .with_account_from_sapling_activation(BlockHash([0; 32]))
1485        .build();
1486
1487    let account_id = st.test_account().unwrap().id();
1488
1489    let secret_key = SecretKey::from_secret_bytes([1u8; 32]).expect("valid secret key");
1490    let taddr = TransparentAddress::from_pubkey(&secret_key.public_key());
1491
1492    assert_matches!(
1493        st.wallet_mut()
1494            .import_standalone_transparent_address(account_id, taddr),
1495        Ok(_)
1496    );
1497
1498    let receivers_before = st
1499        .wallet()
1500        .get_transparent_receivers(account_id, false, true)
1501        .unwrap();
1502
1503    // Second import to the same account should also succeed (idempotent).
1504    assert_matches!(
1505        st.wallet_mut()
1506            .import_standalone_transparent_address(account_id, taddr),
1507        Ok(_)
1508    );
1509
1510    let receivers_after = st
1511        .wallet()
1512        .get_transparent_receivers(account_id, false, true)
1513        .unwrap();
1514    assert_eq!(receivers_before.len(), receivers_after.len());
1515}
1516
1517/// Tests that importing the same standalone address to a different account fails.
1518#[cfg(feature = "transparent-key-import")]
1519pub fn import_standalone_transparent_address_conflict<DSF>(dsf: DSF)
1520where
1521    DSF: DataStoreFactory,
1522{
1523    let mut st = TestBuilder::new()
1524        .with_data_store_factory(dsf)
1525        .with_account_from_sapling_activation(BlockHash([0; 32]))
1526        .build();
1527
1528    let account1_id = st.test_account().unwrap().id();
1529
1530    let secret_key = SecretKey::from_secret_bytes([1u8; 32]).expect("valid secret key");
1531    let taddr = TransparentAddress::from_pubkey(&secret_key.public_key());
1532
1533    assert_matches!(
1534        st.wallet_mut()
1535            .import_standalone_transparent_address(account1_id, taddr),
1536        Ok(_)
1537    );
1538
1539    // Create a second account
1540    let birthday = AccountBirthday::from_parts(
1541        ChainState::empty(
1542            st.network()
1543                .activation_height(NetworkUpgrade::Sapling)
1544                .unwrap()
1545                - 1,
1546            BlockHash([0; 32]),
1547        ),
1548        None,
1549    );
1550    let seed2 = Secret::new(vec![42u8; 32]);
1551    let (account2_id, _) = st
1552        .wallet_mut()
1553        .create_account("account2", &seed2, &birthday, None)
1554        .unwrap();
1555
1556    // Import of the same address to the second account should fail
1557    assert_matches!(
1558        st.wallet_mut()
1559            .import_standalone_transparent_address(account2_id, taddr),
1560        Err(_)
1561    );
1562}
1563
1564/// Tests that a UTXO received at an address imported without key material is reflected in the
1565/// wallet balance, but is not offered as a spendable output.
1566#[cfg(feature = "transparent-key-import")]
1567pub fn import_standalone_transparent_address_balance<DSF>(dsf: DSF)
1568where
1569    DSF: DataStoreFactory,
1570    <<DSF as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
1571{
1572    let mut st = TestBuilder::new()
1573        .with_data_store_factory(dsf)
1574        .with_account_from_sapling_activation(BlockHash([0; 32]))
1575        .build();
1576
1577    let account_id = st.test_account().unwrap().id();
1578    let birthday = st.test_account().unwrap().birthday().height();
1579
1580    let secret_key = SecretKey::from_secret_bytes([1u8; 32]).expect("valid secret key");
1581    let taddr = TransparentAddress::from_pubkey(&secret_key.public_key());
1582
1583    // Import the address without its pubkey.
1584    st.wallet_mut()
1585        .import_standalone_transparent_address(account_id, taddr)
1586        .unwrap();
1587
1588    let height = birthday + 1000;
1589    st.wallet_mut().update_chain_tip(height).unwrap();
1590
1591    // Create a fake UTXO at the address.
1592    let value = Zatoshis::const_from_u64(50_000);
1593    let outpoint = OutPoint::fake();
1594    let txout = TxOut::new(value, taddr.script().into());
1595    let utxo = WalletTransparentOutput::from_parts(
1596        outpoint,
1597        txout,
1598        Some(height),
1599        Some(account_id),
1600        None,
1601        None,
1602    )
1603    .unwrap();
1604    st.wallet_mut()
1605        .put_received_transparent_utxo(&utxo)
1606        .unwrap();
1607
1608    // Verify the balance is reflected via get_transparent_balances.
1609    let target_height = TargetHeight::from(height + 1);
1610    let balances = st
1611        .wallet()
1612        .get_transparent_balances(account_id, target_height, ConfirmationsPolicy::MIN)
1613        .unwrap();
1614    assert_eq!(balances.get(&taddr).map(|(_, b)| b.total()), Some(value),);
1615
1616    // The output must not be offered for spending: the wallet holds no key material with
1617    // which a spend could be constructed.
1618    let utxos = st
1619        .wallet()
1620        .get_spendable_transparent_outputs(
1621            &taddr,
1622            target_height,
1623            ConfirmationsPolicy::MIN,
1624            CoinbaseFilter::AllTransparentOutputs,
1625            LockFilter::Policy(&LockedInputPolicy::Exclude),
1626        )
1627        .unwrap();
1628    assert_eq!(utxos, vec![]);
1629}
1630
1631/// Tests that importing key material for a previously address-only import upgrades the
1632/// address in place: the pubkey (P2PKH) or redeem script (P2SH) becomes the address's
1633/// source, without a duplicate receiver appearing.
1634#[cfg(feature = "transparent-key-import")]
1635pub fn import_standalone_transparent_address_upgrade<DSF>(dsf: DSF)
1636where
1637    DSF: DataStoreFactory,
1638{
1639    let mut st = TestBuilder::new()
1640        .with_data_store_factory(dsf)
1641        .with_account_from_sapling_activation(BlockHash([0; 32]))
1642        .build();
1643
1644    let account_id = st.test_account().unwrap().id();
1645
1646    let secret_key = SecretKey::from_secret_bytes([1u8; 32]).expect("valid secret key");
1647    let pubkey = secret_key.public_key();
1648    let p2pkh_addr = TransparentAddress::from_pubkey(&pubkey);
1649
1650    let (redeem_script, _) = build_test_redeem_script();
1651    let p2sh_addr =
1652        TransparentAddress::from_script_pubkey(&sh(&redeem_script)).expect("valid P2SH address");
1653
1654    // Import both addresses without key material.
1655    st.wallet_mut()
1656        .import_standalone_transparent_address(account_id, p2pkh_addr)
1657        .unwrap();
1658    st.wallet_mut()
1659        .import_standalone_transparent_address(account_id, p2sh_addr)
1660        .unwrap();
1661
1662    let receivers_before = st
1663        .wallet()
1664        .get_transparent_receivers(account_id, false, true)
1665        .unwrap();
1666
1667    // Import the key material for each address.
1668    st.wallet_mut()
1669        .import_standalone_transparent_pubkey(account_id, pubkey)
1670        .unwrap();
1671    st.wallet_mut()
1672        .import_standalone_transparent_script(account_id, redeem_script)
1673        .unwrap();
1674
1675    // The addresses were upgraded in place: no new receivers, and each address's source
1676    // now reflects the imported key material.
1677    let receivers_after = st
1678        .wallet()
1679        .get_transparent_receivers(account_id, false, true)
1680        .unwrap();
1681    assert_eq!(receivers_before.len(), receivers_after.len());
1682
1683    let p2pkh_metadata = receivers_after
1684        .get(&p2pkh_addr)
1685        .expect("address should be present");
1686    assert!(matches!(
1687        p2pkh_metadata.source(),
1688        TransparentAddressSource::StandalonePubkey(_)
1689    ));
1690
1691    let p2sh_metadata = receivers_after
1692        .get(&p2sh_addr)
1693        .expect("address should be present");
1694    assert!(matches!(
1695        p2sh_metadata.source(),
1696        TransparentAddressSource::StandaloneScript(_)
1697    ));
1698}
1699
1700/// Tests that importing a standalone transparent public key succeeds.
1701#[cfg(feature = "transparent-key-import")]
1702pub fn import_standalone_transparent_pubkey<DSF>(dsf: DSF)
1703where
1704    DSF: DataStoreFactory,
1705{
1706    let mut st = TestBuilder::new()
1707        .with_data_store_factory(dsf)
1708        .with_account_from_sapling_activation(BlockHash([0; 32]))
1709        .build();
1710
1711    let account_id = st.test_account().unwrap().id();
1712
1713    let secret_key = SecretKey::from_secret_bytes([1u8; 32]).expect("valid secret key");
1714    let pubkey = secret_key.public_key();
1715    assert_matches!(
1716        st.wallet_mut()
1717            .import_standalone_transparent_pubkey(account_id, pubkey),
1718        Ok(_)
1719    );
1720}
1721
1722/// Tests that importing the same pubkey twice to the same account is idempotent.
1723#[cfg(feature = "transparent-key-import")]
1724pub fn import_standalone_transparent_pubkey_idempotent<DSF>(dsf: DSF)
1725where
1726    DSF: DataStoreFactory,
1727{
1728    let mut st = TestBuilder::new()
1729        .with_data_store_factory(dsf)
1730        .with_account_from_sapling_activation(BlockHash([0; 32]))
1731        .build();
1732
1733    let account_id = st.test_account().unwrap().id();
1734
1735    let secret_key = SecretKey::from_secret_bytes([1u8; 32]).expect("valid secret key");
1736    let pubkey = secret_key.public_key();
1737
1738    // First import
1739    assert_matches!(
1740        st.wallet_mut()
1741            .import_standalone_transparent_pubkey(account_id, pubkey),
1742        Ok(_)
1743    );
1744
1745    // Snapshot state after first import
1746    let receivers_before = st
1747        .wallet()
1748        .get_transparent_receivers(account_id, false, true)
1749        .unwrap();
1750
1751    // Second import to same account should also succeed (idempotent)
1752    assert_matches!(
1753        st.wallet_mut()
1754            .import_standalone_transparent_pubkey(account_id, pubkey),
1755        Ok(_)
1756    );
1757
1758    // Verify wallet state is unchanged
1759    let receivers_after = st
1760        .wallet()
1761        .get_transparent_receivers(account_id, false, true)
1762        .unwrap();
1763
1764    assert_eq!(receivers_before.len(), receivers_after.len());
1765
1766    let taddr = TransparentAddress::from_pubkey(&pubkey);
1767    let metadata = receivers_after
1768        .get(&taddr)
1769        .expect("address should be present");
1770    assert!(matches!(
1771        metadata.source(),
1772        TransparentAddressSource::StandalonePubkey(_)
1773    ));
1774}
1775
1776/// Tests that importing the same pubkey to a different account fails.
1777#[cfg(feature = "transparent-key-import")]
1778pub fn import_standalone_transparent_pubkey_conflict<DSF>(dsf: DSF)
1779where
1780    DSF: DataStoreFactory,
1781{
1782    let mut st = TestBuilder::new()
1783        .with_data_store_factory(dsf)
1784        .with_account_from_sapling_activation(BlockHash([0; 32]))
1785        .build();
1786
1787    let account1_id = st.test_account().unwrap().id();
1788
1789    let secret_key = SecretKey::from_secret_bytes([1u8; 32]).expect("valid secret key");
1790    let pubkey = secret_key.public_key();
1791
1792    // Import to first account
1793    assert_matches!(
1794        st.wallet_mut()
1795            .import_standalone_transparent_pubkey(account1_id, pubkey),
1796        Ok(_)
1797    );
1798
1799    // Create a second account
1800    let birthday = AccountBirthday::from_parts(
1801        ChainState::empty(
1802            st.network()
1803                .activation_height(NetworkUpgrade::Sapling)
1804                .unwrap()
1805                - 1,
1806            BlockHash([0; 32]),
1807        ),
1808        None,
1809    );
1810    let seed2 = Secret::new(vec![42u8; 32]);
1811    let (account2_id, _) = st
1812        .wallet_mut()
1813        .create_account("account2", &seed2, &birthday, None)
1814        .unwrap();
1815
1816    // Import same pubkey to second account should fail
1817    assert_matches!(
1818        st.wallet_mut()
1819            .import_standalone_transparent_pubkey(account2_id, pubkey),
1820        Err(_)
1821    );
1822}
1823
1824/// Tests that a UTXO received at a standalone P2PKH address is reflected in the wallet balance.
1825#[cfg(feature = "transparent-key-import")]
1826pub fn import_standalone_transparent_pubkey_balance<DSF>(dsf: DSF)
1827where
1828    DSF: DataStoreFactory,
1829    <<DSF as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
1830{
1831    let mut st = TestBuilder::new()
1832        .with_data_store_factory(dsf)
1833        .with_account_from_sapling_activation(BlockHash([0; 32]))
1834        .build();
1835
1836    let account_id = st.test_account().unwrap().id();
1837    let birthday = st.test_account().unwrap().birthday().height();
1838
1839    let secret_key = SecretKey::from_secret_bytes([1u8; 32]).expect("valid secret key");
1840    let pubkey = secret_key.public_key();
1841
1842    // Import the public key.
1843    st.wallet_mut()
1844        .import_standalone_transparent_pubkey(account_id, pubkey)
1845        .unwrap();
1846
1847    // Derive the P2PKH address.
1848    let taddr = TransparentAddress::from_pubkey(&pubkey);
1849
1850    let height = birthday + 1000;
1851    st.wallet_mut().update_chain_tip(height).unwrap();
1852
1853    // Create a fake UTXO at the P2PKH address.
1854    let value = Zatoshis::const_from_u64(50_000);
1855    let outpoint = OutPoint::fake();
1856    let txout = TxOut::new(value, taddr.script().into());
1857    let utxo = WalletTransparentOutput::from_parts(
1858        outpoint,
1859        txout,
1860        Some(height),
1861        Some(account_id),
1862        None,
1863        None,
1864    )
1865    .unwrap();
1866    st.wallet_mut()
1867        .put_received_transparent_utxo(&utxo)
1868        .unwrap();
1869
1870    // Verify the balance is reflected via get_transparent_balances.
1871    let target_height = TargetHeight::from(height + 1);
1872    let balances = st
1873        .wallet()
1874        .get_transparent_balances(account_id, target_height, ConfirmationsPolicy::MIN)
1875        .unwrap();
1876    assert_eq!(
1877        balances.get(&taddr).map(|(_, b)| b.spendable_value()),
1878        Some(value),
1879    );
1880
1881    // Verify the UTXO is returned by get_spendable_transparent_outputs.
1882    let utxos = st
1883        .wallet()
1884        .get_spendable_transparent_outputs(
1885            &taddr,
1886            target_height,
1887            ConfirmationsPolicy::MIN,
1888            CoinbaseFilter::AllTransparentOutputs,
1889            LockFilter::Policy(&LockedInputPolicy::Exclude),
1890        )
1891        .unwrap();
1892    assert_eq!(utxos.len(), 1);
1893    assert_eq!(utxos[0].value(), value);
1894}
1895
1896/// Tests spending from a standalone P2PKH address by shielding its balance.
1897#[cfg(feature = "transparent-key-import")]
1898pub fn spend_from_standalone_pubkey<DSF>(dsf: DSF, cache: impl TestCache)
1899where
1900    DSF: DataStoreFactory,
1901{
1902    let mut st = TestBuilder::new()
1903        .with_data_store_factory(dsf)
1904        .with_block_cache(cache)
1905        .with_account_from_sapling_activation(BlockHash([0; 32]))
1906        .build();
1907
1908    let account = st.test_account().cloned().unwrap();
1909    let account_id = account.id();
1910
1911    // Create a keypair and derive the P2PKH address.
1912    let secret_key = SecretKey::from_secret_bytes([1u8; 32]).expect("valid secret key");
1913    let pubkey = secret_key.public_key();
1914
1915    // Import the public key.
1916    st.wallet_mut()
1917        .import_standalone_transparent_pubkey(account_id, pubkey)
1918        .unwrap();
1919
1920    // Derive the P2PKH address.
1921    let taddr = TransparentAddress::from_pubkey(&pubkey);
1922
1923    // Initialize chain data with blocks (needed for shielding transaction creation).
1924    let not_our_key = ExtendedSpendingKey::master(&[])
1925        .expect("the derivation path yields a valid key")
1926        .to_diversifiable_full_viewing_key();
1927    let not_our_value = Zatoshis::const_from_u64(10000);
1928    let (start_height, _, _) =
1929        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
1930    for _ in 1..10 {
1931        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
1932    }
1933    st.scan_cached_blocks(start_height, 10);
1934
1935    // Create a fake UTXO at the P2PKH address.
1936    let value = Zatoshis::from_u64(100000).unwrap();
1937    let height = st.wallet().chain_height().unwrap().unwrap();
1938    let txout = TxOut::new(value, taddr.script().into());
1939    let utxo = WalletTransparentOutput::from_parts(
1940        OutPoint::fake(),
1941        txout,
1942        Some(height),
1943        Some(account_id),
1944        None,
1945        None,
1946    )
1947    .unwrap();
1948    st.wallet_mut()
1949        .put_received_transparent_utxo(&utxo)
1950        .unwrap();
1951
1952    // Build SpendingKeys with the standalone key for the P2PKH address.
1953    let mut standalone_keys = HashMap::new();
1954    standalone_keys.insert(taddr, vec![secret_key]);
1955    let spending_keys = SpendingKeys::new(
1956        account.usk().clone(),
1957        #[cfg(feature = "transparent-key-import")]
1958        standalone_keys,
1959    );
1960
1961    // Shield the P2PKH UTXO.
1962    let input_selector = GreedyInputSelector::new();
1963    let change_strategy =
1964        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling);
1965
1966    let prover = ::zcash_proofs::prover::LocalTxProver::bundled();
1967    let network = *st.network();
1968    let clock = st.clock().clone();
1969    let txids = wallet::shield_transparent_funds(
1970        st.wallet_mut(),
1971        &network,
1972        &clock,
1973        &mut UnwrapErr(SysRng),
1974        &prover,
1975        &prover,
1976        &input_selector,
1977        &change_strategy,
1978        value,
1979        &spending_keys,
1980        &[taddr],
1981        account_id,
1982        ConfirmationsPolicy::MIN,
1983    )
1984    .unwrap();
1985
1986    assert!(!txids.is_empty());
1987
1988    // The wallet should have zero transparent balance after shielding.
1989    check_balance::<DSF>(
1990        &st,
1991        &account,
1992        &taddr,
1993        ConfirmationsPolicy::MIN,
1994        &Balance::ZERO,
1995    );
1996
1997    // The shielded balance should now include the value minus the fee.
1998    let fee = st
1999        .get_tx_from_history(*txids.first())
2000        .unwrap()
2001        .unwrap()
2002        .fee_paid()
2003        .expect("fee should be known for wallet-created transactions");
2004    let summary = st
2005        .wallet()
2006        .get_wallet_summary(ConfirmationsPolicy::MIN)
2007        .unwrap()
2008        .unwrap();
2009    let account_balance = summary.account_balances().get(&account_id).unwrap();
2010    assert_eq!(
2011        account_balance
2012            .sapling_balance()
2013            .change_pending_confirmation(),
2014        (value - fee).unwrap(),
2015    );
2016}
2017
2018/// Tests that importing a standalone P2SH address succeeds and the address appears
2019/// in `get_transparent_receivers` with the correct `TransparentAddressSource`.
2020#[cfg(feature = "transparent-key-import")]
2021pub fn import_standalone_transparent_p2sh<DSF>(dsf: DSF)
2022where
2023    DSF: DataStoreFactory,
2024{
2025    let mut st = TestBuilder::new()
2026        .with_data_store_factory(dsf)
2027        .with_account_from_sapling_activation(BlockHash([0; 32]))
2028        .build();
2029
2030    let account_id = st.test_account().unwrap().id();
2031    let (redeem_script, _) = build_test_redeem_script();
2032
2033    // Import should succeed
2034    assert_matches!(
2035        st.wallet_mut()
2036            .import_standalone_transparent_script(account_id, redeem_script.clone()),
2037        Ok(_)
2038    );
2039
2040    // Verify the address appears in get_transparent_receivers
2041    let receivers = st
2042        .wallet()
2043        .get_transparent_receivers(account_id, false, true)
2044        .unwrap();
2045
2046    // The P2SH address derived from the redeem script should be present
2047    let script_pubkey = sh(&redeem_script);
2048    let expected_addr =
2049        TransparentAddress::from_script_pubkey(&script_pubkey).expect("valid P2SH address");
2050
2051    let metadata = receivers
2052        .get(&expected_addr)
2053        .expect("address should be present");
2054    assert!(matches!(
2055        metadata.source(),
2056        TransparentAddressSource::StandaloneScript(_)
2057    ));
2058}
2059
2060/// Tests that importing the same P2SH address twice to the same account is idempotent.
2061#[cfg(feature = "transparent-key-import")]
2062pub fn import_standalone_transparent_p2sh_idempotent<DSF>(dsf: DSF)
2063where
2064    DSF: DataStoreFactory,
2065{
2066    let mut st = TestBuilder::new()
2067        .with_data_store_factory(dsf)
2068        .with_account_from_sapling_activation(BlockHash([0; 32]))
2069        .build();
2070
2071    let account_id = st.test_account().unwrap().id();
2072    let (redeem_script, _) = build_test_redeem_script();
2073
2074    // First import
2075    assert_matches!(
2076        st.wallet_mut()
2077            .import_standalone_transparent_script(account_id, redeem_script.clone()),
2078        Ok(_)
2079    );
2080
2081    // Snapshot state after first import
2082    let receivers_before = st
2083        .wallet()
2084        .get_transparent_receivers(account_id, false, true)
2085        .unwrap();
2086
2087    // Second import to same account should also succeed (idempotent)
2088    assert_matches!(
2089        st.wallet_mut()
2090            .import_standalone_transparent_script(account_id, redeem_script.clone()),
2091        Ok(_)
2092    );
2093
2094    // Verify wallet state is unchanged
2095    let receivers_after = st
2096        .wallet()
2097        .get_transparent_receivers(account_id, false, true)
2098        .unwrap();
2099
2100    assert_eq!(receivers_before.len(), receivers_after.len());
2101
2102    let script_pubkey = sh(&redeem_script);
2103    let expected_addr =
2104        TransparentAddress::from_script_pubkey(&script_pubkey).expect("valid P2SH address");
2105    let metadata = receivers_after
2106        .get(&expected_addr)
2107        .expect("address should be present");
2108    assert!(matches!(
2109        metadata.source(),
2110        TransparentAddressSource::StandaloneScript(_)
2111    ));
2112}
2113
2114/// Tests that importing the same P2SH address to a different account fails.
2115#[cfg(feature = "transparent-key-import")]
2116pub fn import_standalone_transparent_p2sh_conflict<DSF>(dsf: DSF)
2117where
2118    DSF: DataStoreFactory,
2119{
2120    let mut st = TestBuilder::new()
2121        .with_data_store_factory(dsf)
2122        .with_account_from_sapling_activation(BlockHash([0; 32]))
2123        .build();
2124
2125    let account1_id = st.test_account().unwrap().id();
2126    let (redeem_script, _) = build_test_redeem_script();
2127
2128    // Import to first account
2129    assert_matches!(
2130        st.wallet_mut()
2131            .import_standalone_transparent_script(account1_id, redeem_script.clone()),
2132        Ok(_)
2133    );
2134
2135    // Create a second account
2136    let birthday = AccountBirthday::from_parts(
2137        ChainState::empty(
2138            st.network()
2139                .activation_height(NetworkUpgrade::Sapling)
2140                .unwrap()
2141                - 1,
2142            BlockHash([0; 32]),
2143        ),
2144        None,
2145    );
2146    let seed2 = Secret::new(vec![42u8; 32]);
2147    let (account2_id, _) = st
2148        .wallet_mut()
2149        .create_account("account2", &seed2, &birthday, None)
2150        .unwrap();
2151
2152    // Import same redeem script to second account should fail
2153    assert_matches!(
2154        st.wallet_mut()
2155            .import_standalone_transparent_script(account2_id, redeem_script),
2156        Err(_)
2157    );
2158}
2159
2160/// Tests that a UTXO received at a standalone P2SH address is reflected in the wallet balance.
2161#[cfg(feature = "transparent-key-import")]
2162pub fn import_standalone_transparent_p2sh_balance<DSF>(dsf: DSF)
2163where
2164    DSF: DataStoreFactory,
2165    <<DSF as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
2166{
2167    let mut st = TestBuilder::new()
2168        .with_data_store_factory(dsf)
2169        .with_account_from_sapling_activation(BlockHash([0; 32]))
2170        .build();
2171
2172    let account_id = st.test_account().unwrap().id();
2173    let birthday = st.test_account().unwrap().birthday().height();
2174
2175    let (redeem_script, _) = build_test_redeem_script();
2176
2177    // Import the P2SH address.
2178    st.wallet_mut()
2179        .import_standalone_transparent_script(account_id, redeem_script.clone())
2180        .unwrap();
2181
2182    // Derive the expected transparent address from the redeem script.
2183    let script_pubkey = sh(&redeem_script);
2184    let taddr = TransparentAddress::from_script_pubkey(&script_pubkey).expect("valid P2SH address");
2185
2186    let height = birthday + 1000;
2187    st.wallet_mut().update_chain_tip(height).unwrap();
2188
2189    // Create a fake UTXO at the P2SH address.
2190    let value = Zatoshis::const_from_u64(50_000);
2191    let outpoint = OutPoint::fake();
2192    let txout = TxOut::new(value, taddr.script().into());
2193    let utxo = WalletTransparentOutput::from_parts(
2194        outpoint,
2195        txout,
2196        Some(height),
2197        Some(account_id),
2198        None,
2199        None,
2200    )
2201    .unwrap();
2202    st.wallet_mut()
2203        .put_received_transparent_utxo(&utxo)
2204        .unwrap();
2205
2206    // Verify the balance is reflected via get_transparent_balances.
2207    let target_height = TargetHeight::from(height + 1);
2208    let balances = st
2209        .wallet()
2210        .get_transparent_balances(account_id, target_height, ConfirmationsPolicy::MIN)
2211        .unwrap();
2212    assert_eq!(
2213        balances.get(&taddr).map(|(_, b)| b.spendable_value()),
2214        Some(value),
2215    );
2216
2217    // Verify the UTXO is returned by get_spendable_transparent_outputs.
2218    let utxos = st
2219        .wallet()
2220        .get_spendable_transparent_outputs(
2221            &taddr,
2222            target_height,
2223            ConfirmationsPolicy::MIN,
2224            CoinbaseFilter::AllTransparentOutputs,
2225            LockFilter::Policy(&LockedInputPolicy::Exclude),
2226        )
2227        .unwrap();
2228    assert_eq!(utxos.len(), 1);
2229    assert_eq!(utxos[0].value(), value);
2230}
2231
2232/// Tests spending from a standalone P2SH (multisig) address by shielding its balance.
2233#[cfg(feature = "transparent-key-import")]
2234pub fn spend_from_standalone_p2sh<DSF>(dsf: DSF, cache: impl TestCache)
2235where
2236    DSF: DataStoreFactory,
2237{
2238    let mut st = TestBuilder::new()
2239        .with_data_store_factory(dsf)
2240        .with_block_cache(cache)
2241        .with_account_from_sapling_activation(BlockHash([0; 32]))
2242        .build();
2243
2244    let account = st.test_account().cloned().unwrap();
2245    let account_id = account.id();
2246    // Build the redeem script and get the signing key.
2247    let (redeem_script, secret_key) = build_test_redeem_script();
2248
2249    // Import the P2SH address.
2250    st.wallet_mut()
2251        .import_standalone_transparent_script(account_id, redeem_script.clone())
2252        .unwrap();
2253
2254    // Derive the P2SH address.
2255    let script_pubkey = sh(&redeem_script);
2256    let taddr = TransparentAddress::from_script_pubkey(&script_pubkey).expect("valid P2SH address");
2257
2258    // Initialize chain data with blocks (needed for shielding transaction creation).
2259    let not_our_key = ExtendedSpendingKey::master(&[])
2260        .expect("the derivation path yields a valid key")
2261        .to_diversifiable_full_viewing_key();
2262    let not_our_value = Zatoshis::const_from_u64(10000);
2263    let (start_height, _, _) =
2264        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
2265    for _ in 1..10 {
2266        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
2267    }
2268    st.scan_cached_blocks(start_height, 10);
2269
2270    // Create a fake UTXO at the P2SH address.
2271    let value = Zatoshis::from_u64(100000).unwrap();
2272    let height = st.wallet().chain_height().unwrap().unwrap();
2273    let txout = TxOut::new(value, taddr.script().into());
2274    let utxo = WalletTransparentOutput::from_parts(
2275        OutPoint::fake(),
2276        txout,
2277        Some(height),
2278        Some(account_id),
2279        None,
2280        None,
2281    )
2282    .unwrap();
2283    st.wallet_mut()
2284        .put_received_transparent_utxo(&utxo)
2285        .unwrap();
2286
2287    // Build SpendingKeys with the standalone key for the P2SH address.
2288    let mut standalone_keys = HashMap::new();
2289    standalone_keys.insert(taddr, vec![secret_key]);
2290    let spending_keys = SpendingKeys::new(
2291        account.usk().clone(),
2292        #[cfg(feature = "transparent-key-import")]
2293        standalone_keys,
2294    );
2295
2296    // Shield the P2SH UTXO.
2297    let input_selector = GreedyInputSelector::new();
2298    let change_strategy =
2299        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling);
2300
2301    let prover = ::zcash_proofs::prover::LocalTxProver::bundled();
2302    let network = *st.network();
2303    let clock = st.clock().clone();
2304    let txids = wallet::shield_transparent_funds(
2305        st.wallet_mut(),
2306        &network,
2307        &clock,
2308        &mut UnwrapErr(SysRng),
2309        &prover,
2310        &prover,
2311        &input_selector,
2312        &change_strategy,
2313        value,
2314        &spending_keys,
2315        &[taddr],
2316        account_id,
2317        ConfirmationsPolicy::MIN,
2318    )
2319    .unwrap();
2320
2321    assert!(!txids.is_empty());
2322
2323    // The wallet should have zero transparent balance after shielding.
2324    check_balance::<DSF>(
2325        &st,
2326        &account,
2327        &taddr,
2328        ConfirmationsPolicy::MIN,
2329        &Balance::ZERO,
2330    );
2331
2332    // The shielded balance should now include the value minus the fee.
2333    let fee = st
2334        .get_tx_from_history(*txids.first())
2335        .unwrap()
2336        .unwrap()
2337        .fee_paid()
2338        .expect("fee should be known for wallet-created transactions");
2339    let summary = st
2340        .wallet()
2341        .get_wallet_summary(ConfirmationsPolicy::MIN)
2342        .unwrap()
2343        .unwrap();
2344    let account_balance = summary.account_balances().get(&account_id).unwrap();
2345    assert_eq!(
2346        account_balance
2347            .sapling_balance()
2348            .change_pending_confirmation(),
2349        (value - fee).unwrap(),
2350    );
2351}
2352
2353/// Tests [`WalletWrite::mark_transparent_addresses_exposed`] by observing the effect on the
2354/// address's exposure metadata via
2355/// [`WalletRead::get_transparent_address_metadata`](crate::data_api::WalletRead::get_transparent_address_metadata).
2356pub fn mark_transparent_addresses_exposed<DSF>(dsf: DSF)
2357where
2358    DSF: DataStoreFactory,
2359{
2360    let mut st = TestBuilder::new()
2361        .with_data_store_factory(dsf)
2362        .with_account_from_sapling_activation(BlockHash([0; 32]))
2363        .build();
2364
2365    let account_id = st.test_account().unwrap().id();
2366    let taddr = *st
2367        .wallet()
2368        .get_last_generated_address_matching(account_id, UnifiedAddressRequest::AllAvailableKeys)
2369        .unwrap()
2370        .unwrap()
2371        .transparent()
2372        .unwrap();
2373
2374    let exposure_of = |st: &TestState<_, <DSF as DataStoreFactory>::DataStore, LocalNetwork>,
2375                       addr: &TransparentAddress|
2376     -> Exposure {
2377        st.wallet()
2378            .get_transparent_address_metadata(account_id, addr)
2379            .unwrap()
2380            .unwrap()
2381            .exposure()
2382    };
2383
2384    // Calling with a very high height does not raise an already-recorded exposure,
2385    // and records the provided height if no prior exposure was tracked.
2386    let initial = exposure_of(&st, &taddr);
2387    let very_high = BlockHeight::from(u32::MAX);
2388    st.wallet_mut()
2389        .mark_transparent_addresses_exposed(&[(taddr, very_high)])
2390        .unwrap();
2391    match initial {
2392        Exposure::Exposed { at_height, .. } => assert_matches!(
2393            exposure_of(&st, &taddr),
2394            Exposure::Exposed { at_height: h, .. } if h == at_height
2395        ),
2396        Exposure::Unknown | Exposure::CannotKnow => assert_matches!(
2397            exposure_of(&st, &taddr),
2398            Exposure::Exposed { at_height: h, .. } if h == very_high
2399        ),
2400    }
2401
2402    // Calling with a lower height lowers the recorded exposure.
2403    st.wallet_mut()
2404        .mark_transparent_addresses_exposed(&[(taddr, BlockHeight::from(0))])
2405        .unwrap();
2406    assert_matches!(
2407        exposure_of(&st, &taddr),
2408        Exposure::Exposed { at_height, .. } if at_height == BlockHeight::from(0)
2409    );
2410
2411    // Calling with a higher height does not raise the recorded exposure.
2412    st.wallet_mut()
2413        .mark_transparent_addresses_exposed(&[(taddr, BlockHeight::from(100))])
2414        .unwrap();
2415    assert_matches!(
2416        exposure_of(&st, &taddr),
2417        Exposure::Exposed { at_height, .. } if at_height == BlockHeight::from(0)
2418    );
2419
2420    // An address not tracked by the wallet must return an error.
2421    let unknown = TransparentAddress::PublicKeyHash([0u8; 20]);
2422    assert!(
2423        st.wallet_mut()
2424            .mark_transparent_addresses_exposed(&[(unknown, BlockHeight::from(1))])
2425            .is_err()
2426    );
2427
2428    // An empty input is a no-op.
2429    st.wallet_mut()
2430        .mark_transparent_addresses_exposed(&[])
2431        .unwrap();
2432}
2433
2434/// Tests that [`WalletWrite::mark_transparent_addresses_exposed`] correctly handles bulk
2435/// input: all addresses in a successful call must be marked, and an unrecognized address
2436/// must cause the entire call to be rolled back.
2437pub fn mark_transparent_addresses_exposed_bulk<DSF>(dsf: DSF)
2438where
2439    DSF: DataStoreFactory,
2440{
2441    let gap_limits = GapLimits::new(5, 2, 2);
2442    let mut st = TestBuilder::new()
2443        .with_data_store_factory(dsf)
2444        .with_gap_limits(gap_limits)
2445        .with_account_from_sapling_activation(BlockHash([0; 32]))
2446        .build();
2447
2448    let account_id = st.test_account().unwrap().id();
2449
2450    let mut receivers = st
2451        .wallet()
2452        .get_transparent_receivers(account_id, false, true)
2453        .unwrap()
2454        .into_iter()
2455        .filter_map(|(addr, meta)| {
2456            let exposure = meta.exposure();
2457            meta.address_index().map(|i| (i.index(), addr, exposure))
2458        })
2459        .collect::<Vec<_>>();
2460    receivers.sort_by_key(|(i, _, _)| *i);
2461
2462    // Use known-unexposed receivers for the bulk-success test, so that the post-call
2463    // recorded height is exactly the one we pass in regardless of any default exposure
2464    // that address generation may set on other receivers.
2465    let unexposed = receivers
2466        .iter()
2467        .copied()
2468        .filter(|(_, _, exposure)| matches!(exposure, Exposure::Unknown))
2469        .collect::<Vec<_>>();
2470    assert!(
2471        unexposed.len() >= 2,
2472        "account should have at least 2 unexposed derived receivers"
2473    );
2474
2475    // Mark two unexposed addresses at distinct heights in a single bulk call.
2476    let (_idx_a, addr_a, _) = unexposed[0];
2477    let (_idx_b, addr_b, _) = unexposed[1];
2478    let height_a = BlockHeight::from(10);
2479    let height_b = BlockHeight::from(20);
2480    st.wallet_mut()
2481        .mark_transparent_addresses_exposed(&[(addr_a, height_a), (addr_b, height_b)])
2482        .unwrap();
2483
2484    let exposure_of = |st: &TestState<_, <DSF as DataStoreFactory>::DataStore, LocalNetwork>,
2485                       addr: &TransparentAddress|
2486     -> Exposure {
2487        st.wallet()
2488            .get_transparent_address_metadata(account_id, addr)
2489            .unwrap()
2490            .unwrap()
2491            .exposure()
2492    };
2493    assert_matches!(
2494        exposure_of(&st, &addr_a),
2495        Exposure::Exposed { at_height, .. } if at_height == height_a
2496    );
2497    assert_matches!(
2498        exposure_of(&st, &addr_b),
2499        Exposure::Exposed { at_height, .. } if at_height == height_b
2500    );
2501
2502    // Now attempt a bulk call where the second entry is unrecognized. The whole call must
2503    // fail, and the first entry must not have been partially applied. Pick a third
2504    // receiver distinct from `addr_a`/`addr_b` — its prior exposure state is irrelevant
2505    // since the assertion is preservation, not a specific height.
2506    let (idx_c, addr_c, _) = *receivers
2507        .iter()
2508        .find(|(_, addr, _)| *addr != addr_a && *addr != addr_b)
2509        .expect("account should have a third derived receiver");
2510    let before = exposure_of(&st, &addr_c);
2511    let unknown = TransparentAddress::PublicKeyHash([0x7u8; 20]);
2512    assert!(
2513        st.wallet_mut()
2514            .mark_transparent_addresses_exposed(&[
2515                (addr_c, BlockHeight::from(5)),
2516                (unknown, BlockHeight::from(5)),
2517            ])
2518            .is_err()
2519    );
2520    assert_eq!(
2521        exposure_of(&st, &addr_c),
2522        before,
2523        "exposure at index {idx_c} must not change when bulk call fails atomically"
2524    );
2525}
2526
2527/// Tests that [`WalletWrite::mark_transparent_addresses_exposed`] returns an error when
2528/// asked to mark an address that the wallet does not track.
2529pub fn mark_transparent_addresses_exposed_unknown_address<DSF>(dsf: DSF)
2530where
2531    DSF: DataStoreFactory,
2532{
2533    let mut st = TestBuilder::new()
2534        .with_data_store_factory(dsf)
2535        .with_account_from_sapling_activation(BlockHash([0; 32]))
2536        .build();
2537
2538    let unknown = TransparentAddress::PublicKeyHash([0u8; 20]);
2539    assert!(
2540        st.wallet_mut()
2541            .mark_transparent_addresses_exposed(&[(unknown, BlockHeight::from(1))])
2542            .is_err()
2543    );
2544}
2545
2546/// Constructs a fake transparent-only transaction spending `vin` and paying `value` to `taddr`.
2547///
2548/// When `vin` is empty the transaction spends one arbitrary outpoint, so that it is never
2549/// structurally a coinbase transaction. The `lock_time` parameter has no consensus meaning here;
2550/// distinct values may be used to give otherwise-identical transactions distinct txids.
2551fn fake_transparent_payment_tx(
2552    lock_time: u32,
2553    vin: &[OutPoint],
2554    value: Zatoshis,
2555    taddr: &TransparentAddress,
2556) -> Transaction {
2557    let bundle = Bundle {
2558        vin: if vin.is_empty() {
2559            vec![TxIn::from_parts(OutPoint::fake(), Script::default(), 0)]
2560        } else {
2561            vin.iter()
2562                .map(|outpoint| TxIn::from_parts(outpoint.clone(), Script::default(), 0))
2563                .collect()
2564        },
2565        vout: vec![TxOut::new(value, taddr.script().into())],
2566        authorization: Authorized,
2567    };
2568
2569    TransactionData::<zcash_primitives::transaction::Authorized>::from_parts(
2570        TxVersion::V5,
2571        BranchId::Nu5,
2572        lock_time,
2573        BlockHeight::from(0),
2574        Some(bundle),
2575        None,
2576        None,
2577        None,
2578    )
2579    .freeze()
2580    .unwrap()
2581}
2582
2583/// Scans a block that spends a wallet transparent output *before* scanning the block that created
2584/// it, and verifies that the spend is recognized once the output is discovered.
2585///
2586/// This is the out-of-order case the transparent spend map exists for: at the time the spending
2587/// block is scanned the wallet does not know it holds the output, so the spend cannot be matched
2588/// against anything. The spending transaction is recorded against the outpoint, and the spend must
2589/// be resolved when the earlier block brings the output into the wallet.
2590pub fn scan_detects_out_of_order_transparent_spend<DSF>(dsf: DSF, cache: impl TestCache)
2591where
2592    DSF: DataStoreFactory,
2593    <<DSF as DataStoreFactory>::DataStore as WalletRead>::AccountId:
2594        ConditionallySelectable + Default + Ord + std::hash::Hash + Send + Sync + 'static,
2595{
2596    let mut st = TestBuilder::new()
2597        .with_data_store_factory(dsf)
2598        .with_block_cache(cache)
2599        .with_account_from_sapling_activation(BlockHash([0; 32]))
2600        .build();
2601
2602    let account_id = st.test_account().unwrap().id();
2603    let taddr = wallet_taddr(st.wallet(), account_id);
2604    let value = Zatoshis::const_from_u64(100000);
2605
2606    // The block that pays the wallet, followed by the block that spends what it paid.
2607    let (received_height, _, received_txid) =
2608        st.generate_next_block_transparent(&[], &[(taddr, value)]);
2609    let funded_outpoint = OutPoint::new(received_txid.into(), 0);
2610    let (spend_height, _, spend_txid) =
2611        st.generate_next_block_transparent(std::slice::from_ref(&funded_outpoint), &[]);
2612
2613    st.scan_cached_blocks(spend_height, 1);
2614
2615    // The wallet cannot recognize a spend of an output it has never seen, so at this point it
2616    // holds no record of the output at all.
2617    assert_matches!(
2618        st.wallet().get_transparent_output(&funded_outpoint, None),
2619        Ok(None),
2620        "the wallet must not know of the output before the block creating it is scanned",
2621    );
2622
2623    // Scanning the earlier block brings the output into the wallet, at which point the
2624    // already-observed spend must be attached to it.
2625    st.scan_cached_blocks(received_height, 1);
2626
2627    let target_height = TargetHeight::from(spend_height + 1);
2628
2629    // The output is now known to the wallet. Asserting this separately is what keeps the
2630    // "not unspent" assertions below from being satisfied by an output that was never recorded
2631    // at all, which is indistinguishable from a spent one in every query that filters on
2632    // spendability.
2633    assert_matches!(
2634        st.wallet().get_transparent_output(&funded_outpoint, None),
2635        Ok(Some(utxo)) if utxo.txout().value() == value,
2636        "the output must have been recorded when the block creating it was scanned",
2637    );
2638
2639    assert_matches!(
2640        st.wallet()
2641            .get_unspent_transparent_output(&funded_outpoint, target_height),
2642        Ok(None),
2643        "the spend observed before the output was discovered must have been resolved",
2644    );
2645    assert_matches!(
2646        st.wallet()
2647            .get_spendable_transparent_outputs(
2648                &taddr,
2649                target_height,
2650                ConfirmationsPolicy::MIN,
2651                CoinbaseFilter::AllTransparentOutputs,
2652                LockFilter::Policy(&LockedInputPolicy::Exclude),
2653            )
2654            .as_deref(),
2655        Ok(&[])
2656    );
2657    assert_matches!(
2658        st.wallet()
2659            .get_transparent_balances(account_id, target_height, ConfirmationsPolicy::MIN),
2660        Ok(balances) if balances.get(&taddr).map(|(_, b)| b.total()) == Some(Zatoshis::ZERO)
2661            || balances.is_empty()
2662    );
2663
2664    // The spend must be attributed to the transaction that actually effected it, which the wallet
2665    // had no other reason to store.
2666    let spending_txids = st
2667        .wallet()
2668        .get_tx_history()
2669        .unwrap()
2670        .into_iter()
2671        .map(|tx| tx.txid())
2672        .collect::<Vec<_>>();
2673    assert!(
2674        spending_txids.contains(&spend_txid),
2675        "the spending transaction {spend_txid} should have been recorded; history holds {spending_txids:?}",
2676    );
2677}
2678
2679/// Scans a block that pays a wallet transparent address, then the block that spends the output,
2680/// and verifies that the spend is recognized directly during the scan of the later block.
2681///
2682/// This is the in-order counterpart of [`scan_detects_out_of_order_transparent_spend`]: here the
2683/// wallet already tracks the outpoint when the spending block is scanned, so the spend is matched
2684/// without consulting the spend map.
2685pub fn scan_detects_transparent_spend<DSF>(dsf: DSF, cache: impl TestCache)
2686where
2687    DSF: DataStoreFactory,
2688    <<DSF as DataStoreFactory>::DataStore as WalletRead>::AccountId:
2689        ConditionallySelectable + Default + Ord + std::hash::Hash + Send + Sync + 'static,
2690{
2691    let mut st = TestBuilder::new()
2692        .with_data_store_factory(dsf)
2693        .with_block_cache(cache)
2694        .with_account_from_sapling_activation(BlockHash([0; 32]))
2695        .build();
2696
2697    let account_id = st.test_account().unwrap().id();
2698    let taddr = wallet_taddr(st.wallet(), account_id);
2699    let value = Zatoshis::const_from_u64(100000);
2700
2701    let (received_height, _, received_txid) =
2702        st.generate_next_block_transparent(&[], &[(taddr, value)]);
2703    let funded_outpoint = OutPoint::new(received_txid.into(), 0);
2704
2705    st.scan_cached_blocks(received_height, 1);
2706
2707    // The scan of the paying block must have recorded the output as a wallet UTXO.
2708    assert_matches!(
2709        st.wallet().get_unspent_transparent_output(
2710            &funded_outpoint,
2711            TargetHeight::from(received_height + 1),
2712        ),
2713        Ok(Some(utxo)) if utxo.txout().value() == value
2714    );
2715
2716    let (spend_height, _, _) =
2717        st.generate_next_block_transparent(std::slice::from_ref(&funded_outpoint), &[]);
2718    st.scan_cached_blocks(spend_height, 1);
2719
2720    assert_matches!(
2721        st.wallet().get_transparent_output(&funded_outpoint, None),
2722        Ok(Some(_)),
2723        "the output must remain known to the wallet after being spent",
2724    );
2725    assert_matches!(
2726        st.wallet()
2727            .get_unspent_transparent_output(&funded_outpoint, TargetHeight::from(spend_height + 1)),
2728        Ok(None),
2729        "the output must be recorded as spent once its spend has been scanned",
2730    );
2731}
2732
2733/// Returns the default external transparent receiver of the given account.
2734fn wallet_taddr<DbT>(wallet: &DbT, account_id: <DbT as WalletRead>::AccountId) -> TransparentAddress
2735where
2736    DbT: WalletRead,
2737    <DbT as WalletRead>::Error: std::fmt::Debug,
2738{
2739    *wallet
2740        .get_last_generated_address_matching(account_id, UnifiedAddressRequest::AllAvailableKeys)
2741        .unwrap()
2742        .unwrap()
2743        .transparent()
2744        .unwrap()
2745}
2746
2747/// Builds a block at `height` whose coinbase transaction is followed by a transparent-only
2748/// transaction paying `value` to `taddr`, scans it, and returns the scanned block together with
2749/// the outpoint of the payment.
2750///
2751/// Placing the payment behind the coinbase keeps the output it creates out of the coinbase
2752/// maturity rule. `lock_time` has no consensus meaning here; distinct values give the payment
2753/// transactions of otherwise-identical blocks distinct txids.
2754///
2755/// The scan is performed against the wallet's current tracked spend identifiers, as
2756/// `scan_cached_blocks` does, so that a spend of an output the wallet already holds is detected.
2757#[allow(clippy::too_many_arguments)]
2758fn scan_transparent_payment_block<DbT>(
2759    wallet: &DbT,
2760    network: &LocalNetwork,
2761    account_id: <DbT as WalletRead>::AccountId,
2762    height: BlockHeight,
2763    lock_time: u32,
2764    vin: &[OutPoint],
2765    value: Zatoshis,
2766    taddr: &TransparentAddress,
2767) -> (ScannedBlock<<DbT as WalletRead>::AccountId>, OutPoint)
2768where
2769    DbT: WalletRead,
2770    <DbT as WalletRead>::Error: std::fmt::Debug,
2771    <DbT as WalletRead>::AccountId:
2772        ConditionallySelectable + Default + Ord + std::hash::Hash + Send + Sync + 'static,
2773{
2774    /// The block subsidy is immaterial to what is under test; any value the miner may claim
2775    /// will do.
2776    const MINER_REWARD: Zatoshis = Zatoshis::const_from_u64(625_000_000);
2777    const MINER_ADDR: TransparentAddress = TransparentAddress::PublicKeyHash([0xf5; 20]);
2778
2779    let payment = fake_transparent_payment_tx(lock_time, vin, value, taddr);
2780    let outpoint = OutPoint::new(payment.txid().into(), 0);
2781    let block = Block::from_parts(
2782        BlockHeaderData {
2783            version: 4,
2784            prev_block: BlockHash([0; 32]),
2785            merkle_root: [0; 32],
2786            final_sapling_root: [0; 32],
2787            time: 0,
2788            bits: 0,
2789            nonce: [0; 32],
2790            solution: vec![],
2791        }
2792        .freeze()
2793        .unwrap(),
2794        NonEmpty::from((
2795            fake_transparent_coinbase_tx(lock_time, MINER_REWARD, &MINER_ADDR),
2796            vec![payment],
2797        )),
2798        height,
2799    );
2800
2801    // The block is scanned in isolation, so the note commitment trees are treated as empty as
2802    // of the immediately preceding block. The block contains no shielded outputs, so they
2803    // remain empty afterwards.
2804    let prior_block_metadata = BlockMetadata::from_parts(
2805        height - 1,
2806        BlockHash([0; 32]),
2807        Some(0),
2808        #[cfg(feature = "orchard")]
2809        Some(0),
2810        #[cfg(feature = "orchard")]
2811        Some(0),
2812    );
2813
2814    let scanning_keys =
2815        ScanningKeys::from_account_ufvks(wallet.get_unified_full_viewing_keys().unwrap());
2816    let (header, vtx) = decrypt_block(network, block, &scanning_keys);
2817    let scanned = scan_block(
2818        network,
2819        height,
2820        &header,
2821        vtx,
2822        &scanning_keys,
2823        &SpendIdentifiers::unspent(wallet).unwrap(),
2824        Some(&prior_block_metadata),
2825        |addr| {
2826            wallet
2827                .get_transparent_address_metadata(account_id, addr)
2828                .map(|meta| meta.map(|m| (account_id, m.source().scope())))
2829        },
2830    )
2831    .expect("scanning the block succeeds");
2832
2833    // The scanner must have detected the payment, and nothing from the coinbase.
2834    assert_matches!(
2835        scanned
2836            .transactions()
2837            .iter()
2838            .flat_map(|wtx| wtx.transparent_outputs())
2839            .collect::<Vec<_>>()
2840            .as_slice(),
2841        [output] if output.outpoint() == &outpoint && output.txout().value() == value
2842    );
2843
2844    (scanned, outpoint)
2845}
2846
2847/// Scans a full block containing a transparent output that pays a wallet address, and verifies
2848/// that persisting the scanned block via [`WalletWrite::put_blocks`] records that output as a
2849/// UTXO belonging to the wallet.
2850pub fn scan_full_block_persists_transparent_outputs<DSF>(dsf: DSF)
2851where
2852    DSF: DataStoreFactory,
2853    <<DSF as DataStoreFactory>::DataStore as WalletRead>::AccountId:
2854        ConditionallySelectable + Default + Ord + std::hash::Hash + Send + Sync + 'static,
2855{
2856    let mut st = TestBuilder::new()
2857        .with_data_store_factory(dsf)
2858        .with_account_from_sapling_activation(BlockHash([0; 32]))
2859        .build();
2860
2861    let account = st.test_account().unwrap();
2862    let account_id = account.id();
2863    let h = account.birthday().height() + 1;
2864    let taddr = wallet_taddr(st.wallet(), account_id);
2865
2866    st.wallet_mut().update_chain_tip(h).unwrap();
2867
2868    // The wallet must not already know of any output at this address.
2869    assert_matches!(
2870        st.wallet().get_transparent_balances(
2871            account_id,
2872            TargetHeight::from(h + 1),
2873            ConfirmationsPolicy::MIN,
2874        ),
2875        Ok(balances) if balances.is_empty()
2876    );
2877
2878    let value = Zatoshis::const_from_u64(100000);
2879    let network = *st.network();
2880    let (scanned, outpoint) =
2881        scan_transparent_payment_block(st.wallet(), &network, account_id, h, 1, &[], value, &taddr);
2882
2883    st.wallet_mut()
2884        .put_blocks(&ChainState::empty(h - 1, BlockHash([0; 32])), vec![scanned])
2885        .unwrap();
2886
2887    // The scanned output must now be a UTXO of the wallet.
2888    let target_height = TargetHeight::from(h + 1);
2889    assert_matches!(
2890        st.wallet()
2891            .get_unspent_transparent_output(&outpoint, target_height),
2892        Ok(Some(ret))
2893        if ret.txout().value() == value && ret.mined_height() == Some(h)
2894    );
2895    assert_matches!(
2896        st.wallet().get_spendable_transparent_outputs(
2897            &taddr,
2898            target_height,
2899            ConfirmationsPolicy::MIN,
2900            CoinbaseFilter::AllTransparentOutputs,
2901            LockFilter::Policy(&LockedInputPolicy::Exclude),
2902        ).as_deref(),
2903        Ok([ret]) if ret.outpoint() == &outpoint
2904    );
2905    assert_matches!(
2906        st.wallet().get_transparent_balances(
2907            account_id,
2908            target_height,
2909            ConfirmationsPolicy::MIN,
2910        ),
2911        Ok(balances) if balances.get(&taddr).map(|(_, b)| b.spendable_value()) == Some(value)
2912    );
2913}
2914
2915/// Scans a full block that pays a wallet transparent address, then a full block that spends the
2916/// resulting output, and verifies that the spend is detected.
2917///
2918/// The wallet already tracks the outpoint when the spending block is scanned, so the spend is
2919/// matched directly against its tracked outputs rather than resolved through the spend map.
2920pub fn scan_full_block_detects_transparent_spend<DSF>(dsf: DSF)
2921where
2922    DSF: DataStoreFactory,
2923    <<DSF as DataStoreFactory>::DataStore as WalletRead>::AccountId:
2924        ConditionallySelectable + Default + Ord + std::hash::Hash + Send + Sync + 'static,
2925{
2926    let mut st = TestBuilder::new()
2927        .with_data_store_factory(dsf)
2928        .with_account_from_sapling_activation(BlockHash([0; 32]))
2929        .build();
2930
2931    let account = st.test_account().unwrap();
2932    let account_id = account.id();
2933    let h = account.birthday().height() + 1;
2934    let taddr = wallet_taddr(st.wallet(), account_id);
2935    let value = Zatoshis::const_from_u64(100000);
2936    let network = *st.network();
2937
2938    st.wallet_mut().update_chain_tip(h + 1).unwrap();
2939
2940    let (received, funded_outpoint) =
2941        scan_transparent_payment_block(st.wallet(), &network, account_id, h, 1, &[], value, &taddr);
2942    st.wallet_mut()
2943        .put_blocks(
2944            &ChainState::empty(h - 1, BlockHash([0; 32])),
2945            vec![received],
2946        )
2947        .unwrap();
2948
2949    assert_matches!(
2950        st.wallet().get_transparent_output(&funded_outpoint, None),
2951        Ok(Some(utxo)) if utxo.txout().value() == value,
2952        "the output must be recorded when the block creating it is scanned",
2953    );
2954
2955    // Scanning the spending block must now detect the spend directly.
2956    let (spending, _) = scan_transparent_payment_block(
2957        st.wallet(),
2958        &network,
2959        account_id,
2960        h + 1,
2961        2,
2962        std::slice::from_ref(&funded_outpoint),
2963        value,
2964        &taddr,
2965    );
2966    assert_matches!(
2967        spending
2968            .transactions()
2969            .iter()
2970            .flat_map(|wtx| wtx.transparent_spends())
2971            .collect::<Vec<_>>()
2972            .as_slice(),
2973        [spend] if spend.outpoint() == &funded_outpoint,
2974        "the scanner must report the spend of the wallet's output",
2975    );
2976
2977    st.wallet_mut()
2978        .put_blocks(&ChainState::empty(h, BlockHash([0; 32])), vec![spending])
2979        .unwrap();
2980
2981    assert_matches!(
2982        st.wallet().get_transparent_output(&funded_outpoint, None),
2983        Ok(Some(_)),
2984        "the output must remain known to the wallet after being spent",
2985    );
2986    assert_matches!(
2987        st.wallet()
2988            .get_unspent_transparent_output(&funded_outpoint, TargetHeight::from(h + 2)),
2989        Ok(None),
2990        "the output must be recorded as spent once its spend has been scanned",
2991    );
2992}
2993
2994/// Scans a full block that spends a wallet transparent output *before* the block that created it,
2995/// and verifies that the spend is resolved once the output is discovered.
2996///
2997/// This is the out-of-order case: at the time the spending block is scanned the wallet does not
2998/// know it holds the output, so the spend must be recorded against the outpoint and applied when
2999/// the earlier block brings the output into the wallet.
3000pub fn scan_full_block_detects_out_of_order_transparent_spend<DSF>(dsf: DSF)
3001where
3002    DSF: DataStoreFactory,
3003    <<DSF as DataStoreFactory>::DataStore as WalletRead>::AccountId:
3004        ConditionallySelectable + Default + Ord + std::hash::Hash + Send + Sync + 'static,
3005{
3006    let mut st = TestBuilder::new()
3007        .with_data_store_factory(dsf)
3008        .with_account_from_sapling_activation(BlockHash([0; 32]))
3009        .build();
3010
3011    let account = st.test_account().unwrap();
3012    let account_id = account.id();
3013    let h = account.birthday().height() + 1;
3014    let taddr = wallet_taddr(st.wallet(), account_id);
3015    let value = Zatoshis::const_from_u64(100000);
3016    let network = *st.network();
3017
3018    st.wallet_mut().update_chain_tip(h + 1).unwrap();
3019
3020    // Build the paying block first so that its outpoint is known, but do not scan it yet.
3021    let (received, funded_outpoint) =
3022        scan_transparent_payment_block(st.wallet(), &network, account_id, h, 1, &[], value, &taddr);
3023
3024    // Scan and persist the block that spends it. The wallet cannot recognize the spend: it does
3025    // not yet know that it holds the output being spent.
3026    let (spending, _) = scan_transparent_payment_block(
3027        st.wallet(),
3028        &network,
3029        account_id,
3030        h + 1,
3031        2,
3032        std::slice::from_ref(&funded_outpoint),
3033        value,
3034        &taddr,
3035    );
3036    assert!(
3037        spending
3038            .transactions()
3039            .iter()
3040            .all(|wtx| wtx.transparent_spends().is_empty()),
3041        "the scanner cannot match a spend of an output the wallet has not yet seen",
3042    );
3043    st.wallet_mut()
3044        .put_blocks(&ChainState::empty(h, BlockHash([0; 32])), vec![spending])
3045        .unwrap();
3046
3047    assert_matches!(
3048        st.wallet().get_transparent_output(&funded_outpoint, None),
3049        Ok(None),
3050        "the wallet must not know of the output before the block creating it is scanned",
3051    );
3052
3053    // Persisting the earlier block brings the output into the wallet, at which point the
3054    // already-recorded spend must be applied to it.
3055    st.wallet_mut()
3056        .put_blocks(
3057            &ChainState::empty(h - 1, BlockHash([0; 32])),
3058            vec![received],
3059        )
3060        .unwrap();
3061
3062    // As in the compact-block case, asserting that the output is known is what keeps the
3063    // "not unspent" assertion below from being satisfied by an output never recorded at all.
3064    assert_matches!(
3065        st.wallet().get_transparent_output(&funded_outpoint, None),
3066        Ok(Some(utxo)) if utxo.txout().value() == value,
3067        "the output must have been recorded when the block creating it was scanned",
3068    );
3069    assert_matches!(
3070        st.wallet()
3071            .get_unspent_transparent_output(&funded_outpoint, TargetHeight::from(h + 2)),
3072        Ok(None),
3073        "the spend observed before the output was discovered must have been resolved",
3074    );
3075}
3076
3077/// Verifies that the transparent outputs written while persisting a batch of scanned blocks are
3078/// rolled back along with the rest of the batch when a later block in the batch is rejected.
3079///
3080/// The batch is made to fail by leaving a gap between its two blocks, which
3081/// [`WalletWrite::put_blocks`] rejects only after the first block has been written.
3082pub fn put_blocks_rolls_back_transparent_outputs<DSF>(dsf: DSF)
3083where
3084    DSF: DataStoreFactory,
3085    <<DSF as DataStoreFactory>::DataStore as WalletRead>::AccountId:
3086        ConditionallySelectable + Default + Ord + std::hash::Hash + Send + Sync + 'static,
3087{
3088    let mut st = TestBuilder::new()
3089        .with_data_store_factory(dsf)
3090        .with_account_from_sapling_activation(BlockHash([0; 32]))
3091        .build();
3092
3093    let account = st.test_account().unwrap();
3094    let account_id = account.id();
3095    let h = account.birthday().height() + 1;
3096    let taddr = wallet_taddr(st.wallet(), account_id);
3097
3098    st.wallet_mut().update_chain_tip(h + 2).unwrap();
3099
3100    let value = Zatoshis::const_from_u64(100000);
3101    let network = *st.network();
3102    let (first, first_outpoint) =
3103        scan_transparent_payment_block(st.wallet(), &network, account_id, h, 1, &[], value, &taddr);
3104    let (discontinuous, discontinuous_outpoint) = scan_transparent_payment_block(
3105        st.wallet(),
3106        &network,
3107        account_id,
3108        h + 2,
3109        2,
3110        &[],
3111        value,
3112        &taddr,
3113    );
3114
3115    assert_matches!(
3116        st.wallet_mut().put_blocks(
3117            &ChainState::empty(h - 1, BlockHash([0; 32])),
3118            vec![first, discontinuous],
3119        ),
3120        Err(_)
3121    );
3122
3123    // Neither block's output may have been committed: the first block's writes must have been
3124    // rolled back along with the failure of the second.
3125    let target_height = TargetHeight::from(h + 3);
3126    for outpoint in [&first_outpoint, &discontinuous_outpoint] {
3127        assert_matches!(
3128            st.wallet()
3129                .get_unspent_transparent_output(outpoint, target_height),
3130            Ok(None)
3131        );
3132    }
3133    assert_matches!(
3134        st.wallet().get_transparent_balances(
3135            account_id,
3136            target_height,
3137            ConfirmationsPolicy::MIN,
3138        ),
3139        Ok(balances) if balances.is_empty()
3140    );
3141}
3142
3143/// Sets up a wallet whose account holds no shielded notes and a single spendable
3144/// transparent UTXO at its default external transparent receiver, returning the test
3145/// state, the account, the funding outpoint, and the UTXO value.
3146///
3147/// The chain is seeded with blocks containing notes that do *not* belong to the wallet,
3148/// so that target/anchor heights resolve while the account remains shielded-empty. This
3149/// isolates the transparent-UTXO selection path.
3150#[allow(clippy::type_complexity)]
3151fn setup_transparent_only_account<DSF>(
3152    dsf: DSF,
3153    cache: impl TestCache,
3154    utxo_value: Zatoshis,
3155) -> (
3156    TestState<impl TestCache, <DSF as DataStoreFactory>::DataStore, LocalNetwork>,
3157    TestAccount<<DSF as DataStoreFactory>::Account>,
3158    OutPoint,
3159)
3160where
3161    DSF: DataStoreFactory,
3162{
3163    let mut st = TestBuilder::new()
3164        .with_data_store_factory(dsf)
3165        .with_block_cache(cache)
3166        .with_account_from_sapling_activation(BlockHash([0; 32]))
3167        .build();
3168
3169    let account = st.test_account().cloned().unwrap();
3170    let uaddr = st
3171        .wallet()
3172        .get_last_generated_address_matching(account.id(), UnifiedAddressRequest::AllAvailableKeys)
3173        .unwrap()
3174        .unwrap();
3175    let taddr = uaddr.transparent().unwrap();
3176
3177    // Seed the chain with notes that do not belong to us so that heights resolve while
3178    // the account remains without any shielded notes.
3179    let not_our_key = ExtendedSpendingKey::master(&[])
3180        .expect("the derivation path yields a valid key")
3181        .to_diversifiable_full_viewing_key();
3182    let not_our_value = Zatoshis::const_from_u64(10000);
3183    let (start_height, _, _) =
3184        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
3185    for _ in 1..10 {
3186        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
3187    }
3188    st.scan_cached_blocks(start_height, 10);
3189
3190    // Fund the account with a single transparent UTXO well above the marginal fee.
3191    let txout = TxOut::new(utxo_value, taddr.script().into());
3192    let height = st.wallet().chain_height().unwrap().unwrap();
3193    let outpoint = OutPoint::fake();
3194    let utxo = WalletTransparentOutput::from_parts(
3195        outpoint.clone(),
3196        txout,
3197        Some(height),
3198        Some(account.id()),
3199        Some(TransparentKeyScope::EXTERNAL),
3200        None,
3201    )
3202    .unwrap();
3203    st.wallet_mut()
3204        .put_received_transparent_utxo(&utxo)
3205        .unwrap();
3206
3207    (st, account, outpoint)
3208}
3209
3210/// Builds a single-payment t->t [`TransactionRequest`] paying `amount` to a fixed
3211/// external transparent recipient.
3212fn t2t_request(network: &LocalNetwork, amount: Zatoshis) -> TransactionRequest {
3213    let recipient = TransparentAddress::PublicKeyHash([7u8; 20]);
3214    TransactionRequest::new(vec![Payment::without_memo(
3215        Address::Transparent(recipient).to_zcash_address(network),
3216        amount,
3217    )])
3218    .unwrap()
3219}
3220
3221/// Regression test enforcing the privacy invariant: with the default
3222/// default spend policy (which permits no transparent spending), a transfer must NOT silently spend
3223/// the account's transparent UTXOs as a fallback. An account holding only transparent
3224/// funds must fail with [`InsufficientFunds`] rather than producing a t->t proposal.
3225///
3226/// [`InsufficientFunds`]: crate::data_api::error::Error::InsufficientFunds
3227pub fn propose_t2t_shielded_only_is_insufficient<DSF>(dsf: DSF, cache: impl TestCache)
3228where
3229    DSF: DataStoreFactory,
3230{
3231    let utxo_value = Zatoshis::const_from_u64(100_000);
3232    let (mut st, account, _outpoint) = setup_transparent_only_account(dsf, cache, utxo_value);
3233
3234    let network = *st.network();
3235    let request = t2t_request(&network, Zatoshis::const_from_u64(40_000));
3236
3237    let input_selector = GreedyInputSelector::new();
3238    let change_strategy =
3239        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling);
3240
3241    let result = st.propose_transfer_with_policy(
3242        account.id(),
3243        &input_selector,
3244        &change_strategy,
3245        request,
3246        ConfirmationsPolicy::MIN,
3247        &SpendPolicy::default(),
3248    );
3249
3250    assert_matches!(
3251        result,
3252        Err(crate::data_api::error::Error::InsufficientFunds { .. }),
3253        "shielded-only policy must not spend transparent UTXOs as a fallback",
3254    );
3255}
3256
3257/// With `TransparentSpendPolicy::any_account_addr` (the legacy `ANY_TADDR` behavior), a
3258/// transfer may spend the account's transparent UTXOs. Verifies that the funding UTXO is
3259/// selected as a transparent input and that the proposal balance is consistent.
3260pub fn propose_t2t_any_account_taddr<DSF>(dsf: DSF, cache: impl TestCache)
3261where
3262    DSF: DataStoreFactory,
3263{
3264    let utxo_value = Zatoshis::const_from_u64(100_000);
3265    let transfer_amount = Zatoshis::const_from_u64(40_000);
3266    let (mut st, account, outpoint) = setup_transparent_only_account(dsf, cache, utxo_value);
3267
3268    let network = *st.network();
3269    let request = t2t_request(&network, transfer_amount);
3270
3271    let input_selector = GreedyInputSelector::new();
3272    let change_strategy =
3273        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling);
3274
3275    let proposal = st
3276        .propose_transfer_with_policy(
3277            account.id(),
3278            &input_selector,
3279            &change_strategy,
3280            request,
3281            ConfirmationsPolicy::MIN,
3282            &SpendPolicy::default().with_transparent(TransparentSpendPolicy::any_account_addr()),
3283        )
3284        .expect("transparent spend must succeed under any-account-address transparent spending");
3285
3286    // A pure t->t transfer is a single step (no ZIP-320 ephemeral roundtrip).
3287    assert_eq!(proposal.steps().len(), 1);
3288    let step = &proposal.steps().head;
3289
3290    assert_eq!(
3291        step.transparent_inputs().len(),
3292        1,
3293        "expected exactly one transparent input selected from the account's UTXOs",
3294    );
3295    assert_eq!(step.transparent_inputs()[0].outpoint(), &outpoint);
3296    assert_eq!(step.transparent_inputs()[0].txout().value(), utxo_value);
3297
3298    // `TransactionBalance::total()` is `change + fee`, which by the balance equation equals
3299    // input total minus the explicit payment.
3300    assert_eq!(
3301        step.balance().total(),
3302        (utxo_value - transfer_amount).unwrap(),
3303    );
3304    assert!(step.balance().fee_required() > Zatoshis::ZERO);
3305    assert!(!step.balance().proposed_change().is_empty());
3306}
3307
3308/// Verifies that `GreedyInputSelector::propose_transaction` successfully re-gathers
3309/// transparent inputs when the initial fee-aware gather's estimate (which accounts only
3310/// for the transparent side of the transaction) turns out to be insufficient once the
3311/// real change strategy accounts for the additional shielded action required by a
3312/// shielded payment recipient.
3313///
3314/// This exercises the `ChangeError::InsufficientFunds` fallback path in
3315/// `GreedyInputSelector::propose_transaction`, which re-invokes
3316/// `InputSource::select_spendable_transparent_outputs` with a corrected `TargetValue`
3317/// when the first gather's reservation proves too small. Funding many small transparent
3318/// UTXOs forces the initial gather to stop with just enough inputs to cover the payment
3319/// under its own (transparent-only) fee estimate; the shielded payment output then pushes
3320/// the real required fee higher, so satisfying the request is only possible by gathering
3321/// additional inputs beyond that initial estimate.
3322pub fn propose_t2shielded_requires_transparent_regather<DSF>(dsf: DSF, cache: impl TestCache)
3323where
3324    DSF: DataStoreFactory,
3325{
3326    let mut st = TestBuilder::new()
3327        .with_data_store_factory(dsf)
3328        .with_block_cache(cache)
3329        .with_account_from_sapling_activation(BlockHash([0; 32]))
3330        .build();
3331
3332    let account = st.test_account().cloned().unwrap();
3333    let uaddr = st
3334        .wallet()
3335        .get_last_generated_address_matching(account.id(), UnifiedAddressRequest::AllAvailableKeys)
3336        .unwrap()
3337        .unwrap();
3338    let taddr = *uaddr.transparent().unwrap();
3339
3340    // Seed the chain with notes that do not belong to us so that heights resolve.
3341    let not_our_key = ExtendedSpendingKey::master(&[])
3342        .expect("the derivation path yields a valid key")
3343        .to_diversifiable_full_viewing_key();
3344    let not_our_value = Zatoshis::const_from_u64(10_000);
3345    let (start_height, _, _) =
3346        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
3347    for _ in 1..10 {
3348        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
3349    }
3350    st.scan_cached_blocks(start_height, 10);
3351
3352    // Fund the account with many small transparent UTXOs, none of which alone are
3353    // remotely close to the payment amount, so that gathering enough of them to satisfy
3354    // the (larger, corrected) real requirement remains possible.
3355    let dust_value = Zatoshis::const_from_u64(10_000);
3356    let n_dust = 30;
3357    let height = st.wallet().chain_height().unwrap().unwrap();
3358    for i in 0..n_dust {
3359        let mut hash = [0u8; 32];
3360        hash[..4].copy_from_slice(&(i as u32).to_le_bytes());
3361        let utxo = WalletTransparentOutput::from_parts(
3362            OutPoint::new(hash, 0),
3363            TxOut::new(dust_value, taddr.script().into()),
3364            Some(height),
3365            Some(account.id()),
3366            Some(TransparentKeyScope::EXTERNAL),
3367            None,
3368        )
3369        .unwrap();
3370        st.wallet_mut()
3371            .put_received_transparent_utxo(&utxo)
3372            .unwrap();
3373    }
3374
3375    // Pay a shielded recipient. The initial transparent gather's fee estimate accounts
3376    // only for the transparent inputs it selects; it does not (and cannot, since the
3377    // shielded payment output isn't known to `InputSource::select_spendable_transparent_outputs`)
3378    // account for the additional sapling action this payment requires, so the first pass
3379    // undershoots and a re-gather is required to actually satisfy the request.
3380    let network = *st.network();
3381    let recipient = ExtendedSpendingKey::master(&[1u8; 32])
3382        .expect("the derivation path yields a valid key")
3383        .to_diversifiable_full_viewing_key()
3384        .default_address()
3385        .1;
3386    let payment_amount = Zatoshis::const_from_u64(50_000);
3387    let request = TransactionRequest::new(vec![Payment::without_memo(
3388        Address::Sapling(Box::new(recipient)).to_zcash_address(&network),
3389        payment_amount,
3390    )])
3391    .unwrap();
3392
3393    let input_selector = GreedyInputSelector::new();
3394    let change_strategy =
3395        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling);
3396
3397    // Independently reproduce the initial gather that `GreedyInputSelector` will perform
3398    // (bounded only by the payment amount, since that's the only information available
3399    // before the shielded payment output's fee contribution is known). Comparing this to
3400    // the transparent inputs actually used by the successful proposal below demonstrates
3401    // that the proposal could only have succeeded via the re-gather fallback: the initial
3402    // gather's own reservation ignores the extra sapling action the payment requires, so
3403    // it cannot by itself have covered the real, higher requirement.
3404    let initial_gather = st
3405        .wallet()
3406        .select_spendable_transparent_outputs(
3407            account.id(),
3408            TargetHeight::from(height + 1),
3409            ConfirmationsPolicy::MIN,
3410            CoinbaseFilter::NonCoinbaseOnly,
3411            None,
3412            TargetValue::AtLeast(payment_amount),
3413            usize::MAX,
3414            &StandardFeeRule::Zip317,
3415            LockFilter::Policy(&LockedInputPolicy::Exclude),
3416        )
3417        .expect("initial gather should succeed");
3418    let initial_gather_value: Zatoshis = initial_gather
3419        .iter()
3420        .map(|u| u.value())
3421        .fold(Zatoshis::ZERO, |acc, v| (acc + v).unwrap());
3422
3423    let proposal = st
3424        .propose_transfer_with_policy(
3425            account.id(),
3426            &input_selector,
3427            &change_strategy,
3428            request,
3429            ConfirmationsPolicy::MIN,
3430            &SpendPolicy::default().with_transparent(TransparentSpendPolicy::any_account_addr()),
3431        )
3432        .expect(
3433            "transparent spend should succeed via the re-gather fallback despite the \
3434             initial gather's fee estimate being insufficient",
3435        );
3436
3437    let step = &proposal.steps().head;
3438    let gathered_value: Zatoshis = step
3439        .transparent_inputs()
3440        .iter()
3441        .map(|i| i.txout().value())
3442        .fold(Zatoshis::ZERO, |acc, v| (acc + v).unwrap());
3443    assert!(
3444        gathered_value > initial_gather_value,
3445        "the successful proposal should have gathered more transparent value ({}) than \
3446         the insufficient initial gather ({})",
3447        u64::from(gathered_value),
3448        u64::from(initial_gather_value),
3449    );
3450    assert!(step.balance().fee_required() > Zatoshis::ZERO);
3451}
3452
3453/// Verifies that `GreedyInputSelector::with_shielding_block_space_percent` also bounds the
3454/// transparent gather performed for general (non-shielding) transfers, not just shielding.
3455///
3456/// Funds more dust UTXOs than fit within a 1%-of-block-space cap, and requests a payment
3457/// whose post-fee cost can only be met by exceeding that cap. The gather must stop at the
3458/// cap rather than consuming every eligible UTXO, so the proposal fails with
3459/// [`InsufficientFunds`] instead of succeeding with an uncapped number of transparent inputs.
3460///
3461/// [`InsufficientFunds`]: crate::data_api::error::Error::InsufficientFunds
3462pub fn propose_transfer_transparent_input_cap<DSF>(dsf: DSF, cache: impl TestCache)
3463where
3464    DSF: DataStoreFactory,
3465{
3466    // At 1% of block space the cap is (2_000_000 * 1 / 100) / 150 = 133 inputs.
3467    const BLOCK_SPACE_PERCENT: u32 = 1;
3468    const CAP: usize = 133;
3469    const NUM_UTXOS: usize = CAP + 7; // 140; more than enough to exceed the cap.
3470    const DUST_VALUE: u64 = 10_000;
3471
3472    let mut st = TestBuilder::new()
3473        .with_data_store_factory(dsf)
3474        .with_block_cache(cache)
3475        .with_account_from_sapling_activation(BlockHash([0; 32]))
3476        .build();
3477
3478    let account = st.test_account().cloned().unwrap();
3479    let uaddr = st
3480        .wallet()
3481        .get_last_generated_address_matching(account.id(), UnifiedAddressRequest::AllAvailableKeys)
3482        .unwrap()
3483        .unwrap();
3484    let taddr = *uaddr.transparent().unwrap();
3485
3486    // Seed the chain with notes that do not belong to us so that heights resolve.
3487    let not_our_key = ExtendedSpendingKey::master(&[])
3488        .expect("the derivation path yields a valid key")
3489        .to_diversifiable_full_viewing_key();
3490    let not_our_value = Zatoshis::const_from_u64(10_000);
3491    let (start_height, _, _) =
3492        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
3493    for _ in 1..10 {
3494        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
3495    }
3496    st.scan_cached_blocks(start_height, 10);
3497
3498    // Fund the account with more dust UTXOs than fit within the cap.
3499    let height = st.wallet().chain_height().unwrap().unwrap();
3500    for i in 0..NUM_UTXOS {
3501        let mut hash = [0u8; 32];
3502        hash[..4].copy_from_slice(&(i as u32).to_le_bytes());
3503        let utxo = WalletTransparentOutput::from_parts(
3504            OutPoint::new(hash, 0),
3505            TxOut::new(Zatoshis::const_from_u64(DUST_VALUE), taddr.script().into()),
3506            Some(height),
3507            Some(account.id()),
3508            Some(TransparentKeyScope::EXTERNAL),
3509            None,
3510        )
3511        .unwrap();
3512        st.wallet_mut()
3513            .put_received_transparent_utxo(&utxo)
3514            .unwrap();
3515    }
3516
3517    // Request a post-fee amount that is only reachable by gathering more than `CAP` inputs
3518    // (with the cap, `CAP` inputs net `DUST_VALUE * CAP - 5_000 * CAP = 5_000 * CAP`
3519    // post-fee; requesting exactly that much would succeed, so request more).
3520    let payment_amount = Zatoshis::const_from_u64(5_000 * (CAP as u64) + DUST_VALUE);
3521
3522    let network = *st.network();
3523    let request = t2t_request(&network, payment_amount);
3524
3525    let input_selector =
3526        GreedyInputSelector::new().with_shielding_block_space_percent(BLOCK_SPACE_PERCENT);
3527    let change_strategy =
3528        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling);
3529
3530    let result = st.propose_transfer_with_policy(
3531        account.id(),
3532        &input_selector,
3533        &change_strategy,
3534        request,
3535        ConfirmationsPolicy::MIN,
3536        &SpendPolicy::default().with_transparent(TransparentSpendPolicy::any_account_addr()),
3537    );
3538
3539    // The gather stops at `CAP` inputs, whose value the error reports as available; the
3540    // request needs the payment plus one logical action per gathered input.
3541    let expected_available = Zatoshis::const_from_u64(DUST_VALUE * (CAP as u64));
3542    let expected_required = (payment_amount
3543        + (zip317::marginal_fee(st.network(), height + 1) * (CAP as u64)).unwrap())
3544    .unwrap();
3545    assert_matches!(
3546        result,
3547        Err(crate::data_api::error::Error::InsufficientFunds { available, required })
3548            if available == expected_available && required == expected_required,
3549        "the transparent gather should stop at the input cap rather than consuming every \
3550         eligible dust UTXO, so the request should fail with the capped inputs reported as \
3551         available rather than succeed with an uncapped number of inputs",
3552    );
3553}
3554
3555/// With a `TransparentSource::FromAddresses` transparent source, only the explicitly named transparent
3556/// addresses are eligible. Funds two of the account's external receivers but names only
3557/// one; the proposal must select solely from the named address.
3558pub fn propose_t2t_from_addresses<DSF>(dsf: DSF, cache: impl TestCache)
3559where
3560    DSF: DataStoreFactory,
3561{
3562    let mut st = TestBuilder::new()
3563        .with_data_store_factory(dsf)
3564        .with_block_cache(cache)
3565        .with_account_from_sapling_activation(BlockHash([0; 32]))
3566        .build();
3567
3568    let account = st.test_account().cloned().unwrap();
3569
3570    // Seed the chain with notes that do not belong to us so heights resolve.
3571    let not_our_key = ExtendedSpendingKey::master(&[])
3572        .expect("the derivation path yields a valid key")
3573        .to_diversifiable_full_viewing_key();
3574    let not_our_value = Zatoshis::const_from_u64(10000);
3575    let (start_height, _, _) =
3576        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
3577    for _ in 1..10 {
3578        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
3579    }
3580    st.scan_cached_blocks(start_height, 10);
3581
3582    // Enumerate two distinct external transparent receivers belonging to the account.
3583    let external_taddrs = st
3584        .wallet()
3585        .get_transparent_receivers(account.id(), false, true)
3586        .unwrap();
3587    let mut taddrs_by_index = external_taddrs
3588        .into_iter()
3589        .filter_map(|(addr, meta)| meta.address_index().map(|i| (i, addr)))
3590        .collect::<BTreeMap<_, _>>()
3591        .into_values();
3592    let addr_named = taddrs_by_index.next().expect("at least one external taddr");
3593    let addr_other = taddrs_by_index
3594        .next()
3595        .expect("at least two external taddrs");
3596
3597    // Fund both receivers with a spendable UTXO each. The unnamed address's UTXO is
3598    // inserted first AND holds strictly more value than the named address's, so that if
3599    // the address filter were not enforced, the value-descending gather would select the
3600    // unnamed address's UTXO (which alone covers the payment) and stop -- making this test
3601    // fail. The named UTXO must be selected by policy, not merely by gather order.
3602    let named_value = Zatoshis::const_from_u64(100_000);
3603    let other_value = Zatoshis::const_from_u64(150_000);
3604    let height = st.wallet().chain_height().unwrap().unwrap();
3605    let named_outpoint = OutPoint::new([1u8; 32], 0);
3606    let other_outpoint = OutPoint::new([2u8; 32], 0);
3607    for (addr, outpoint, value) in [
3608        (addr_other, other_outpoint.clone(), other_value),
3609        (addr_named, named_outpoint.clone(), named_value),
3610    ] {
3611        let utxo = WalletTransparentOutput::from_parts(
3612            outpoint,
3613            TxOut::new(value, addr.script().into()),
3614            Some(height),
3615            Some(account.id()),
3616            Some(TransparentKeyScope::EXTERNAL),
3617            None,
3618        )
3619        .unwrap();
3620        st.wallet_mut()
3621            .put_received_transparent_utxo(&utxo)
3622            .unwrap();
3623    }
3624
3625    let network = *st.network();
3626    let request = t2t_request(&network, Zatoshis::const_from_u64(40_000));
3627
3628    let input_selector = GreedyInputSelector::new();
3629    let change_strategy =
3630        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling);
3631
3632    let proposal = st
3633        .propose_transfer_with_policy(
3634            account.id(),
3635            &input_selector,
3636            &change_strategy,
3637            request,
3638            ConfirmationsPolicy::MIN,
3639            &SpendPolicy::default()
3640                .with_transparent(TransparentSpendPolicy::from_one_address(addr_named)),
3641        )
3642        .expect("transparent spend from named address must succeed");
3643
3644    let step = &proposal.steps().head;
3645    let selected: Vec<&OutPoint> = step
3646        .transparent_inputs()
3647        .iter()
3648        .map(|i| i.outpoint())
3649        .collect();
3650    assert!(
3651        selected.contains(&&named_outpoint),
3652        "the named address's UTXO must be selected",
3653    );
3654    assert!(
3655        !selected.contains(&&other_outpoint),
3656        "an unnamed address's UTXO must not be selected",
3657    );
3658}
3659
3660/// Verifies that the value-bounded `select_spendable_transparent_outputs` gather returns
3661/// only enough UTXOs to cover the requested `TargetValue`, rather than every spendable
3662/// output held by the account. This is the behavior that prevents wallets with large
3663/// numbers of small transparent UTXOs (e.g. recovered `zcashd` imports) from falling over
3664/// when a small transfer is requested.
3665pub fn value_bounded_transparent_gather<DSF>(dsf: DSF, cache: impl TestCache)
3666where
3667    DSF: DataStoreFactory,
3668{
3669    let mut st = TestBuilder::new()
3670        .with_data_store_factory(dsf)
3671        .with_block_cache(cache)
3672        .with_account_from_sapling_activation(BlockHash([0; 32]))
3673        .build();
3674
3675    let account = st.test_account().cloned().unwrap();
3676    let uaddr = st
3677        .wallet()
3678        .get_last_generated_address_matching(account.id(), UnifiedAddressRequest::AllAvailableKeys)
3679        .unwrap()
3680        .unwrap();
3681    let taddr = *uaddr.transparent().unwrap();
3682
3683    // Seed the chain with notes that do not belong to us so that heights resolve.
3684    let not_our_key = ExtendedSpendingKey::master(&[])
3685        .expect("the derivation path yields a valid key")
3686        .to_diversifiable_full_viewing_key();
3687    let not_our_value = Zatoshis::const_from_u64(10_000);
3688    let (start_height, _, _) =
3689        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
3690    for _ in 1..10 {
3691        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
3692    }
3693    st.scan_cached_blocks(start_height, 10);
3694
3695    // Fund the account with many small dust UTXOs. Each is well above the marginal fee
3696    // (1_000 zats) so it's spendable, but tiny relative to the total. A naive "return
3697    // everything" gather would load all of these into memory; the value-bounded gather
3698    // should only return enough to cover the request.
3699    let dust_value = Zatoshis::const_from_u64(10_000);
3700    let n_dust = 50;
3701    let height = st.wallet().chain_height().unwrap().unwrap();
3702    for i in 0..n_dust {
3703        let mut hash = [0u8; 32];
3704        hash[..4].copy_from_slice(&(i as u32).to_le_bytes());
3705        let utxo = WalletTransparentOutput::from_parts(
3706            OutPoint::new(hash, 0),
3707            TxOut::new(dust_value, taddr.script().into()),
3708            Some(height),
3709            Some(account.id()),
3710            Some(TransparentKeyScope::EXTERNAL),
3711            None,
3712        )
3713        .unwrap();
3714        st.wallet_mut()
3715            .put_received_transparent_utxo(&utxo)
3716            .unwrap();
3717    }
3718
3719    // Request 30_000 zats — 3x a single dust UTXO, but a small fraction of the total.
3720    let target = Zatoshis::const_from_u64(30_000);
3721    let target_height = TargetHeight::from(height + 1);
3722
3723    let bound = st
3724        .wallet()
3725        .select_spendable_transparent_outputs(
3726            account.id(),
3727            target_height,
3728            ConfirmationsPolicy::MIN,
3729            CoinbaseFilter::AllTransparentOutputs,
3730            None,
3731            TargetValue::AtLeast(target),
3732            usize::MAX,
3733            &StandardFeeRule::Zip317,
3734            LockFilter::Policy(&LockedInputPolicy::Exclude),
3735        )
3736        .expect("value-bounded gather should succeed");
3737
3738    // The gather should return enough UTXOs to cover the target post-fee, not all 50.
3739    // Each UTXO is 10_000 zats. Under ZIP 317, `k` P2PKH inputs cost
3740    // `5_000 * max(2, k)` zats in marginal fee, so the post-fee value of the first `k`
3741    // gathered UTXOs is `10_000 * k - 5_000 * max(2, k)`. This first reaches the
3742    // 30_000-zat target at `k = 6` (60_000 - 30_000 = 30_000), one more than the 5
3743    // UTXOs (50_000 - 25_000 = 25_000) that would still fall short.
3744    assert!(
3745        !bound.is_empty(),
3746        "value-bounded gather should return at least one UTXO",
3747    );
3748    assert_eq!(
3749        bound.len(),
3750        6,
3751        "value-bounded gather should return exactly 6 UTXOs (10_000 zats each) to cover \
3752         30_000 zats net of the ZIP 317 marginal fee for 6 P2PKH inputs",
3753    );
3754    assert!(
3755        bound.len() < n_dust,
3756        "value-bounded gather should not return all {n_dust} UTXOs (returned {})",
3757        bound.len(),
3758    );
3759    // The summed value should meet the target.
3760    let total: Zatoshis = bound
3761        .iter()
3762        .map(|u| u.value())
3763        .fold(Zatoshis::ZERO, |acc, v| (acc + v).unwrap());
3764    assert!(
3765        total >= target,
3766        "value-bounded gather should cover the target (got {}, want >= {})",
3767        u64::from(total),
3768        u64::from(target),
3769    );
3770
3771    // AllFunds should return all eligible UTXOs.
3772    let all = st
3773        .wallet()
3774        .select_spendable_transparent_outputs(
3775            account.id(),
3776            target_height,
3777            ConfirmationsPolicy::MIN,
3778            CoinbaseFilter::AllTransparentOutputs,
3779            None,
3780            TargetValue::AllFunds(MaxSpendMode::MaxSpendable),
3781            usize::MAX,
3782            &StandardFeeRule::Zip317,
3783            LockFilter::Policy(&LockedInputPolicy::Exclude),
3784        )
3785        .expect("AllFunds gather should succeed");
3786    assert_eq!(all.len(), n_dust);
3787}
3788
3789/// Tests that [`WalletWrite::reserve_next_n_internal_addresses`] reserves sequential
3790/// internal-scope (change) addresses, that reservation observes the internal-scope gap
3791/// limit, and that internal-scope reservations are accounted independently of
3792/// ephemeral-scope reservations.
3793///
3794/// This test expects the data store to be configured with the default gap limits, under
3795/// which the internal-scope gap limit is 5.
3796///
3797/// The `is_reached_gap_limit` predicate must return `true` if and only if the provided
3798/// error is the backend's exact "reached gap limit" error variant, the scope reported by
3799/// that error is [`TransparentKeyScope::INTERNAL`], and the address index reported by that
3800/// error equals the provided expected index. It must not match any other error. (A
3801/// predicate is used because this test cannot name the backend's concrete error type
3802/// without inverting the crate dependency.)
3803pub fn reserve_next_n_internal_addresses_gap_limit<DSF>(
3804    dsf: DSF,
3805    cache: impl TestCache,
3806    is_reached_gap_limit: impl Fn(
3807        &<DSF::DataStore as crate::data_api::WalletRead>::Error,
3808        DSF::AccountId,
3809        u32,
3810    ) -> bool,
3811) where
3812    DSF: DataStoreFactory,
3813{
3814    let mut st = TestBuilder::new()
3815        .with_data_store_factory(dsf)
3816        .with_block_cache(cache)
3817        .with_account_from_sapling_activation(BlockHash([0; 32]))
3818        .build();
3819    let account_id = st.test_account().cloned().unwrap().id();
3820
3821    // Seed the chain so that a chain height is known; address reservation records the
3822    // exposure height of each reserved address.
3823    let not_our_key = ExtendedSpendingKey::master(&[])
3824        .expect("the derivation path yields a valid key")
3825        .to_diversifiable_full_viewing_key();
3826    let not_our_value = Zatoshis::const_from_u64(10000);
3827    let (start_height, _, _) =
3828        st.generate_next_block(&not_our_key, AddressType::DefaultExternal, not_our_value);
3829    st.scan_cached_blocks(start_height, 1);
3830
3831    // Reserving internal addresses yields distinct, sequentially-indexed addresses derived
3832    // under the internal (change) key scope.
3833    let reserved = st
3834        .wallet_mut()
3835        .reserve_next_n_internal_addresses(account_id, 3)
3836        .unwrap();
3837    assert_eq!(reserved.len(), 3);
3838    for (i, (_, meta)) in reserved.iter().enumerate() {
3839        assert_eq!(meta.scope(), Some(TransparentKeyScope::INTERNAL));
3840        assert_eq!(
3841            meta.address_index(),
3842            Some(NonHardenedChildIndex::const_from_index(
3843                u32::try_from(i).unwrap()
3844            )),
3845        );
3846    }
3847    // None of the reserved addresses have received funds, so the gap cannot advance: with
3848    // the default internal-scope gap limit of 5, only two more addresses may be reserved.
3849    // Reservation continues at the next sequential indices, so the returned addresses are
3850    // distinct from those of the first batch.
3851    let more = st
3852        .wallet_mut()
3853        .reserve_next_n_internal_addresses(account_id, 2)
3854        .unwrap();
3855    assert_eq!(more.len(), 2);
3856    for (i, (_, meta)) in more.iter().enumerate() {
3857        assert_eq!(meta.scope(), Some(TransparentKeyScope::INTERNAL));
3858        assert_eq!(
3859            meta.address_index(),
3860            Some(NonHardenedChildIndex::const_from_index(
3861                u32::try_from(reserved.len() + i).unwrap()
3862            )),
3863        );
3864    }
3865    let unique_addrs = reserved
3866        .iter()
3867        .chain(more.iter())
3868        .map(|(a, _)| *a)
3869        .collect::<HashSet<_>>();
3870    assert_eq!(unique_addrs.len(), reserved.len() + more.len());
3871
3872    assert_matches!(
3873        st.wallet_mut().reserve_next_n_internal_addresses(account_id, 1),
3874        Err(e) if is_reached_gap_limit(&e, account_id, 5)
3875    );
3876
3877    // Internal-scope reservations must not consume ephemeral-scope gap space.
3878    let ephemeral = st
3879        .wallet_mut()
3880        .reserve_next_n_ephemeral_addresses(account_id, 1)
3881        .unwrap();
3882    assert_eq!(ephemeral[0].1.scope(), Some(TransparentKeyScope::EPHEMERAL),);
3883    assert_eq!(
3884        ephemeral[0].1.address_index(),
3885        Some(NonHardenedChildIndex::const_from_index(0)),
3886    );
3887}
3888
3889/// Tests the full lifecycle of a t->t transfer with transparent change: a change strategy
3890/// configured with [`TransparentChangePolicy::TransparentChangeAllowed`] must propose a
3891/// non-ephemeral transparent change output, and transaction creation must send that change
3892/// to a previously-unexposed internal-scope (change) transparent address of the spending
3893/// account, where it is recorded as received and becomes spendable once mined.
3894///
3895/// [`TransparentChangePolicy::TransparentChangeAllowed`]: crate::fees::TransparentChangePolicy::TransparentChangeAllowed
3896pub fn propose_t2t_with_transparent_change<DSF>(dsf: DSF, cache: impl TestCache)
3897where
3898    DSF: DataStoreFactory,
3899{
3900    let utxo_value = Zatoshis::const_from_u64(100_000);
3901    let transfer_amount = Zatoshis::const_from_u64(40_000);
3902    let (mut st, account, outpoint) = setup_transparent_only_account(dsf, cache, utxo_value);
3903
3904    let network = *st.network();
3905    let request = t2t_request(&network, transfer_amount);
3906
3907    let input_selector = GreedyInputSelector::new();
3908    let change_strategy =
3909        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling)
3910            .with_transparent_change_policy(TransparentChangePolicy::TransparentChangeAllowed);
3911
3912    let proposal = st
3913        .propose_transfer_with_policy(
3914            account.id(),
3915            &input_selector,
3916            &change_strategy,
3917            request,
3918            ConfirmationsPolicy::MIN,
3919            &SpendPolicy::default().with_transparent(TransparentSpendPolicy::any_account_addr()),
3920        )
3921        .expect("t->t proposal with transparent change must succeed");
3922
3923    // A t->t transfer with non-ephemeral transparent change is a single step.
3924    assert_eq!(proposal.steps().len(), 1);
3925    let step = &proposal.steps().head;
3926    assert_eq!(step.transparent_inputs().len(), 1);
3927    assert_eq!(step.transparent_inputs()[0].outpoint(), &outpoint);
3928    assert!(step.shielded_inputs().is_none());
3929
3930    // Under ZIP 317, one P2PKH input and two P2PKH outputs (the payment plus the change
3931    // output) require `5_000 * max(1, 2) = 10_000` zats in fees.
3932    let expected_fee = Zatoshis::const_from_u64(10_000);
3933    let expected_change = ((utxo_value - transfer_amount).unwrap() - expected_fee).unwrap();
3934    assert_eq!(step.balance().fee_required(), expected_fee);
3935    assert_eq!(
3936        step.balance().proposed_change(),
3937        [ChangeValue::transparent(expected_change)],
3938    );
3939    assert!(!step.balance().proposed_change()[0].is_ephemeral());
3940
3941    // A proposal containing a transparent change output must survive a serialization
3942    // round trip.
3943    super::check_proposal_serialization_roundtrip(&network, st.wallet(), &proposal);
3944
3945    // Creating the transaction should reserve an internal-scope address for the change.
3946    let txids = st
3947        .create_proposed_transactions::<Infallible, _, Infallible, _>(
3948            account.usk(),
3949            OvkPolicy::Sender,
3950            &proposal,
3951        )
3952        .expect("transaction creation must succeed");
3953    assert_eq!(txids.len(), 1);
3954    let txid = txids.head;
3955
3956    // The transaction must be fully transparent, with exactly the payment and change outputs.
3957    let tx = st
3958        .wallet()
3959        .get_transaction(txid)
3960        .unwrap()
3961        .expect("the created transaction is retrievable");
3962    assert!(tx.sapling_bundle().is_none());
3963    #[cfg(feature = "orchard")]
3964    assert!(tx.orchard_bundle().is_none());
3965    let bundle = tx
3966        .transparent_bundle()
3967        .expect("the transaction has a transparent bundle");
3968    assert_eq!(bundle.vin.len(), 1);
3969    assert_eq!(bundle.vout.len(), 2);
3970
3971    // Identify the change output as the output that does not pay the external recipient.
3972    let payment_recipient = TransparentAddress::PublicKeyHash([7u8; 20]);
3973    let change_outputs: Vec<_> = bundle
3974        .vout
3975        .iter()
3976        .filter(|out| out.recipient_address() != Some(payment_recipient))
3977        .collect();
3978    assert_eq!(change_outputs.len(), 1);
3979    let change_output = change_outputs[0];
3980    assert_eq!(change_output.value(), expected_change);
3981    let change_address = change_output
3982        .recipient_address()
3983        .expect("the change output pays a standard P2PKH address");
3984
3985    // The change address must be an internal-scope (change) address of the spending account,
3986    // exposed at the current chain height by having been reserved for change.
3987    let receivers = st
3988        .wallet()
3989        .get_transparent_receivers(account.id(), true, false)
3990        .unwrap();
3991    let change_meta = receivers
3992        .get(&change_address)
3993        .expect("the change address belongs to the spending account");
3994    assert_eq!(change_meta.scope(), Some(TransparentKeyScope::INTERNAL));
3995    let cur_height = st.wallet().chain_height().unwrap().unwrap();
3996    assert_matches!(
3997        change_meta.exposure(),
3998        Exposure::Exposed { at_height, .. } if at_height == cur_height
3999    );
4000
4001    // Mine the transaction; the change output should then be spendable at the change address.
4002    let (h, _) = st.generate_next_block_including(txid);
4003    st.scan_cached_blocks(h, 1);
4004
4005    let mut expected_balance = Balance::ZERO;
4006    expected_balance
4007        .add_spendable_value(expected_change)
4008        .unwrap();
4009    check_balance::<DSF>(
4010        &st,
4011        &account,
4012        &change_address,
4013        ConfirmationsPolicy::MIN,
4014        &expected_balance,
4015    );
4016}
4017
4018/// Tests that when a fully-transparent transaction balances exactly (input value equals
4019/// payments plus the minimum fee), no transparent change output is produced even when the
4020/// change strategy is configured with [`TransparentChangePolicy::TransparentChangeAllowed`].
4021///
4022/// [`TransparentChangePolicy::TransparentChangeAllowed`]: crate::fees::TransparentChangePolicy::TransparentChangeAllowed
4023pub fn propose_t2t_transparent_change_exact_match<DSF>(dsf: DSF, cache: impl TestCache)
4024where
4025    DSF: DataStoreFactory,
4026{
4027    // Under ZIP 317, one P2PKH input and one P2PKH output require the minimum fee of
4028    // 10_000 zats, so a 50_000-zat UTXO exactly covers a 40_000-zat payment.
4029    let utxo_value = Zatoshis::const_from_u64(50_000);
4030    let transfer_amount = Zatoshis::const_from_u64(40_000);
4031    let (mut st, account, _outpoint) = setup_transparent_only_account(dsf, cache, utxo_value);
4032
4033    let network = *st.network();
4034    let request = t2t_request(&network, transfer_amount);
4035
4036    let input_selector = GreedyInputSelector::new();
4037    let change_strategy =
4038        single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Sapling)
4039            .with_transparent_change_policy(TransparentChangePolicy::TransparentChangeAllowed);
4040
4041    let proposal = st
4042        .propose_transfer_with_policy(
4043            account.id(),
4044            &input_selector,
4045            &change_strategy,
4046            request,
4047            ConfirmationsPolicy::MIN,
4048            &SpendPolicy::default().with_transparent(TransparentSpendPolicy::any_account_addr()),
4049        )
4050        .expect("exactly-balanced t->t proposal must succeed");
4051
4052    assert_eq!(proposal.steps().len(), 1);
4053    let step = &proposal.steps().head;
4054    assert_eq!(
4055        step.balance().fee_required(),
4056        Zatoshis::const_from_u64(10_000),
4057    );
4058    assert_eq!(step.balance().proposed_change(), []);
4059}