1use std::{
2 cmp::Eq,
3 collections::HashSet,
4 convert::Infallible,
5 hash::Hash,
6 num::{NonZeroU8, NonZeroU32, NonZeroU64, NonZeroUsize},
7};
8
9use assert_matches::assert_matches;
10use incrementalmerkletree::{Hashable, Level, Position, frontier::Frontier};
11use rand::{Rng, RngExt};
12use secrecy::Secret;
13use shardtree::error::ShardTreeError;
14use subtle::ConditionallySelectable;
15
16use transparent::address::TransparentAddress;
17use zcash_keys::{
18 address::{Address, UnifiedAddress},
19 keys::{UnifiedAddressRequest, UnifiedSpendingKey},
20};
21use zcash_primitives::{
22 block::BlockHash,
23 transaction::{
24 Transaction,
25 builder::{
26 BLOSSOM_DEFAULT_TX_EXPIRY_DELTA, NU7_DEFAULT_TX_EXPIRY_DELTA, default_tx_expiry_delta,
27 },
28 fees::zip317::{FeeRule as Zip317FeeRule, marginal_fee, minimum_fee},
29 },
30};
31use zcash_protocol::{
32 ShieldedPool,
33 consensus::{self, BlockHeight, BranchId, NetworkUpgrade, Parameters},
34 local_consensus::LocalNetwork,
35 memo::{Memo, MemoBytes},
36 value::{COIN, MAX_MONEY, Zatoshis},
37};
38use zip32::Scope;
39use zip321::{Payment, TransactionRequest};
40
41use crate::{
42 data_api::{
43 self, Account as _, AccountBirthday, BoundedU8, DecryptedTransaction, InputSource,
44 MaxSpendMode, NoteFilter, Ratio, SAPLING_SHARD_HEIGHT, TargetValue, WalletCommitmentTrees,
45 WalletRead, WalletSummary, WalletTest, WalletWrite,
46 anchor_retention::AnchorRetentionInterval,
47 chain::{self, BlockSource, ChainState, CommitmentTreeRoot, ScanSummary},
48 error::{AddressExpiryError, Error},
49 scanning::ScanPriority,
50 testing::{
51 AddressType, CacheInsertionResult, FakeCompactOutput, InitialChainState, TestBuilder,
52 single_output_change_strategy,
53 },
54 wallet::{
55 ConfirmationsPolicy, TargetHeight, TransferErrT, decrypt_and_store_transaction,
56 input_selection::{GreedyInputSelector, LockFilter},
57 },
58 },
59 decrypt_transaction,
60 fees::{
61 self, DustOutputPolicy, SplitPolicy, StandardFeeRule,
62 standard::{self, SingleOutputChangeStrategy},
63 },
64 scanning::ScanError,
65 wallet::{Note, NoteId, OvkPolicy, ReceivedNote},
66};
67
68use super::{DataStoreFactory, Reset, TestCache, TestFvk, TestState};
69
70use crate::data_api::ll::wallet::PRUNING_DEPTH;
71use crate::data_api::wallet::input_selection::GreedyInputSelectorError;
72use crate::{
73 data_api::BlockMetadata,
74 scanning::{
75 ScanningKeys, SpendIdentifiers,
76 full::{decrypt_block, scan_block},
77 },
78};
79use incrementalmerkletree::Retention;
80use nonempty::NonEmpty;
81use shardtree::{ShardTree, store::ShardStore};
82use std::collections::BTreeSet;
83use zcash_primitives::block::{Block, BlockHeaderData};
84use zcash_protocol::PoolType;
85
86#[cfg(feature = "orchard")]
87use {
88 super::orchard::OrchardPoolTester,
89 crate::data_api::{ORCHARD_SHARD_HEIGHT, wallet::propose_transfer},
90 std::collections::BTreeMap,
91 zcash_primitives::transaction::{TxVersion, builder::BundlePadding},
92 zcash_protocol::zip318::{AnchorBucketInterval, MAX_RESIDUAL_VALUE},
93};
94
95#[cfg(not(feature = "orchard"))]
96use zcash_address::{
97 ZcashAddress,
98 unified::{self, Encoding as _, Receiver, Revision, Uitem},
99};
100
101#[cfg(all(feature = "orchard", not(feature = "transparent-inputs")))]
104use crate::proposal::ProposalError;
105
106#[cfg(any(feature = "orchard", feature = "transparent-inputs"))]
108use crate::data_api::wallet::input_selection::SpendPolicy;
109
110#[cfg(feature = "transparent-inputs")]
111use {
112 crate::{
113 data_api::{
114 CoinbaseFilter, OutputOfSentTx, TransactionDataRequest, TransactionStatus,
115 wallet::input_selection::TransparentSpendPolicy,
116 },
117 fees::ChangeValue,
118 proposal::{Proposal, ProposalError, StepOutput, StepOutputIndex},
119 wallet::{Exposure, TransparentAddressSource, WalletTransparentOutput},
120 },
121 secrecy::ExposeSecret,
122 std::str::FromStr,
123 transparent::bundle::{OutPoint, TxOut},
124 zcash_keys::keys::transparent::{
125 NonHardenedChildIndex, TransparentKeyScope, gap_limits::GapLimits,
126 },
127 zcash_primitives::transaction::fees::{FeeRule, transparent::InputSize},
128 zcash_protocol::{
129 TxId,
130 value::{BalanceError, ZatBalance},
131 },
132};
133
134#[cfg(feature = "pczt")]
135use {
136 crate::data_api::wallet::{SignerView, redact_pczt_for_batch_signer, redact_pczt_for_signer},
137 pczt::roles::{combiner::Combiner, prover::Prover, signer::Signer},
138 rand::rngs::SysRng,
139 rand_core::UnwrapErr,
140 transparent::builder::TransparentSigningSet,
141 zcash_primitives::transaction::builder::{BuildConfig, Builder},
142 zcash_proofs::prover::LocalTxProver,
143 zcash_protocol::consensus::ZIP212_GRACE_PERIOD,
144 zcash_script::opcode::PushValue,
145};
146
147#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
148use {
149 crate::data_api::wallet::input_selection::LockedInputPolicy,
150 zcash_protocol::consensus::COINBASE_MATURITY_BLOCKS,
151};
152
153pub mod dsl;
154use dsl::{TestDsl, TestNoteConfig, TestScenario};
155
156pub mod locking;
157pub use locking::*;
158
159pub(crate) const SHARD_1_NOTE_VALUE: Zatoshis = Zatoshis::const_from_u64(150_000);
162
163pub(crate) const PRE_BIRTHDAY_BLOCKS: u32 = 55;
170
171const RECOVERY_A_NOTE_VALUE: Zatoshis = Zatoshis::const_from_u64(150_000);
174
175const RECOVERY_B_NOTE_VALUE: Zatoshis = Zatoshis::const_from_u64(80_000);
178
179#[derive(Clone, Copy, PartialEq, Eq)]
182enum Shard1ScanOrder {
183 NoteFirst,
186 CompletionFirst,
189}
190
191const SHARD_1_FRONTIER_GAP: u32 = 71;
194
195fn build_shard_1_prefix_fixture<T, Dsf>(
201 ds_factory: Dsf,
202 cache: impl TestCache,
203) -> (
204 TestState<impl TestCache, Dsf::DataStore, LocalNetwork>,
205 <Dsf as DataStoreFactory>::AccountId,
206 UnifiedSpendingKey,
207 T::Fvk,
208)
209where
210 T: ShieldedPoolTester,
211 Dsf: DataStoreFactory,
212 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
213{
214 const SHARD_POSITIONS: u32 = 1 << SAPLING_SHARD_HEIGHT;
217 #[cfg(feature = "orchard")]
218 const _: () = assert!(SAPLING_SHARD_HEIGHT == ORCHARD_SHARD_HEIGHT);
219
220 const TEST_SEED: [u8; 32] = [0u8; 32];
224
225 let initial_tree_size: u32 = 2 * SHARD_POSITIONS - SHARD_1_FRONTIER_GAP;
230
231 let mut st = TestBuilder::new()
232 .with_data_store_factory(ds_factory)
233 .with_block_cache(cache)
234 .with_initial_chain_state(|rng, network| {
235 let birthday_height = network.activation_height(NetworkUpgrade::Nu5).unwrap() + 1000;
236
237 let (prior_sapling_roots, sapling_initial_tree) =
238 Frontier::random_with_prior_subtree_roots(
239 rng,
240 initial_tree_size.into(),
241 NonZeroU8::new(SAPLING_SHARD_HEIGHT).unwrap(),
242 );
243 let prior_sapling_roots = prior_sapling_roots
244 .into_iter()
245 .map(|root| CommitmentTreeRoot::from_parts(birthday_height - 500, root))
246 .collect::<Vec<_>>();
247
248 #[cfg(feature = "orchard")]
249 let (prior_orchard_roots, orchard_initial_tree) =
250 Frontier::random_with_prior_subtree_roots(
251 rng,
252 initial_tree_size.into(),
253 NonZeroU8::new(ORCHARD_SHARD_HEIGHT).unwrap(),
254 );
255 #[cfg(feature = "orchard")]
256 let prior_orchard_roots = prior_orchard_roots
257 .into_iter()
258 .map(|root| CommitmentTreeRoot::from_parts(birthday_height - 500, root))
259 .collect::<Vec<_>>();
260
261 #[cfg(feature = "orchard")]
263 let ironwood_initial_tree = Frontier::empty();
264
265 InitialChainState {
266 chain_state: ChainState::new(
267 birthday_height - 1 - PRE_BIRTHDAY_BLOCKS,
268 BlockHash([5; 32]),
269 sapling_initial_tree,
270 #[cfg(feature = "orchard")]
271 orchard_initial_tree,
272 #[cfg(feature = "orchard")]
273 ironwood_initial_tree,
274 ),
275 prior_sapling_roots,
276 #[cfg(feature = "orchard")]
277 prior_orchard_roots,
278 }
279 })
280 .build();
281
282 for _ in 0..PRE_BIRTHDAY_BLOCKS {
288 st.generate_empty_block();
289 }
290
291 let usk = UnifiedSpendingKey::from_seed(st.network(), &TEST_SEED, zip32::AccountId::ZERO)
296 .expect("account USK derivation from seed should succeed");
297 let dfvk = T::sk_to_fvk(T::usk_to_sk(&usk));
298 let birthday_prior_chain_state = st
299 .latest_cached_block()
300 .expect("pre-birthday blocks have been cached")
301 .chain_state()
302 .clone();
303 let birthday = AccountBirthday::from_parts(birthday_prior_chain_state, None);
304 let seed = Secret::new(TEST_SEED.to_vec());
305 let (account, _) = st
306 .wallet_mut()
307 .import_account_hd("primary", &seed, zip32::AccountId::ZERO, &birthday, None)
308 .expect("account import should succeed");
309 let account_id = account.id();
310
311 (st, account_id, usk, dfvk)
312}
313
314fn build_shard_1_note_fixture<T, Dsf>(
362 ds_factory: Dsf,
363 cache: impl TestCache,
364 trailing_filler_blocks: u32,
365 scan_order: Shard1ScanOrder,
366) -> (
367 TestState<impl TestCache, Dsf::DataStore, LocalNetwork>,
368 <Dsf as DataStoreFactory>::AccountId,
369 UnifiedSpendingKey,
370)
371where
372 T: ShieldedPoolTester,
373 Dsf: DataStoreFactory,
374 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
375{
376 let (mut st, account_id, usk, dfvk) = build_shard_1_prefix_fixture::<T, Dsf>(ds_factory, cache);
377
378 let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
379 let filler_value = Zatoshis::const_from_u64(1000);
380
381 let mut block_a_outputs = Vec::with_capacity(50);
386 block_a_outputs.push(FakeCompactOutput::new(
387 dfvk.clone(),
388 AddressType::DefaultExternal,
389 SHARD_1_NOTE_VALUE,
390 ));
391 for _ in 1..50 {
392 block_a_outputs.push(FakeCompactOutput::new(
393 not_our_key.clone(),
394 AddressType::DefaultExternal,
395 filler_value,
396 ));
397 }
398 let (block_a_height, _, _) = st.generate_next_block_multi(&block_a_outputs);
399 if scan_order == Shard1ScanOrder::NoteFirst {
400 st.scan_cached_blocks(block_a_height, 1);
401 }
402
403 let block_b_outputs: Vec<_> = (0..30)
408 .map(|_| {
409 FakeCompactOutput::new(
410 not_our_key.clone(),
411 AddressType::DefaultExternal,
412 filler_value,
413 )
414 })
415 .collect();
416 let (block_b_height, _, _) = st.generate_next_block_multi(&block_b_outputs);
417 st.scan_cached_blocks(block_b_height, 1);
418
419 let shard_1_root = T::shard_root(&mut st, 1).unwrap();
428 T::put_subtree_roots(
429 &mut st,
430 1,
431 &[CommitmentTreeRoot::from_parts(block_b_height, shard_1_root)],
432 )
433 .unwrap();
434 if scan_order == Shard1ScanOrder::CompletionFirst {
435 st.scan_cached_blocks(block_a_height, 1);
436 }
437
438 if trailing_filler_blocks > 0 {
441 for _ in 0..trailing_filler_blocks {
442 st.generate_next_block(¬_our_key, AddressType::DefaultExternal, filler_value);
443 }
444 st.scan_cached_blocks(block_b_height + 1, trailing_filler_blocks as usize);
445 }
446
447 (st, account_id, usk)
448}
449
450pub(crate) fn build_stable_shard_fixture<T, Dsf>(
463 ds_factory: Dsf,
464 cache: impl TestCache,
465) -> (
466 TestState<impl TestCache, Dsf::DataStore, LocalNetwork>,
467 <Dsf as DataStoreFactory>::AccountId,
468 UnifiedSpendingKey,
469)
470where
471 T: ShieldedPoolTester,
472 Dsf: DataStoreFactory,
473 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
474{
475 build_shard_1_note_fixture::<T, Dsf>(
476 ds_factory,
477 cache,
478 PRUNING_DEPTH + 10,
479 Shard1ScanOrder::NoteFirst,
480 )
481}
482
483pub(crate) fn build_tip_shard_fixture<T, Dsf>(
499 ds_factory: Dsf,
500 cache: impl TestCache,
501) -> (
502 TestState<impl TestCache, Dsf::DataStore, LocalNetwork>,
503 <Dsf as DataStoreFactory>::AccountId,
504 UnifiedSpendingKey,
505)
506where
507 T: ShieldedPoolTester,
508 Dsf: DataStoreFactory,
509 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
510{
511 build_shard_1_note_fixture::<T, Dsf>(ds_factory, cache, 5, Shard1ScanOrder::NoteFirst)
512}
513
514fn build_two_account_recovery_fixture<T, Dsf>(
550 ds_factory: Dsf,
551 cache: impl TestCache,
552) -> (
553 TestState<impl TestCache, Dsf::DataStore, LocalNetwork>,
554 <Dsf as DataStoreFactory>::AccountId,
555 UnifiedSpendingKey,
556)
557where
558 T: ShieldedPoolTester,
559 Dsf: DataStoreFactory,
560 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
561{
562 const SHARD_POSITIONS: u32 = 1 << SAPLING_SHARD_HEIGHT;
565 #[cfg(feature = "orchard")]
566 const _: () = assert!(SAPLING_SHARD_HEIGHT == ORCHARD_SHARD_HEIGHT);
567
568 const TEST_SEED: [u8; 32] = [0u8; 32];
572
573 let initial_tree_size: u32 = 2 * SHARD_POSITIONS - 71;
577
578 let mut st = TestBuilder::new()
579 .with_data_store_factory(ds_factory)
580 .with_block_cache(cache)
581 .with_initial_chain_state(|rng, network| {
582 let birthday_height = network.activation_height(NetworkUpgrade::Nu5).unwrap() + 1000;
583
584 let (prior_sapling_roots, sapling_initial_tree) =
585 Frontier::random_with_prior_subtree_roots(
586 rng,
587 initial_tree_size.into(),
588 NonZeroU8::new(SAPLING_SHARD_HEIGHT).unwrap(),
589 );
590 let prior_sapling_roots = prior_sapling_roots
591 .into_iter()
592 .map(|root| CommitmentTreeRoot::from_parts(birthday_height - 500, root))
593 .collect::<Vec<_>>();
594
595 #[cfg(feature = "orchard")]
596 let (prior_orchard_roots, orchard_initial_tree) =
597 Frontier::random_with_prior_subtree_roots(
598 rng,
599 initial_tree_size.into(),
600 NonZeroU8::new(ORCHARD_SHARD_HEIGHT).unwrap(),
601 );
602 #[cfg(feature = "orchard")]
603 let prior_orchard_roots = prior_orchard_roots
604 .into_iter()
605 .map(|root| CommitmentTreeRoot::from_parts(birthday_height - 500, root))
606 .collect::<Vec<_>>();
607
608 #[cfg(feature = "orchard")]
610 let ironwood_initial_tree = Frontier::empty();
611
612 InitialChainState {
613 chain_state: ChainState::new(
614 birthday_height - 1,
615 BlockHash([5; 32]),
616 sapling_initial_tree,
617 #[cfg(feature = "orchard")]
618 orchard_initial_tree,
619 #[cfg(feature = "orchard")]
620 ironwood_initial_tree,
621 ),
622 prior_sapling_roots,
623 #[cfg(feature = "orchard")]
624 prior_orchard_roots,
625 }
626 })
627 .with_account_having_current_birthday()
628 .build();
629
630 let dfvk_a = T::test_account_fvk(&st);
631 let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
632 let filler_value = Zatoshis::const_from_u64(1000);
633
634 let zip32_index_b = zip32::AccountId::ZERO.next().unwrap();
637 let usk_b = UnifiedSpendingKey::from_seed(st.network(), &TEST_SEED, zip32_index_b)
638 .expect("account B USK derivation from seed should succeed");
639 let fvk_b = T::sk_to_fvk(T::usk_to_sk(&usk_b));
640
641 let mut block_a1_outputs = Vec::with_capacity(35);
645 block_a1_outputs.push(FakeCompactOutput::new(
646 dfvk_a.clone(),
647 AddressType::DefaultExternal,
648 RECOVERY_A_NOTE_VALUE,
649 ));
650 for _ in 1..35 {
651 block_a1_outputs.push(FakeCompactOutput::new(
652 not_our_key.clone(),
653 AddressType::DefaultExternal,
654 filler_value,
655 ));
656 }
657 let (block_a1_height, _, _) = st.generate_next_block_multi(&block_a1_outputs);
658
659 let block_a2_outputs: Vec<_> = (0..36)
662 .map(|_| {
663 FakeCompactOutput::new(
664 not_our_key.clone(),
665 AddressType::DefaultExternal,
666 filler_value,
667 )
668 })
669 .collect();
670 let (block_a2_height, _, _) = st.generate_next_block_multi(&block_a2_outputs);
671 st.scan_cached_blocks(block_a1_height, 2);
672
673 let shard_1_root = T::shard_root(&mut st, 1).unwrap();
676 T::put_subtree_roots(
677 &mut st,
678 1,
679 &[CommitmentTreeRoot::from_parts(
680 block_a2_height,
681 shard_1_root,
682 )],
683 )
684 .unwrap();
685
686 for _ in 0..3 {
689 st.generate_next_block(¬_our_key, AddressType::DefaultExternal, filler_value);
690 }
691 st.scan_cached_blocks(block_a2_height + 1, 3);
692
693 let b_prior_chain_state = st
697 .latest_cached_block()
698 .expect("blocks have been scanned")
699 .chain_state()
700 .clone();
701 let b_birthday = AccountBirthday::from_parts(b_prior_chain_state, None);
702 let seed = Secret::new(TEST_SEED.to_vec());
703 let (account_b, _) = st
704 .wallet_mut()
705 .import_account_hd("account B", &seed, zip32_index_b, &b_birthday, None)
706 .expect("account B import should succeed");
707 let account_b_id = account_b.id();
708
709 let mut block_b_outputs = Vec::with_capacity(5);
712 block_b_outputs.push(FakeCompactOutput::new(
713 fvk_b.clone(),
714 AddressType::DefaultExternal,
715 RECOVERY_B_NOTE_VALUE,
716 ));
717 for _ in 1..5 {
718 block_b_outputs.push(FakeCompactOutput::new(
719 not_our_key.clone(),
720 AddressType::DefaultExternal,
721 filler_value,
722 ));
723 }
724 let (block_b_height, _, _) = st.generate_next_block_multi(&block_b_outputs);
725
726 let trailing_filler_blocks = PRUNING_DEPTH + 10;
729 for _ in 0..trailing_filler_blocks {
730 st.generate_next_block(¬_our_key, AddressType::DefaultExternal, filler_value);
731 }
732 st.scan_cached_blocks(block_b_height, 1 + trailing_filler_blocks as usize);
733
734 (st, account_b_id, usk_b)
735}
736
737pub(crate) fn assert_send_max_consumes_balance<T, Cache, DbT, ParamsT, AccountIdT, ErrT>(
742 st: &mut TestState<Cache, DbT, ParamsT>,
743 account_id: AccountIdT,
744 expected_balance: Zatoshis,
745) where
746 T: ShieldedPoolTester,
747 Cache: TestCache,
748 <Cache::BlockSource as BlockSource>::Error: std::fmt::Debug,
749 ParamsT: consensus::Parameters + Send + 'static,
750 AccountIdT: std::fmt::Debug + std::cmp::Eq + std::hash::Hash,
751 ErrT: std::fmt::Debug,
752 DbT: InputSource<AccountId = AccountIdT, Error = ErrT>
753 + WalletTest
754 + WalletWrite
755 + WalletRead<AccountId = AccountIdT, Error = ErrT>
756 + WalletCommitmentTrees,
757 <DbT as WalletRead>::AccountId: ConditionallySelectable + Default + Send + 'static,
758{
759 let send_max_recipient = T::sk_default_address(&T::sk(&[0xdd; 32]));
760 let proposal = st
761 .propose_send_max_transfer(
762 account_id,
763 &Zip317FeeRule::standard(),
764 send_max_recipient.to_zcash_address(st.network()),
765 None,
766 MaxSpendMode::MaxSpendable,
767 ConfirmationsPolicy::MIN,
768 )
769 .expect("send-max proposal should succeed when spendable balance is non-zero");
770 let step = proposal.steps().first();
771 let total_payments: Zatoshis = step
772 .transaction_request()
773 .payments()
774 .values()
775 .map(|p| p.amount().expect("send-max proposal payments have amounts"))
776 .sum::<Option<Zatoshis>>()
777 .expect("send-max payments should not overflow");
778 let fee = step.balance().fee_required();
779 assert_eq!(
780 (total_payments + fee).expect("payments + fee should not overflow"),
781 expected_balance,
782 "send-max proposal outputs + fee must equal the spendable balance",
783 );
784}
785
786#[cfg_attr(
794 feature = "orchard",
795 doc = "[`OrchardPoolTester`]: super::orchard::OrchardPoolTester"
796)]
797#[cfg_attr(
798 not(feature = "orchard"),
799 doc = "[`OrchardPoolTester`]: https://github.com/zcash/librustzcash/blob/0777cbc2def6ba6b99f96333eaf96c314c1f3a37/zcash_client_backend/src/data_api/testing/orchard.rs#L33"
800)]
801pub trait ShieldedPoolTester {
802 const SHIELDED_PROTOCOL: ShieldedPool;
803
804 type Sk;
805 type Fvk: TestFvk;
806 type MerkleTreeHash;
807 type Note;
808
809 fn test_account_fvk<Cache, DbT: WalletTest, P: consensus::Parameters>(
810 st: &TestState<Cache, DbT, P>,
811 ) -> Self::Fvk;
812 fn usk_to_sk(usk: &UnifiedSpendingKey) -> &Self::Sk;
813 fn sk(seed: &[u8]) -> Self::Sk;
814 fn sk_to_fvk(sk: &Self::Sk) -> Self::Fvk;
815 fn sk_default_address(sk: &Self::Sk) -> Address;
816 fn fvk_default_address(fvk: &Self::Fvk) -> Address;
817 fn fvks_equal(a: &Self::Fvk, b: &Self::Fvk) -> bool;
818
819 fn random_fvk(mut rng: impl Rng) -> Self::Fvk {
820 let sk = {
821 let mut sk_bytes = vec![0; 32];
822 rng.fill_bytes(&mut sk_bytes);
823 Self::sk(&sk_bytes)
824 };
825
826 Self::sk_to_fvk(&sk)
827 }
828 fn random_address(rng: impl Rng) -> Address {
829 Self::fvk_default_address(&Self::random_fvk(rng))
830 }
831
832 fn empty_tree_leaf() -> Self::MerkleTreeHash;
833 fn empty_tree_root(level: Level) -> Self::MerkleTreeHash;
834
835 fn put_subtree_roots<Cache, DbT: WalletTest + WalletCommitmentTrees, P>(
836 st: &mut TestState<Cache, DbT, P>,
837 start_index: u64,
838 roots: &[CommitmentTreeRoot<Self::MerkleTreeHash>],
839 ) -> Result<(), ShardTreeError<<DbT as WalletCommitmentTrees>::Error>>;
840
841 fn shard_root<Cache, DbT: WalletTest + WalletCommitmentTrees, P>(
847 st: &mut TestState<Cache, DbT, P>,
848 shard_index: u64,
849 ) -> Result<Self::MerkleTreeHash, ShardTreeError<<DbT as WalletCommitmentTrees>::Error>>;
850
851 fn next_subtree_index<A: Hash + Eq>(s: &WalletSummary<A>) -> u64;
852
853 fn note_value(note: &Self::Note) -> Zatoshis;
854
855 #[allow(clippy::type_complexity)]
856 fn select_spendable_notes<Cache, DbT: InputSource + WalletTest, P>(
857 st: &TestState<Cache, DbT, P>,
858 account: <DbT as InputSource>::AccountId,
859 target_value: TargetValue,
860 target_height: TargetHeight,
861 confirmations_policy: ConfirmationsPolicy,
862 exclude: &[DbT::NoteRef],
863 ) -> Result<Vec<ReceivedNote<DbT::NoteRef, Self::Note>>, <DbT as InputSource>::Error>;
864
865 #[allow(clippy::type_complexity)]
866 fn select_unspent_notes<Cache, DbT: InputSource + WalletTest, P>(
867 st: &TestState<Cache, DbT, P>,
868 account: <DbT as InputSource>::AccountId,
869 target_height: TargetHeight,
870 exclude: &[DbT::NoteRef],
871 ) -> Result<Vec<ReceivedNote<DbT::NoteRef, Self::Note>>, <DbT as InputSource>::Error>;
872
873 fn decrypted_pool_outputs_count<A>(d_tx: &DecryptedTransaction<Transaction, A>) -> usize;
874
875 fn with_decrypted_pool_memos<A>(
876 d_tx: &DecryptedTransaction<Transaction, A>,
877 f: impl FnMut(&MemoBytes),
878 );
879
880 fn try_output_recovery<P: consensus::Parameters>(
881 params: &P,
882 height: BlockHeight,
883 tx: &Transaction,
884 fvk: &Self::Fvk,
885 ) -> Option<(Note, Address, MemoBytes)>;
886
887 fn received_note_count(summary: &ScanSummary) -> usize;
888
889 #[cfg(feature = "pczt")]
890 fn add_proof_generation_keys(
891 pczt: pczt::Pczt,
892 usk: &UnifiedSpendingKey,
893 ) -> Result<pczt::Pczt, pczt::roles::updater::SaplingError>;
894
895 #[cfg(feature = "pczt")]
896 fn apply_signatures_to_pczt(
897 signer: &mut Signer,
898 usk: &UnifiedSpendingKey,
899 ) -> Result<(), pczt::roles::signer::Error>;
900}
901
902fn anchor_grid<P: consensus::Parameters>(
904 network: &P,
905 interval: zcash_protocol::zip318::AnchorBucketInterval,
906) -> zcash_protocol::zip318::AnchorGrid {
907 zcash_protocol::zip318::AnchorGrid::new(
908 interval,
909 zcash_protocol::zip318::BlockSpacing::for_network(network),
910 )
911}
912
913pub fn send_single_step_proposed_transfer<T: ShieldedPoolTester>(
924 dsf: impl DataStoreFactory,
925 cache: impl TestCache,
926) {
927 let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
928
929 let (h, _, _) = st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60000));
931
932 let to_extsk = T::sk(&[0xf5; 32]);
933 let to: Address = T::sk_default_address(&to_extsk);
934 let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
935 to.to_zcash_address(st.network()),
936 Zatoshis::const_from_u64(10000),
937 )])
938 .unwrap();
939
940 let fee_rule = StandardFeeRule::Zip317;
941
942 let change_memo = "Test change memo".parse::<Memo>().unwrap();
943 let change_strategy = standard::SingleOutputChangeStrategy::new(
944 fee_rule,
945 Some(change_memo.clone().into()),
946 T::SHIELDED_PROTOCOL,
947 DustOutputPolicy::default(),
948 );
949 let input_selector = GreedyInputSelector::new();
950
951 let account = st.get_account();
952 let proposal = st
953 .propose_transfer(
954 account.id(),
955 &input_selector,
956 &change_strategy,
957 request,
958 ConfirmationsPolicy::MIN,
959 )
960 .unwrap();
961
962 let sent_tx_id = st.create_proposed_expecting(&proposal, 1)[0];
963
964 let tx = st
966 .wallet()
967 .get_transaction(sent_tx_id)
968 .unwrap()
969 .expect("Created transaction was stored.");
970 let ufvks = [(account.id(), account.usk().to_unified_full_viewing_key())]
971 .into_iter()
972 .collect();
973 let d_tx = decrypt_transaction(st.network(), None, Some(h), &tx, &ufvks);
974 assert_eq!(T::decrypted_pool_outputs_count(&d_tx), 2);
975
976 let mut found_tx_change_memo = false;
977 let mut found_tx_empty_memo = false;
978 T::with_decrypted_pool_memos(&d_tx, |memo| {
979 if Memo::try_from(memo).unwrap() == change_memo {
980 found_tx_change_memo = true
981 }
982 if Memo::try_from(memo).unwrap() == Memo::Empty {
983 found_tx_empty_memo = true
984 }
985 });
986 assert!(found_tx_change_memo);
987 assert!(found_tx_empty_memo);
988
989 let sent_note_ids = st
991 .wallet()
992 .get_sent_note_ids(&sent_tx_id, T::SHIELDED_PROTOCOL)
993 .unwrap();
994 assert_eq!(sent_note_ids.len(), 2);
995
996 let mut found_sent_change_memo = false;
999 let mut found_sent_empty_memo = false;
1000 for sent_note_id in sent_note_ids {
1001 match st
1002 .wallet()
1003 .get_memo(sent_note_id)
1004 .expect("Note id is valid")
1005 .as_ref()
1006 {
1007 Some(m) if m == &change_memo => {
1008 found_sent_change_memo = true;
1009 }
1010 Some(m) if m == &Memo::Empty => {
1011 found_sent_empty_memo = true;
1012 }
1013 Some(other) => panic!("Unexpected memo value: {other:?}"),
1014 None => panic!("Memo should not be stored as NULL"),
1015 }
1016 }
1017 assert!(found_sent_change_memo);
1018 assert!(found_sent_empty_memo);
1019
1020 assert_matches!(
1022 st.wallet()
1023 .get_memo(NoteId::new(sent_tx_id, T::SHIELDED_PROTOCOL, 12345)),
1024 Ok(None)
1025 );
1026
1027 let tx_history = st.wallet().get_tx_history().unwrap();
1028 assert_eq!(tx_history.len(), 2);
1029 {
1030 let tx_0 = &tx_history[0];
1031 assert_eq!(tx_0.total_spent(), Zatoshis::const_from_u64(0));
1032 assert_eq!(tx_0.total_received(), Zatoshis::const_from_u64(60000));
1033 }
1034
1035 {
1036 let tx_1 = &tx_history[1];
1037 assert_eq!(tx_1.total_spent(), Zatoshis::const_from_u64(60000));
1038 assert_eq!(tx_1.total_received(), Zatoshis::const_from_u64(40000));
1039 }
1040
1041 let network = *st.network();
1042 assert_matches!(
1043 decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, None),
1044 Ok(_)
1045 );
1046}
1047
1048pub fn scan_full_block_detects_outputs<T: ShieldedPoolTester>(
1055 dsf: impl DataStoreFactory,
1056 cache: impl TestCache,
1057) {
1058 let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
1059
1060 let (h, _, _) = st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60000));
1062
1063 let to_extsk = T::sk(&[0xf5; 32]);
1066 let to: Address = T::sk_default_address(&to_extsk);
1067 let request = TransactionRequest::new(vec![Payment::without_memo(
1068 to.to_zcash_address(st.network()),
1069 Zatoshis::const_from_u64(10000),
1070 )])
1071 .unwrap();
1072
1073 let change_strategy =
1074 single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
1075 let input_selector = GreedyInputSelector::new();
1076
1077 let account = st.get_account();
1078 let proposal = st
1079 .propose_transfer(
1080 account.id(),
1081 &input_selector,
1082 &change_strategy,
1083 request,
1084 ConfirmationsPolicy::MIN,
1085 )
1086 .unwrap();
1087
1088 let txids = st
1089 .create_proposed_transactions::<Infallible, _, Infallible, _>(
1090 account.usk(),
1091 OvkPolicy::Sender,
1092 &proposal,
1093 )
1094 .unwrap();
1095 assert_eq!(txids.len(), 1);
1096
1097 let tx = st
1098 .wallet()
1099 .get_transaction(*txids.first())
1100 .unwrap()
1101 .expect("the created transaction was stored");
1102
1103 let ufvk = account.usk().to_unified_full_viewing_key();
1106 let scanning_keys = ScanningKeys::from_account_ufvks([(zip32::AccountId::ZERO, ufvk)]);
1107
1108 let network = *st.network();
1112 let header = BlockHeaderData {
1113 version: 4,
1114 prev_block: BlockHash([0; 32]),
1115 merkle_root: [0; 32],
1116 final_sapling_root: [0; 32],
1117 time: 0,
1118 bits: 0,
1119 nonce: [0; 32],
1120 solution: vec![],
1121 }
1122 .freeze()
1123 .unwrap();
1124 let block = Block::from_parts(header, NonEmpty::singleton(tx), h);
1125
1126 let prior_block_metadata = BlockMetadata::from_parts(
1127 h - 1,
1128 BlockHash([0; 32]),
1129 Some(0),
1130 #[cfg(feature = "orchard")]
1131 Some(0),
1132 #[cfg(feature = "orchard")]
1133 Some(0),
1134 );
1135
1136 let (header, vtx) = decrypt_block(&network, block, &scanning_keys);
1138
1139 #[cfg(feature = "transparent-inputs")]
1141 let scanned = scan_block(
1142 &network,
1143 h,
1144 &header,
1145 vtx,
1146 &scanning_keys,
1147 &SpendIdentifiers::empty(),
1148 Some(&prior_block_metadata),
1149 |_addr| Ok::<_, Infallible>(None),
1150 )
1151 .expect("scanning the block succeeds");
1152 #[cfg(not(feature = "transparent-inputs"))]
1153 let scanned = scan_block::<_, _, _, Infallible>(
1154 &network,
1155 h,
1156 &header,
1157 vtx,
1158 &scanning_keys,
1159 &SpendIdentifiers::empty(),
1160 Some(&prior_block_metadata),
1161 )
1162 .expect("scanning the block succeeds");
1163
1164 assert_eq!(scanned.transactions().len(), 1);
1167 let received_outputs: usize = scanned
1168 .transactions()
1169 .iter()
1170 .map(|wtx| {
1171 let n = wtx.sapling_outputs().len();
1172 #[cfg(feature = "orchard")]
1173 let n = n + wtx.orchard_outputs().len();
1174 n
1175 })
1176 .sum();
1177 assert_eq!(received_outputs, 1);
1178
1179 let total_commitments = scanned.sapling().commitments().len();
1184 #[cfg(feature = "orchard")]
1185 let total_commitments = total_commitments + scanned.orchard().commitments().len();
1186 assert_eq!(total_commitments, 2);
1187
1188 let total_final_tree_size = scanned.sapling().final_tree_size();
1189 #[cfg(feature = "orchard")]
1190 let total_final_tree_size = total_final_tree_size + scanned.orchard().final_tree_size();
1191 assert_eq!(total_final_tree_size, 2);
1192
1193 let last_retention = scanned.sapling().commitments().last().map(|(_, r)| *r);
1198 #[cfg(feature = "orchard")]
1199 let last_retention = scanned
1200 .orchard()
1201 .commitments()
1202 .last()
1203 .map(|(_, r)| *r)
1204 .or(last_retention);
1205 assert!(
1206 matches!(last_retention, Some(Retention::Checkpoint { id, .. }) if id == h),
1207 "final note commitment should be a checkpoint at height {h:?}, got {last_retention:?}",
1208 );
1209}
1210
1211#[derive(Clone, Copy, Debug, PartialEq)]
1212struct ConfirmationStep {
1213 i: u32,
1214 confirmation_requirement: u32,
1215 number_of_confirmations: u32,
1216 pending_balance: Zatoshis,
1217 spendable_balance: Zatoshis,
1218 total_balance: Zatoshis,
1219}
1220
1221#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1224pub enum InputTrust {
1225 Internal,
1227 ExternalUntrusted,
1229 ExternalTrusted,
1231}
1232
1233pub fn zip_315_confirmations_test_steps<T: ShieldedPoolTester>(
1241 dsf: impl DataStoreFactory,
1242 cache: impl TestCache,
1243 input_trust: InputTrust,
1244) {
1245 let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
1246 let account = st.test_account().cloned().unwrap();
1247 let starting_balance = Zatoshis::const_from_u64(60_000);
1248
1249 let confirmations_policy = ConfirmationsPolicy::default();
1252 let (address_type, min_confirmations) = match input_trust {
1253 InputTrust::Internal => (AddressType::Internal, confirmations_policy.trusted()),
1254 InputTrust::ExternalUntrusted => (
1255 AddressType::DefaultExternal,
1256 confirmations_policy.untrusted(),
1257 ),
1258 InputTrust::ExternalTrusted => {
1259 (AddressType::DefaultExternal, confirmations_policy.trusted())
1260 }
1261 };
1262 let min_confirmations = u32::from(min_confirmations);
1263
1264 let (_, r, _) = st.add_a_single_note_checking_balance(
1265 TestNoteConfig::from(starting_balance).with_address_type(address_type),
1266 );
1267 let txid = r.txids()[0];
1268
1269 let trusted = input_trust == InputTrust::ExternalTrusted;
1271 if trusted {
1272 st.wallet_mut().set_tx_trust(txid, true).unwrap();
1273 }
1274
1275 let add_confirmation = |i: u32| {
1276 let (h, _) = st.generate_empty_block();
1277 st.scan_cached_blocks(h, 1);
1278 let outputs = st
1279 .wallet()
1280 .get_received_outputs(txid, TargetHeight::from(h + 1), confirmations_policy)
1281 .unwrap();
1282 assert_eq!(outputs.len(), 1);
1283 assert_eq!(
1284 outputs[0].confirmations_until_spendable(),
1285 u32::from(if trusted {
1286 confirmations_policy.trusted()
1287 } else {
1288 confirmations_policy.untrusted()
1289 })
1290 .saturating_sub(i + 1)
1291 );
1292 ConfirmationStep {
1293 i,
1294 confirmation_requirement: min_confirmations,
1295 number_of_confirmations: 1 + i,
1296 pending_balance: st.get_pending_shielded_balance(account.id(), confirmations_policy),
1297 spendable_balance: st.get_spendable_balance(account.id(), confirmations_policy),
1298 total_balance: st.get_total_balance(account.id()),
1299 }
1300 };
1301
1302 let steps = (1u32..min_confirmations)
1304 .map(add_confirmation)
1305 .collect::<Vec<_>>();
1306
1307 assert!(
1308 steps
1309 .iter()
1310 .filter(|step| step.number_of_confirmations < min_confirmations)
1311 .all(|step| step.spendable_balance == Zatoshis::ZERO),
1312 "spendable balance is equal to starting balance until we have sufficient confirmations"
1313 );
1314
1315 let to = T::random_address(st.rng_mut());
1316 let proposed = st.propose_standard_transfer::<Infallible>(
1318 account.id(),
1319 StandardFeeRule::Zip317,
1320 confirmations_policy,
1321 &to,
1322 Zatoshis::const_from_u64(10_000),
1323 None,
1324 None,
1325 T::SHIELDED_PROTOCOL,
1326 );
1327 assert!(
1328 proposed.is_ok(),
1329 "Could not spend funds by confirmation policy ({input_trust:?}): {proposed:#?}\n\
1330 steps: {steps:#?}",
1331 );
1332}
1333
1334pub fn spend_max_spendable_single_step_proposed_transfer<T: ShieldedPoolTester>(
1346 dsf: impl DataStoreFactory,
1347 cache: impl TestCache,
1348) {
1349 let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
1350
1351 let value = Zatoshis::const_from_u64(60000);
1353 let h = st
1354 .add_notes_checking_balance([Some(value), None, None, None, Some(value)])
1355 .block_height()
1356 .unwrap();
1357
1358 let account = st.test_account().cloned().unwrap();
1360 let confirmation_policy = ConfirmationsPolicy::new_symmetrical(
1361 NonZeroU32::new(2).expect("2 is not zero"),
1362 #[cfg(feature = "transparent-inputs")]
1363 false,
1364 );
1365 assert_eq!(
1366 st.get_spendable_balance(account.id(), confirmation_policy),
1367 value
1368 );
1369
1370 let to_extsk = T::sk(&[0xf5; 32]);
1371 let to: Address = T::sk_default_address(&to_extsk);
1372
1373 let fee_rule = StandardFeeRule::Zip317;
1374
1375 let send_max_memo = "Test Send Max memo".parse::<Memo>().unwrap();
1376
1377 let addy = to.to_zcash_address(st.network());
1378 let proposal = st
1379 .propose_send_max_transfer(
1380 account.id(),
1381 &fee_rule,
1382 addy,
1383 Some(MemoBytes::from(send_max_memo.clone())),
1384 MaxSpendMode::MaxSpendable,
1385 confirmation_policy,
1386 )
1387 .unwrap();
1388
1389 let sent_tx_id = st.create_proposed_expecting(&proposal, 1)[0];
1390
1391 let tx = st
1393 .wallet()
1394 .get_transaction(sent_tx_id)
1395 .unwrap()
1396 .expect("Created transaction was stored.");
1397 let ufvks = [(account.id(), account.usk().to_unified_full_viewing_key())]
1398 .into_iter()
1399 .collect();
1400 let d_tx = decrypt_transaction(st.network(), None, Some(h), &tx, &ufvks);
1401 assert_eq!(T::decrypted_pool_outputs_count(&d_tx), 1);
1402
1403 let mut found_send_max_memo = false;
1404 let mut found_tx_empty_memo = false;
1405 T::with_decrypted_pool_memos(&d_tx, |memo| {
1406 if Memo::try_from(memo).unwrap() == send_max_memo {
1407 found_send_max_memo = true
1408 }
1409 if Memo::try_from(memo).unwrap() == Memo::Empty {
1410 found_tx_empty_memo = true
1411 }
1412 });
1413 assert!(found_send_max_memo);
1414 assert!(!found_tx_empty_memo); let sent_note_ids = st
1418 .wallet()
1419 .get_sent_note_ids(&sent_tx_id, T::SHIELDED_PROTOCOL)
1420 .unwrap();
1421 assert_eq!(sent_note_ids.len(), 1);
1422
1423 let mut found_sent_empty_memo = false;
1425 let mut found_sent_max_memo = false;
1426 for sent_note_id in sent_note_ids {
1427 match st
1428 .wallet()
1429 .get_memo(sent_note_id)
1430 .expect("Memo retrieval should succeed")
1431 .as_ref()
1432 {
1433 Some(m) if m == &Memo::Empty => {
1434 found_sent_empty_memo = true;
1435 }
1436 Some(m) if m == &send_max_memo => {
1437 found_sent_max_memo = true;
1438 }
1439 Some(other) => panic!("Unexpected memo value: {other:?}"),
1440 None => panic!("Memo should not be stored as NULL"),
1441 }
1442 }
1443
1444 assert!(found_sent_max_memo);
1445 assert!(!found_sent_empty_memo);
1446
1447 assert_matches!(
1449 st.wallet()
1450 .get_memo(NoteId::new(sent_tx_id, T::SHIELDED_PROTOCOL, 12345)),
1451 Ok(None)
1452 );
1453
1454 let tx_history = st.wallet().get_tx_history().unwrap();
1455 assert_eq!(tx_history.len(), 3);
1456 {
1457 let tx_0 = &tx_history[0];
1458 assert_eq!(tx_0.total_spent(), Zatoshis::const_from_u64(0));
1459 assert_eq!(tx_0.total_received(), Zatoshis::const_from_u64(60000));
1460 }
1461 {
1462 let tx_1 = &tx_history[1];
1463 assert_eq!(tx_1.total_spent(), Zatoshis::const_from_u64(0));
1464 assert_eq!(tx_1.total_received(), Zatoshis::const_from_u64(60000));
1465 }
1466 {
1467 let tx_2 = &tx_history[2];
1468 assert_eq!(tx_2.total_spent(), Zatoshis::const_from_u64(60000));
1469 assert_eq!(tx_2.total_received(), Zatoshis::const_from_u64(0));
1470 }
1471
1472 let network = *st.network();
1473 assert_matches!(
1474 decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, None),
1475 Ok(_)
1476 );
1477}
1478
1479pub fn spend_everything_single_step_proposed_transfer<T: ShieldedPoolTester>(
1491 dsf: impl DataStoreFactory,
1492 cache: impl TestCache,
1493) {
1494 let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
1495
1496 let account = st.test_account().cloned().unwrap();
1497
1498 let (h, _, _) = st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60000));
1500
1501 let to_extsk = T::sk(&[0xf5; 32]);
1502 let to: Address = T::sk_default_address(&to_extsk);
1503
1504 let fee_rule = StandardFeeRule::Zip317;
1505
1506 let send_max_memo = "Test Send Max memo".parse::<Memo>().unwrap();
1507
1508 let addy = to.to_zcash_address(st.network());
1509 let proposal = st
1510 .propose_send_max_transfer(
1511 account.id(),
1512 &fee_rule,
1513 addy,
1514 Some(MemoBytes::from(send_max_memo.clone())),
1515 MaxSpendMode::Everything,
1516 ConfirmationsPolicy::MIN,
1517 )
1518 .unwrap();
1519
1520 let sent_tx_id = st.create_proposed_expecting(&proposal, 1)[0];
1521
1522 let tx = st
1524 .wallet()
1525 .get_transaction(sent_tx_id)
1526 .unwrap()
1527 .expect("Created transaction was stored.");
1528 let ufvks = [(account.id(), account.usk().to_unified_full_viewing_key())]
1529 .into_iter()
1530 .collect();
1531 let d_tx = decrypt_transaction(st.network(), None, Some(h), &tx, &ufvks);
1532 assert_eq!(T::decrypted_pool_outputs_count(&d_tx), 1);
1533
1534 let mut found_send_max_memo = false;
1535 let mut found_tx_empty_memo = false;
1536 T::with_decrypted_pool_memos(&d_tx, |memo| {
1537 if Memo::try_from(memo).unwrap() == send_max_memo {
1538 found_send_max_memo = true
1539 }
1540 if Memo::try_from(memo).unwrap() == Memo::Empty {
1541 found_tx_empty_memo = true
1542 }
1543 });
1544 assert!(found_send_max_memo);
1545 assert!(!found_tx_empty_memo); let sent_note_ids = st
1549 .wallet()
1550 .get_sent_note_ids(&sent_tx_id, T::SHIELDED_PROTOCOL)
1551 .unwrap();
1552 assert_eq!(sent_note_ids.len(), 1);
1553
1554 let mut found_sent_empty_memo = false;
1556 let mut found_sent_max_memo = false;
1557 for sent_note_id in sent_note_ids {
1558 match st
1559 .wallet()
1560 .get_memo(sent_note_id)
1561 .expect("Memo retrieval should succeed")
1562 .as_ref()
1563 {
1564 Some(m) if m == &Memo::Empty => {
1565 found_sent_empty_memo = true;
1566 }
1567 Some(m) if m == &send_max_memo => {
1568 found_sent_max_memo = true;
1569 }
1570 Some(other) => panic!("Unexpected memo value: {other:?}"),
1571 None => panic!("Memo should not be stored as NULL"),
1572 }
1573 }
1574
1575 assert!(found_sent_max_memo);
1576 assert!(!found_sent_empty_memo);
1577
1578 assert_matches!(
1580 st.wallet()
1581 .get_memo(NoteId::new(sent_tx_id, T::SHIELDED_PROTOCOL, 12345)),
1582 Ok(None)
1583 );
1584
1585 let tx_history = st.wallet().get_tx_history().unwrap();
1586 assert_eq!(tx_history.len(), 2);
1587 {
1588 let tx_0 = &tx_history[0];
1589 assert_eq!(tx_0.total_spent(), Zatoshis::const_from_u64(0));
1590 assert_eq!(tx_0.total_received(), Zatoshis::const_from_u64(60000));
1591 }
1592
1593 {
1594 let tx_1 = &tx_history[1];
1595 assert_eq!(tx_1.total_spent(), Zatoshis::const_from_u64(60000));
1596 assert_eq!(tx_1.total_received(), Zatoshis::const_from_u64(0));
1597 }
1598
1599 let network = *st.network();
1600 assert_matches!(
1601 decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, None),
1602 Ok(_)
1603 );
1604}
1605
1606#[cfg(feature = "transparent-inputs")]
1615pub fn fails_to_send_max_spendable_to_transparent_with_memo<T: ShieldedPoolTester>(
1616 dsf: impl DataStoreFactory,
1617 cache: impl TestCache,
1618) {
1619 let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
1620
1621 st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60000));
1623
1624 let account = st.test_account().cloned().unwrap();
1625 let (default_addr, _) = account.usk().default_transparent_address();
1626
1627 let to: Address = Address::Transparent(default_addr);
1628
1629 let fee_rule = StandardFeeRule::Zip317;
1630
1631 let send_max_memo = "Test Send Max memo".parse::<Memo>().unwrap();
1632
1633 let addy = to.to_zcash_address(st.network());
1634 assert_matches!(
1635 st.propose_send_max_transfer(
1636 account.id(),
1637 &fee_rule,
1638 addy,
1639 Some(MemoBytes::from(send_max_memo.clone())),
1640 MaxSpendMode::Everything,
1641 ConfirmationsPolicy::MIN
1642 ),
1643 Err(data_api::error::Error::Payment(
1644 zip321::PaymentError::TransparentMemo
1645 ))
1646 );
1647}
1648
1649#[cfg(feature = "transparent-inputs")]
1659pub fn send_max_spendable_to_transparent<T: ShieldedPoolTester>(
1660 dsf: impl DataStoreFactory,
1661 cache: impl TestCache,
1662) {
1663 let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
1664
1665 let value = Zatoshis::const_from_u64(60000);
1667 st.add_a_single_note_checking_balance(value);
1668
1669 let account = st.test_account().cloned().unwrap();
1670 let to: Address = Address::Transparent(TransparentAddress::PublicKeyHash([0x7f; 20]));
1671
1672 let fee_rule = StandardFeeRule::Zip317;
1673
1674 let expected_fee = (marginal_fee_at_target(&st) * 3u64).unwrap();
1677 let expected_payment = (value - expected_fee).unwrap();
1678
1679 let addy = to.to_zcash_address(st.network());
1680 let proposal = st
1681 .propose_send_max_transfer(
1682 account.id(),
1683 &fee_rule,
1684 addy,
1685 None,
1686 MaxSpendMode::Everything,
1687 ConfirmationsPolicy::MIN,
1688 )
1689 .unwrap();
1690
1691 let steps: Vec<_> = proposal.steps().iter().cloned().collect();
1692 assert_eq!(steps.len(), 1);
1693 assert_eq!(steps[0].balance().fee_required(), expected_fee);
1694 assert_eq!(steps[0].balance().proposed_change(), []);
1695 assert_eq!(
1696 steps[0].payment_pools(),
1697 &std::collections::BTreeMap::from([(0, PoolType::TRANSPARENT)])
1698 );
1699 assert_matches!(
1700 steps[0].transaction_request().payments().get(&0),
1701 Some(payment) if payment.amount() == Some(expected_payment)
1702 );
1703
1704 st.create_proposed_expecting(&proposal, 1);
1705}
1706
1707#[cfg(feature = "transparent-inputs")]
1710pub fn send_max_fee_overflow_is_an_error<T: ShieldedPoolTester>(
1711 dsf: impl DataStoreFactory,
1712 cache: impl TestCache,
1713) {
1714 #[derive(Clone, Debug)]
1716 struct MaxMoneyFeeRule;
1717
1718 impl FeeRule for MaxMoneyFeeRule {
1719 type Error = Infallible;
1720
1721 fn fee_required<P: consensus::Parameters>(
1722 &self,
1723 _params: &P,
1724 _target_height: BlockHeight,
1725 _transparent_input_sizes: impl IntoIterator<Item = InputSize>,
1726 _transparent_output_sizes: impl IntoIterator<Item = usize>,
1727 _sapling_input_count: usize,
1728 _sapling_output_count: usize,
1729 _orchard_action_count: usize,
1730 _ironwood_action_count: usize,
1731 ) -> Result<Zatoshis, Self::Error> {
1732 Ok(Zatoshis::const_from_u64(MAX_MONEY))
1733 }
1734 }
1735
1736 let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
1737
1738 st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60000));
1740
1741 let account = st.test_account().cloned().unwrap();
1742
1743 let tex_addr = Address::Tex([0x4; 20]);
1746 let addy = tex_addr.to_zcash_address(st.network());
1747
1748 assert_matches!(
1749 st.propose_send_max_transfer(
1750 account.id(),
1751 &MaxMoneyFeeRule,
1752 addy,
1753 None,
1754 MaxSpendMode::Everything,
1755 ConfirmationsPolicy::MIN,
1756 ),
1757 Err(data_api::error::Error::NoteSelection(
1758 GreedyInputSelectorError::Balance(BalanceError::Overflow)
1759 ))
1760 );
1761}
1762
1763#[cfg(feature = "orchard")]
1774pub fn send_max_spends_inputs_across_pools<P0: ShieldedPoolTester, P1: ShieldedPoolTester>(
1775 ds_factory: impl DataStoreFactory,
1776 cache: impl TestCache,
1777) {
1778 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<P0>();
1779 let account = st.test_account().cloned().unwrap();
1780
1781 let p0_fvk = P0::test_account_fvk(&st);
1783 let p1_fvk = P1::test_account_fvk(&st);
1784 let note_value = Zatoshis::const_from_u64(350000);
1785 st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
1786 st.generate_next_block(&p1_fvk, AddressType::DefaultExternal, note_value);
1787 st.scan_cached_blocks(account.birthday().height(), 2);
1788
1789 let total = (note_value * 2u64).unwrap();
1790 assert_eq!(
1791 st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
1792 total
1793 );
1794
1795 let to: Address = P1::sk_default_address(&P1::sk(&[0xf5; 32]));
1796 let fee_rule = StandardFeeRule::Zip317;
1797
1798 let expected_fee = (marginal_fee_at_target(&st) * 4u64).unwrap();
1802 let expected_payment = (total - expected_fee).unwrap();
1803
1804 let addy = to.to_zcash_address(st.network());
1805 let proposal = st
1806 .propose_send_max_transfer(
1807 account.id(),
1808 &fee_rule,
1809 addy,
1810 None,
1811 MaxSpendMode::Everything,
1812 ConfirmationsPolicy::MIN,
1813 )
1814 .unwrap();
1815
1816 let steps: Vec<_> = proposal.steps().iter().cloned().collect();
1817 assert_eq!(steps.len(), 1);
1818 assert_eq!(steps[0].balance().fee_required(), expected_fee);
1819 assert_eq!(steps[0].balance().proposed_change(), []);
1820 assert_eq!(
1821 steps[0].payment_pools(),
1822 &BTreeMap::from([(0, PoolType::Shielded(P1::SHIELDED_PROTOCOL))])
1823 );
1824 assert_matches!(
1825 steps[0].transaction_request().payments().get(&0),
1826 Some(payment) if payment.amount() == Some(expected_payment)
1827 );
1828
1829 let input_notes = steps[0]
1831 .shielded_inputs()
1832 .expect("the proposal has shielded inputs")
1833 .notes();
1834 assert_eq!(input_notes.len(), 2);
1835 let input_pools = input_notes
1836 .iter()
1837 .map(|n| n.note().pool())
1838 .collect::<BTreeSet<_>>();
1839 assert_eq!(
1840 input_pools,
1841 BTreeSet::from([P0::SHIELDED_PROTOCOL, P1::SHIELDED_PROTOCOL])
1842 );
1843
1844 let txids = st.create_proposed_expecting(&proposal, 1);
1845
1846 let (h, _) = st.generate_next_block_including(txids[0]);
1848 st.scan_cached_blocks(h, 1);
1849 assert_eq!(st.get_total_balance(account.id()), Zatoshis::ZERO);
1850}
1851
1852#[cfg(feature = "orchard")]
1855const DUST_SHORTFALL_P0_NOTE_VALUE: Zatoshis = Zatoshis::const_from_u64(60_000);
1856#[cfg(feature = "orchard")]
1860const DUST_SHORTFALL_PAYMENT: Zatoshis = Zatoshis::const_from_u64(47_000);
1861#[cfg(feature = "orchard")]
1864const DUST_SHORTFALL_P1_NOTE_COVERING_FEE: Zatoshis = Zatoshis::const_from_u64(20_000);
1865#[cfg(feature = "orchard")]
1868const DUST_SHORTFALL_P1_NOTE_BELOW_FEE: Zatoshis = Zatoshis::const_from_u64(6_000);
1869
1870fn marginal_fee_at_target<C: TestCache, D: WalletTest + WalletWrite, P: Parameters>(
1872 st: &TestState<C, D, P>,
1873) -> Zatoshis {
1874 marginal_fee(st.network(), proposal_target_height(st))
1875}
1876
1877fn minimum_fee_at_target<C: TestCache, D: WalletTest + WalletWrite, P: Parameters>(
1880 st: &TestState<C, D, P>,
1881) -> Zatoshis {
1882 minimum_fee(st.network(), proposal_target_height(st))
1883}
1884
1885fn proposal_target_height<C: TestCache, D: WalletTest + WalletWrite, P: Parameters>(
1887 st: &TestState<C, D, P>,
1888) -> BlockHeight {
1889 st.wallet()
1890 .get_target_and_anchor_heights(NonZeroU32::MIN)
1891 .expect("the wallet can be read")
1892 .expect("the wallet knows its chain tip")
1893 .0
1894 .into()
1895}
1896
1897#[cfg(feature = "orchard")]
1900fn two_bundle_fee<C: TestCache, D: WalletTest + WalletWrite, P: Parameters>(
1901 st: &TestState<C, D, P>,
1902) -> Zatoshis {
1903 const BUNDLES: u64 = 2;
1904 const PADDED_ACTIONS_PER_BUNDLE: u64 = 2;
1905 (marginal_fee_at_target(st) * (BUNDLES * PADDED_ACTIONS_PER_BUNDLE)).unwrap()
1906}
1907
1908#[cfg(feature = "orchard")]
1912struct DustShortfallScenario<P0: ShieldedPoolTester, Cache, Dsf: DataStoreFactory> {
1913 st: TestDsl<dsl::TestScenario<P0, Cache, Dsf>>,
1914 recipient: Address,
1915 amount: Zatoshis,
1916 total: Zatoshis,
1918}
1919
1920#[cfg(feature = "orchard")]
1923fn dust_shortfall_across_pools<P0, P1, Cache, Dsf>(
1924 ds_factory: Dsf,
1925 cache: Cache,
1926 p1_note_value: Zatoshis,
1927) -> DustShortfallScenario<P0, Cache, Dsf>
1928where
1929 P0: ShieldedPoolTester,
1930 P1: ShieldedPoolTester,
1931 Cache: TestCache,
1932 Dsf: DataStoreFactory,
1933{
1934 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<P0>();
1935 let account = st.test_account().cloned().unwrap();
1936
1937 let p0_fvk = P0::test_account_fvk(&st);
1938 let p1_fvk = P1::test_account_fvk(&st);
1939 st.generate_next_block(
1940 &p0_fvk,
1941 AddressType::DefaultExternal,
1942 DUST_SHORTFALL_P0_NOTE_VALUE,
1943 );
1944 st.generate_next_block(&p1_fvk, AddressType::DefaultExternal, p1_note_value);
1945 st.scan_cached_blocks(account.birthday().height(), 2);
1946
1947 DustShortfallScenario {
1948 st,
1949 recipient: P0::sk_default_address(&P0::sk(&[0xf5; 32])),
1950 amount: DUST_SHORTFALL_PAYMENT,
1951 total: (DUST_SHORTFALL_P0_NOTE_VALUE + p1_note_value).unwrap(),
1952 }
1953}
1954
1955#[cfg(feature = "orchard")]
1965pub fn transfer_grows_across_pools_at_a_dust_shortfall<
1966 P0: ShieldedPoolTester,
1967 P1: ShieldedPoolTester,
1968>(
1969 ds_factory: impl DataStoreFactory,
1970 cache: impl TestCache,
1971) {
1972 let DustShortfallScenario {
1973 mut st,
1974 recipient,
1975 amount,
1976 total,
1977 } = dust_shortfall_across_pools::<P0, P1, _, _>(
1978 ds_factory,
1979 cache,
1980 DUST_SHORTFALL_P1_NOTE_COVERING_FEE,
1981 );
1982
1983 let expected_fee = two_bundle_fee(&st);
1984 let expected_change = (total - amount - expected_fee).unwrap();
1985
1986 let proposal = st.propose_transfer_to(&recipient, amount);
1987
1988 assert_eq!(proposal.steps().len(), 1);
1989 let step = &proposal.steps().head;
1990 assert_eq!(step.balance().fee_required(), expected_fee);
1991 assert_matches!(
1992 step.transaction_request().payments().get(&0),
1993 Some(payment) if payment.amount() == Some(amount)
1994 );
1995 let input_pools = step
1996 .shielded_inputs()
1997 .expect("the proposal has shielded inputs")
1998 .notes()
1999 .iter()
2000 .map(|n| n.note().pool())
2001 .collect::<BTreeSet<_>>();
2002 assert_eq!(
2003 input_pools,
2004 BTreeSet::from([P0::SHIELDED_PROTOCOL, P1::SHIELDED_PROTOCOL])
2005 );
2006 let change = step.balance().proposed_change();
2007 assert_eq!(change.len(), 1);
2008 assert_eq!(change[0].value(), expected_change);
2009
2010 let txids = st.create_proposed_expecting(&proposal, 1);
2011 let (h, _) = st.generate_next_block_including(txids[0]);
2012 st.scan_cached_blocks(h, 1);
2013 assert_eq!(st.get_total_balance(st.get_account().id()), expected_change);
2014}
2015
2016#[cfg(feature = "orchard")]
2025pub fn transfer_fails_across_pools_at_a_dust_shortfall<
2026 P0: ShieldedPoolTester,
2027 P1: ShieldedPoolTester,
2028>(
2029 ds_factory: impl DataStoreFactory,
2030 cache: impl TestCache,
2031) {
2032 let DustShortfallScenario {
2033 mut st,
2034 recipient,
2035 amount,
2036 total,
2037 } = dust_shortfall_across_pools::<P0, P1, _, _>(
2038 ds_factory,
2039 cache,
2040 DUST_SHORTFALL_P1_NOTE_BELOW_FEE,
2041 );
2042
2043 let required = (amount + two_bundle_fee(&st)).unwrap();
2044
2045 st.expect_insufficient_funds(&recipient, amount, total, required);
2046}
2047
2048#[cfg(not(feature = "transparent-inputs"))]
2051pub fn send_max_to_tex_fails_without_transparent_inputs<T: ShieldedPoolTester>(
2052 dsf: impl DataStoreFactory,
2053 cache: impl TestCache,
2054) {
2055 let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
2056
2057 st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60000));
2059
2060 let account = st.test_account().cloned().unwrap();
2061 let tex_addr = Address::Tex([0x4; 20]);
2062 let fee_rule = StandardFeeRule::Zip317;
2063
2064 let addy = tex_addr.to_zcash_address(st.network());
2065 assert_matches!(
2066 st.propose_send_max_transfer(
2067 account.id(),
2068 &fee_rule,
2069 addy,
2070 None,
2071 MaxSpendMode::Everything,
2072 ConfirmationsPolicy::MIN,
2073 ),
2074 Err(data_api::error::Error::NoteSelection(
2075 GreedyInputSelectorError::UnsupportedTexAddress
2076 ))
2077 );
2078}
2079
2080#[cfg(not(feature = "orchard"))]
2084pub fn send_max_delivers_via_sapling_when_orchard_is_unavailable<T: ShieldedPoolTester>(
2085 dsf: impl DataStoreFactory,
2086 cache: impl TestCache,
2087) {
2088 let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
2089
2090 let value = Zatoshis::const_from_u64(60000);
2092 st.add_a_single_note_checking_balance(value);
2093
2094 let account = st.test_account().cloned().unwrap();
2095
2096 let sapling_receiver = match T::sk_default_address(&T::sk(&[0xf5; 32])) {
2100 Address::Sapling(addr) => addr.to_bytes(),
2101 _ => panic!("expected a Sapling address"),
2102 };
2103 let ua = unified::Address::try_from_items(
2104 Revision::R0,
2105 vec![
2106 Uitem::Data(Receiver::Sapling(sapling_receiver)),
2107 Uitem::Data(Receiver::Orchard([0xab; 43])),
2108 ],
2109 )
2110 .unwrap();
2111 let addy = ZcashAddress::try_from_encoded(&ua.encode(&st.network().network_type())).unwrap();
2112
2113 let fee_rule = StandardFeeRule::Zip317;
2114
2115 let expected_fee = minimum_fee_at_target(&st);
2118 let expected_payment = (value - expected_fee).unwrap();
2119
2120 let proposal = st
2121 .propose_send_max_transfer(
2122 account.id(),
2123 &fee_rule,
2124 addy,
2125 None,
2126 MaxSpendMode::Everything,
2127 ConfirmationsPolicy::MIN,
2128 )
2129 .unwrap();
2130
2131 let steps: Vec<_> = proposal.steps().iter().cloned().collect();
2132 assert_eq!(steps.len(), 1);
2133 assert_eq!(steps[0].balance().fee_required(), expected_fee);
2134 assert_eq!(
2135 steps[0].payment_pools(),
2136 &std::collections::BTreeMap::from([(0, PoolType::SAPLING)])
2137 );
2138 assert_matches!(
2139 steps[0].transaction_request().payments().get(&0),
2140 Some(payment) if payment.amount() == Some(expected_payment)
2141 );
2142
2143 st.create_proposed_expecting(&proposal, 1);
2144}
2145
2146#[cfg(not(feature = "orchard"))]
2150pub fn send_max_to_orchard_only_ua_fails_without_orchard<T: ShieldedPoolTester>(
2151 dsf: impl DataStoreFactory,
2152 cache: impl TestCache,
2153) {
2154 let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
2155
2156 st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60000));
2158
2159 let account = st.test_account().cloned().unwrap();
2160
2161 let ua = unified::Address::try_from_items(
2164 Revision::R0,
2165 vec![Uitem::Data(Receiver::Orchard([0xab; 43]))],
2166 )
2167 .unwrap();
2168 let addy = ZcashAddress::try_from_encoded(&ua.encode(&st.network().network_type())).unwrap();
2169
2170 let fee_rule = StandardFeeRule::Zip317;
2171
2172 assert_matches!(
2173 st.propose_send_max_transfer(
2174 account.id(),
2175 &fee_rule,
2176 addy,
2177 None,
2178 MaxSpendMode::Everything,
2179 ConfirmationsPolicy::MIN,
2180 ),
2181 Err(data_api::error::Error::NoteSelection(
2182 GreedyInputSelectorError::UnsupportedAddress(_)
2183 ))
2184 );
2185}
2186
2187pub fn send_max_fails_when_balance_is_consumed_by_fees<T: ShieldedPoolTester>(
2191 dsf: impl DataStoreFactory,
2192 cache: impl TestCache,
2193) {
2194 let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
2195
2196 let account = st.test_account().cloned().unwrap();
2199 let value = minimum_fee(st.network(), account.birthday().height() + 1);
2200 st.add_a_single_note_checking_balance(value);
2201
2202 let to: Address = T::sk_default_address(&T::sk(&[0xf5; 32]));
2203 let fee_rule = StandardFeeRule::Zip317;
2204
2205 let addy = to.to_zcash_address(st.network());
2206 assert_matches!(
2207 st.propose_send_max_transfer(
2208 account.id(),
2209 &fee_rule,
2210 addy,
2211 None,
2212 MaxSpendMode::Everything,
2213 ConfirmationsPolicy::MIN,
2214 ),
2215 Err(data_api::error::Error::InsufficientFunds { available, required })
2216 if available == value && required > value
2217 );
2218}
2219
2220pub fn spend_everything_proposal_fails_when_unconfirmed_funds_present<T: ShieldedPoolTester>(
2233 dsf: impl DataStoreFactory,
2234 cache: impl TestCache,
2235) {
2236 let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
2237 st.add_notes_checking_balance([
2238 Some(Zatoshis::const_from_u64(60000)),
2239 None,
2240 None,
2241 Some(Zatoshis::const_from_u64(123456)),
2242 ]);
2243
2244 let account = st.test_account().cloned().unwrap();
2246 let total_balance = st.get_total_balance(account.id());
2247 let spendable_balance = st.get_spendable_balance(
2248 account.id(),
2249 ConfirmationsPolicy::new_symmetrical_unchecked(
2250 2,
2251 #[cfg(feature = "transparent-inputs")]
2252 true,
2253 ),
2254 );
2255 assert_ne!(total_balance, spendable_balance);
2256
2257 let to_extsk = T::sk(&[0xf5; 32]);
2258 let to: Address = T::sk_default_address(&to_extsk);
2259
2260 let fee_rule = StandardFeeRule::Zip317;
2261
2262 let send_max_memo = "Test Send Max memo".parse::<Memo>().unwrap();
2263
2264 let addy = to.to_zcash_address(st.network());
2265 assert_matches!(
2266 st.propose_send_max_transfer(
2267 account.id(),
2268 &fee_rule,
2269 addy,
2270 Some(MemoBytes::from(send_max_memo.clone())),
2271 MaxSpendMode::Everything,
2272 ConfirmationsPolicy::new_symmetrical_unchecked(
2273 2,
2274 #[cfg(feature = "transparent-inputs")]
2275 true
2276 )
2277 ),
2278 Err(data_api::error::Error::DataSource(_))
2279 );
2280}
2281
2282pub fn send_max_spendable_proposal_succeeds_when_unconfirmed_funds_present<
2294 T: ShieldedPoolTester,
2295>(
2296 dsf: impl DataStoreFactory,
2297 cache: impl TestCache,
2298) {
2299 let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
2300 let h = st
2301 .add_notes_checking_balance([
2302 Some(Zatoshis::const_from_u64(60000)),
2303 None,
2304 None,
2305 Some(Zatoshis::const_from_u64(123456)),
2306 ])
2307 .block_height()
2308 .unwrap();
2309
2310 let account = st.test_account().cloned().unwrap();
2312 let total_balance = st.get_total_balance(account.id());
2313 let spendable_balance = st.get_spendable_balance(
2314 account.id(),
2315 ConfirmationsPolicy::new_symmetrical_unchecked(
2316 2,
2317 #[cfg(feature = "transparent-inputs")]
2318 true,
2319 ),
2320 );
2321 assert_ne!(total_balance, spendable_balance);
2322
2323 let to_extsk = T::sk(&[0xf5; 32]);
2324 let to: Address = T::sk_default_address(&to_extsk);
2325
2326 let fee_rule = StandardFeeRule::Zip317;
2327
2328 let send_max_memo = "Test Send Max memo".parse::<Memo>().unwrap();
2329
2330 let addy = to.to_zcash_address(st.network());
2331 let proposal = st
2332 .propose_send_max_transfer(
2333 account.id(),
2334 &fee_rule,
2335 addy,
2336 Some(MemoBytes::from(send_max_memo.clone())),
2337 MaxSpendMode::MaxSpendable,
2338 ConfirmationsPolicy::new_symmetrical_unchecked(
2339 2,
2340 #[cfg(feature = "transparent-inputs")]
2341 true,
2342 ),
2343 )
2344 .unwrap();
2345
2346 let sent_tx_id = st.create_proposed_expecting(&proposal, 1)[0];
2347
2348 let tx = st
2350 .wallet()
2351 .get_transaction(sent_tx_id)
2352 .unwrap()
2353 .expect("Created transaction was stored.");
2354 let ufvks = [(account.id(), account.usk().to_unified_full_viewing_key())]
2355 .into_iter()
2356 .collect();
2357 let d_tx = decrypt_transaction(st.network(), None, Some(h), &tx, &ufvks);
2358 assert_eq!(T::decrypted_pool_outputs_count(&d_tx), 1);
2359
2360 let mut found_send_max_memo = false;
2361 let mut found_tx_empty_memo = false;
2362 T::with_decrypted_pool_memos(&d_tx, |memo| {
2363 if Memo::try_from(memo).unwrap() == send_max_memo {
2364 found_send_max_memo = true
2365 }
2366 if Memo::try_from(memo).unwrap() == Memo::Empty {
2367 found_tx_empty_memo = true
2368 }
2369 });
2370 assert!(found_send_max_memo);
2371 assert!(!found_tx_empty_memo); let sent_note_ids = st
2375 .wallet()
2376 .get_sent_note_ids(&sent_tx_id, T::SHIELDED_PROTOCOL)
2377 .unwrap();
2378 assert_eq!(sent_note_ids.len(), 1);
2379
2380 let mut found_sent_empty_memo = false;
2382 let mut found_sent_max_memo = false;
2383 for sent_note_id in sent_note_ids {
2384 match st
2385 .wallet()
2386 .get_memo(sent_note_id)
2387 .expect("Memo retrieval should succeed")
2388 .as_ref()
2389 {
2390 Some(m) if m == &Memo::Empty => {
2391 found_sent_empty_memo = true;
2392 }
2393 Some(m) if m == &send_max_memo => {
2394 found_sent_max_memo = true;
2395 }
2396 Some(other) => panic!("Unexpected memo value: {other:?}"),
2397 None => panic!("Memo should not be stored as NULL"),
2398 }
2399 }
2400
2401 assert!(found_sent_max_memo);
2402 assert!(!found_sent_empty_memo);
2403
2404 assert_matches!(
2406 st.wallet()
2407 .get_memo(NoteId::new(sent_tx_id, T::SHIELDED_PROTOCOL, 12345)),
2408 Ok(None)
2409 );
2410
2411 let tx_history = st.wallet().get_tx_history().unwrap();
2412 assert_eq!(tx_history.len(), 2);
2413 {
2414 let tx_0 = &tx_history[0];
2415 assert_eq!(tx_0.total_spent(), Zatoshis::const_from_u64(0));
2416 assert_eq!(tx_0.total_received(), Zatoshis::const_from_u64(60000));
2417 }
2418
2419 {
2420 let tx_1 = &tx_history[1];
2421 assert_eq!(tx_1.total_spent(), Zatoshis::const_from_u64(60000));
2422 assert_eq!(tx_1.total_received(), Zatoshis::const_from_u64(0));
2423 }
2424
2425 let network = *st.network();
2426 assert_matches!(
2427 decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, None),
2428 Ok(_)
2429 );
2430}
2431
2432#[cfg(feature = "transparent-inputs")]
2435pub fn spend_everything_multi_step_single_note_proposed_transfer<T: ShieldedPoolTester, Dsf>(
2436 ds_factory: Dsf,
2437 cache: impl TestCache,
2438) where
2439 Dsf: DataStoreFactory,
2440 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
2441{
2442 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache)
2443 .map(|builder| builder.with_gap_limits(GapLimits::new(10, 5, 3)))
2444 .build::<T>();
2445
2446 let account = st.test_account().cloned().unwrap();
2447 let account_id = account.id();
2448
2449 let value = Zatoshis::const_from_u64(100000);
2450
2451 st.add_a_single_note_checking_balance(value);
2453 let initial_balance = value;
2454 assert_eq!(
2455 st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
2456 initial_balance
2457 );
2458
2459 let expected_step0_fee = (marginal_fee_at_target(&st) * 3u64).unwrap();
2460 let expected_step1_fee = minimum_fee_at_target(&st);
2461 let expected_ephemeral_spend = (value - expected_step0_fee - expected_step1_fee).unwrap();
2462 let expected_ephemeral_balance = (value - expected_step0_fee).unwrap();
2463 let expected_step0_change = (value - expected_step0_fee).unwrap();
2464
2465 let total_sent = (expected_step0_fee + expected_step1_fee + expected_ephemeral_spend).unwrap();
2466
2467 assert_eq!(total_sent, value);
2470
2471 let tex_addr = Address::Tex([0x4; 20]);
2473
2474 let fee_rule = StandardFeeRule::Zip317;
2477
2478 let addy = tex_addr.to_zcash_address(st.network());
2481 let proposal = st
2482 .propose_send_max_transfer(
2483 account_id,
2484 &fee_rule,
2485 addy,
2486 None,
2487 MaxSpendMode::Everything,
2488 ConfirmationsPolicy::MIN,
2489 )
2490 .unwrap();
2491
2492 let steps: Vec<_> = proposal.steps().iter().cloned().collect();
2493 assert_eq!(steps.len(), 2);
2494
2495 assert_eq!(steps[0].balance().fee_required(), expected_step0_fee);
2496 assert_eq!(steps[1].balance().fee_required(), expected_step1_fee);
2497 assert_eq!(
2498 steps[0].balance().proposed_change(),
2499 [
2500 ChangeValue::ephemeral_transparent(
2507 (total_sent - expected_step0_fee).expect("value is non-zero")
2508 ),
2509 ]
2510 );
2511 assert_eq!(steps[1].balance().proposed_change(), []);
2512
2513 let txids = st.create_proposed_expecting(&proposal, 2);
2514
2515 for txid in txids.iter() {
2517 let (h, _) = st.generate_next_block_including(*txid);
2518 st.scan_cached_blocks(h, 1);
2519 }
2520
2521 let confirmed_sent: Vec<Vec<_>> = txids
2523 .iter()
2524 .map(|sent_txid| st.wallet().get_sent_outputs(sent_txid).unwrap())
2525 .collect();
2526
2527 let tx_data_requests = st.wallet().transaction_data_requests().unwrap();
2530 assert!(tx_data_requests.contains(&TransactionDataRequest::GetStatus(*txids.last())));
2531
2532 assert!(expected_step0_change > expected_ephemeral_spend);
2533 assert_eq!(confirmed_sent.len(), 2);
2534 assert_eq!(confirmed_sent[0].len(), 1);
2535 assert_eq!(confirmed_sent[0][0].value, expected_step0_change);
2536 let OutputOfSentTx {
2537 value: ephemeral_v, ..
2538 } = confirmed_sent[0][0].clone();
2539 assert_eq!(ephemeral_v, expected_ephemeral_balance);
2540
2541 assert_eq!(confirmed_sent[1].len(), 1);
2542 assert_matches!(
2543 &confirmed_sent[1][0],
2544 OutputOfSentTx { value: sent_v, external_recipient: sent_to_addr, ephemeral_address: None }
2545 if sent_v == &expected_ephemeral_spend && sent_to_addr == &Some(tex_addr));
2546
2547 let tx_history = st.wallet().get_tx_history().unwrap();
2549
2550 let tx_0 = tx_history
2551 .iter()
2552 .find(|tx| tx.txid() == *txids.first())
2553 .unwrap();
2554 let tx_1 = tx_history
2555 .iter()
2556 .find(|tx| tx.txid() == *txids.last())
2557 .unwrap();
2558
2559 assert_eq!(tx_0.account_id(), &account_id);
2560 assert!(!tx_0.expired_unmined());
2561 assert_eq!(tx_0.has_change(), expected_step0_change.is_zero());
2562 assert!(!tx_0.is_shielding());
2563 assert_eq!(
2564 tx_0.account_value_delta(),
2565 -ZatBalance::from(expected_step0_fee),
2566 );
2567
2568 assert_eq!(tx_1.account_id(), &account_id);
2569 assert!(!tx_1.expired_unmined());
2570 assert!(!tx_1.has_change());
2571 assert!(!tx_0.is_shielding());
2572 assert_eq!(
2573 tx_1.account_value_delta(),
2574 -ZatBalance::from(expected_ephemeral_balance),
2575 );
2576
2577 let ending_balance = st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN);
2578 assert_eq!(initial_balance - total_sent, ending_balance.into());
2579}
2580
2581#[cfg(feature = "transparent-inputs")]
2584pub fn spend_everything_multi_step_many_notes_proposed_transfer<T: ShieldedPoolTester, Dsf>(
2585 ds_factory: Dsf,
2586 cache: impl TestCache,
2587) where
2588 Dsf: DataStoreFactory,
2589 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
2590{
2591 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache)
2592 .map(|builder| builder.with_gap_limits(GapLimits::new(10, 5, 3)))
2593 .build::<T>();
2594
2595 let number_of_notes = 3u64;
2596 let note_value = Zatoshis::const_from_u64(100000);
2597 let value = (note_value * number_of_notes).unwrap();
2598
2599 for _ in 0..number_of_notes {
2601 st.add_a_single_note_checking_balance(note_value);
2602 }
2603
2604 let initial_balance = value;
2605 let account = st.test_account().cloned().unwrap();
2606 let account_id = account.id();
2607 assert_eq!(
2608 st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
2609 initial_balance
2610 );
2611
2612 let expected_step0_fee = (marginal_fee_at_target(&st) * 4u64).unwrap();
2613 let expected_step1_fee = minimum_fee_at_target(&st);
2614 let expected_ephemeral_spend = (value - expected_step0_fee - expected_step1_fee).unwrap();
2615 let expected_ephemeral_balance = (value - expected_step0_fee).unwrap();
2616 let expected_step0_change = (value - expected_step0_fee).unwrap();
2617
2618 let total_sent = (expected_step0_fee + expected_step1_fee + expected_ephemeral_spend).unwrap();
2619
2620 assert_eq!(total_sent, value);
2623
2624 let tex_addr = Address::Tex([0x4; 20]);
2626 let fee_rule = StandardFeeRule::Zip317;
2627
2628 let addy = tex_addr.to_zcash_address(st.network());
2631 let proposal = st
2632 .propose_send_max_transfer(
2633 account_id,
2634 &fee_rule,
2635 addy,
2636 None,
2637 MaxSpendMode::Everything,
2638 ConfirmationsPolicy::MIN,
2639 )
2640 .unwrap();
2641
2642 let steps: Vec<_> = proposal.steps().iter().cloned().collect();
2643 assert_eq!(steps.len(), 2);
2644
2645 assert_eq!(steps[0].balance().fee_required(), expected_step0_fee);
2646 assert_eq!(steps[1].balance().fee_required(), expected_step1_fee);
2647 assert_eq!(
2648 steps[0].balance().proposed_change(),
2649 [ChangeValue::ephemeral_transparent(
2650 (total_sent - expected_step0_fee).expect("value is non-zero")
2651 ),]
2652 );
2653 assert_eq!(steps[1].balance().proposed_change(), []);
2654
2655 let txids = st.create_proposed_expecting(&proposal, 2);
2656
2657 for txid in txids.iter() {
2659 let (h, _) = st.generate_next_block_including(*txid);
2660 st.scan_cached_blocks(h, 1);
2661 }
2662
2663 let confirmed_sent: Vec<Vec<_>> = txids
2665 .iter()
2666 .map(|sent_txid| st.wallet().get_sent_outputs(sent_txid).unwrap())
2667 .collect();
2668
2669 let tx_data_requests = st.wallet().transaction_data_requests().unwrap();
2672 assert!(tx_data_requests.contains(&TransactionDataRequest::GetStatus(*txids.last())));
2673
2674 assert!(expected_step0_change > expected_ephemeral_spend);
2675 assert_eq!(confirmed_sent.len(), 2);
2676 assert_eq!(confirmed_sent[0].len(), 1);
2677 assert_eq!(confirmed_sent[0][0].value, expected_step0_change);
2678 let OutputOfSentTx {
2679 value: ephemeral_v, ..
2680 } = confirmed_sent[0][0].clone();
2681 assert_eq!(ephemeral_v, expected_ephemeral_balance);
2682
2683 assert_eq!(confirmed_sent[1].len(), 1);
2684 assert_matches!(
2685 &confirmed_sent[1][0],
2686 OutputOfSentTx { value: sent_v, external_recipient: sent_to_addr, ephemeral_address: None }
2687 if sent_v == &expected_ephemeral_spend && sent_to_addr == &Some(tex_addr));
2688
2689 let tx_history = st.wallet().get_tx_history().unwrap();
2691
2692 let tx_0 = tx_history
2693 .iter()
2694 .find(|tx| tx.txid() == *txids.first())
2695 .unwrap();
2696 let tx_1 = tx_history
2697 .iter()
2698 .find(|tx| tx.txid() == *txids.last())
2699 .unwrap();
2700
2701 assert_eq!(tx_0.account_id(), &account_id);
2702 assert!(!tx_0.expired_unmined());
2703 assert_eq!(tx_0.has_change(), expected_step0_change.is_zero());
2704 assert!(!tx_0.is_shielding());
2705 assert_eq!(
2706 tx_0.account_value_delta(),
2707 -ZatBalance::from(expected_step0_fee),
2708 );
2709
2710 assert_eq!(tx_1.account_id(), &account_id);
2711 assert!(!tx_1.expired_unmined());
2712 assert!(!tx_1.has_change());
2713 assert!(!tx_0.is_shielding());
2714 assert_eq!(
2715 tx_1.account_value_delta(),
2716 -ZatBalance::from(expected_ephemeral_balance),
2717 );
2718
2719 let ending_balance = st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN);
2720 assert_eq!(initial_balance - total_sent, ending_balance.into());
2721}
2722
2723#[cfg(feature = "transparent-inputs")]
2727pub fn spend_everything_multi_step_with_marginal_notes_proposed_transfer<
2728 T: ShieldedPoolTester,
2729 Dsf,
2730>(
2731 ds_factory: Dsf,
2732 cache: impl TestCache,
2733) where
2734 Dsf: DataStoreFactory,
2735 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
2736{
2737 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache)
2738 .map(|builder| builder.with_gap_limits(GapLimits::new(10, 5, 3)))
2739 .build::<T>();
2740
2741 let number_of_notes = 10u64;
2742 let note_value = Zatoshis::const_from_u64(100000);
2743 let non_marginal_notes_value =
2744 (note_value * number_of_notes).expect("sum of notes should not fail.");
2745
2746 for _ in 0..number_of_notes {
2747 st.add_a_single_note_checking_balance(note_value);
2748 let marginal_fee = marginal_fee_at_target(&st);
2749 st.add_a_single_note_checking_balance(marginal_fee);
2750 }
2751
2752 let account = st.test_account().cloned().unwrap();
2753 let account_id = account.id();
2754 assert_eq!(
2755 st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
2756 non_marginal_notes_value
2757 );
2758
2759 let expected_step0_fee = (marginal_fee_at_target(&st) * (number_of_notes + 1)).unwrap();
2760 let expected_step1_fee = minimum_fee_at_target(&st);
2761 let expected_ephemeral_spend =
2762 (non_marginal_notes_value - expected_step0_fee - expected_step1_fee).unwrap();
2763 let expected_ephemeral_balance = (non_marginal_notes_value - expected_step0_fee).unwrap();
2764 let expected_step0_change = (non_marginal_notes_value - expected_step0_fee).unwrap();
2765
2766 let total_sent = (expected_step0_fee + expected_step1_fee + expected_ephemeral_spend).unwrap();
2767
2768 assert_eq!(total_sent, non_marginal_notes_value);
2771
2772 let tex_addr = Address::Tex([0x4; 20]);
2774
2775 let fee_rule = StandardFeeRule::Zip317;
2776
2777 let addy = tex_addr.to_zcash_address(st.network());
2780 let proposal = st
2781 .propose_send_max_transfer(
2782 account_id,
2783 &fee_rule,
2784 addy,
2785 None,
2786 MaxSpendMode::Everything,
2787 ConfirmationsPolicy::MIN,
2788 )
2789 .unwrap();
2790
2791 let steps: Vec<_> = proposal.steps().iter().cloned().collect();
2792 assert_eq!(steps.len(), 2);
2793
2794 assert_eq!(
2795 steps[0].shielded_inputs().unwrap().notes().len() as u64,
2796 number_of_notes
2797 );
2798 assert_eq!(steps[0].balance().fee_required(), expected_step0_fee);
2799 assert_eq!(steps[1].balance().fee_required(), expected_step1_fee);
2800 assert_eq!(
2801 steps[0].balance().proposed_change(),
2802 [ChangeValue::ephemeral_transparent(
2803 (total_sent - expected_step0_fee).expect("value is non-zero")
2804 ),]
2805 );
2806 assert_eq!(steps[1].balance().proposed_change(), []);
2807
2808 let txids = st.create_proposed_expecting(&proposal, 2);
2809
2810 for txid in txids.iter() {
2812 let (h, _) = st.generate_next_block_including(*txid);
2813 st.scan_cached_blocks(h, 1);
2814 }
2815
2816 let confirmed_sent: Vec<Vec<_>> = txids
2818 .iter()
2819 .map(|sent_txid| st.wallet().get_sent_outputs(sent_txid).unwrap())
2820 .collect();
2821
2822 let tx_data_requests = st.wallet().transaction_data_requests().unwrap();
2825 assert!(tx_data_requests.contains(&TransactionDataRequest::GetStatus(*txids.last())));
2826
2827 assert!(expected_step0_change > expected_ephemeral_spend);
2828 assert_eq!(confirmed_sent.len(), 2);
2829 assert_eq!(confirmed_sent[0].len(), 1);
2830 assert_eq!(confirmed_sent[0][0].value, expected_step0_change);
2831 let OutputOfSentTx {
2832 value: ephemeral_v, ..
2833 } = confirmed_sent[0][0].clone();
2834 assert_eq!(ephemeral_v, expected_ephemeral_balance);
2835
2836 assert_eq!(confirmed_sent[1].len(), 1);
2837 assert_matches!(
2838 &confirmed_sent[1][0],
2839 OutputOfSentTx { value: sent_v, external_recipient: sent_to_addr, ephemeral_address: None }
2840 if sent_v == &expected_ephemeral_spend && sent_to_addr == &Some(tex_addr));
2841
2842 let tx_history = st.wallet().get_tx_history().unwrap();
2844
2845 let tx_0 = tx_history
2846 .iter()
2847 .find(|tx| tx.txid() == *txids.first())
2848 .unwrap();
2849 let tx_1 = tx_history
2850 .iter()
2851 .find(|tx| tx.txid() == *txids.last())
2852 .unwrap();
2853
2854 assert_eq!(tx_0.account_id(), &account_id);
2855 assert!(!tx_0.expired_unmined());
2856 assert_eq!(tx_0.has_change(), expected_step0_change.is_zero());
2857 assert!(!tx_0.is_shielding());
2858 assert_eq!(
2859 tx_0.account_value_delta(),
2860 -ZatBalance::from(expected_step0_fee),
2861 );
2862
2863 assert_eq!(tx_1.account_id(), &account_id);
2864 assert!(!tx_1.expired_unmined());
2865 assert!(!tx_1.has_change());
2866 assert!(!tx_0.is_shielding());
2867 assert_eq!(
2868 tx_1.account_value_delta(),
2869 -ZatBalance::from(expected_ephemeral_balance),
2870 );
2871
2872 let ending_balance = st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN);
2873 assert_eq!(ending_balance, Zatoshis::ZERO); }
2875
2876#[cfg(feature = "transparent-inputs")]
2885pub fn insufficient_funds_counts_transparent_inputs<T: ShieldedPoolTester>(
2886 dsf: impl DataStoreFactory,
2887 cache: impl TestCache,
2888) {
2889 let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
2890
2891 let note_value = Zatoshis::const_from_u64(50_000);
2892 let (h, _, _) = st.add_a_single_note_checking_balance(note_value);
2893
2894 let account = st.test_account().cloned().unwrap();
2895 let uaddr = st
2896 .wallet()
2897 .get_last_generated_address_matching(account.id(), UnifiedAddressRequest::AllAvailableKeys)
2898 .unwrap()
2899 .unwrap();
2900 let taddr = uaddr.transparent().unwrap();
2901
2902 let utxo_value = Zatoshis::const_from_u64(30_000);
2903 let utxo = WalletTransparentOutput::from_parts(
2904 OutPoint::fake(),
2905 TxOut::new(utxo_value, taddr.script().into()),
2906 Some(h),
2907 Some(account.id()),
2908 Some(TransparentKeyScope::EXTERNAL),
2909 None,
2910 )
2911 .unwrap();
2912 st.wallet_mut()
2913 .put_received_transparent_utxo(&utxo)
2914 .unwrap();
2915
2916 let to: Address = T::sk_default_address(&T::sk(&[0xf5; 32]));
2917 let amount = Zatoshis::const_from_u64(100_000);
2918 let request = TransactionRequest::new(vec![Payment::without_memo(
2919 to.to_zcash_address(st.network()),
2920 amount,
2921 )])
2922 .unwrap();
2923
2924 let input_selector = GreedyInputSelector::new();
2925 let change_strategy =
2926 single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
2927
2928 let expected_required = (amount + (marginal_fee_at_target(&st) * 3u64).unwrap()).unwrap();
2932 let expected_available = (note_value + utxo_value).unwrap();
2933
2934 assert_matches!(
2935 st.propose_transfer_with_policy(
2936 account.id(),
2937 &input_selector,
2938 &change_strategy,
2939 request,
2940 ConfirmationsPolicy::MIN,
2941 &SpendPolicy::default().with_transparent(TransparentSpendPolicy::any_account_addr()),
2942 ),
2943 Err(Error::InsufficientFunds { available, required })
2944 if available == expected_available && required == expected_required
2945 );
2946}
2947
2948pub fn send_with_multiple_change_outputs<T: ShieldedPoolTester>(
2949 dsf: impl DataStoreFactory,
2950 cache: impl TestCache,
2951) {
2952 let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
2953
2954 let value = Zatoshis::const_from_u64(650_0000);
2956 let (h, _, _) = st.add_a_single_note_checking_balance(value);
2957
2958 let to_extsk = T::sk(&[0xf5; 32]);
2959 let to: Address = T::sk_default_address(&to_extsk);
2960 let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
2961 to.to_zcash_address(st.network()),
2962 Zatoshis::const_from_u64(100_0000),
2963 )])
2964 .unwrap();
2965
2966 let input_selector = GreedyInputSelector::new();
2967 let change_memo = "Test change memo".parse::<Memo>().unwrap();
2968 let change_strategy = fees::zip317::MultiOutputChangeStrategy::new(
2969 Zip317FeeRule::standard(),
2970 Some(change_memo.clone().into()),
2971 T::SHIELDED_PROTOCOL,
2972 DustOutputPolicy::default(),
2973 SplitPolicy::with_min_output_value(
2974 NonZeroUsize::new(2).unwrap(),
2975 Zatoshis::const_from_u64(100_0000),
2976 ),
2977 );
2978
2979 let account = st.test_account().cloned().unwrap();
2980 let proposal = st
2981 .propose_transfer(
2982 account.id(),
2983 &input_selector,
2984 &change_strategy,
2985 request.clone(),
2986 ConfirmationsPolicy::MIN,
2987 )
2988 .unwrap();
2989
2990 let step = &proposal.steps().head;
2991 assert_eq!(step.balance().proposed_change().len(), 2);
2992
2993 let create_proposed_result = st.create_proposed_transactions::<Infallible, _, Infallible, _>(
2994 account.usk(),
2995 OvkPolicy::Sender,
2996 &proposal,
2997 );
2998 assert_matches!(&create_proposed_result, Ok(txids) if txids.len() == 1);
2999
3000 let sent_tx_id = create_proposed_result.unwrap()[0];
3001
3002 let tx = st
3004 .wallet()
3005 .get_transaction(sent_tx_id)
3006 .unwrap()
3007 .expect("Created transaction was stored.");
3008 let ufvks = [(account.id(), account.usk().to_unified_full_viewing_key())]
3009 .into_iter()
3010 .collect();
3011 let d_tx = decrypt_transaction(st.network(), None, Some(h), &tx, &ufvks);
3012 assert_eq!(T::decrypted_pool_outputs_count(&d_tx), 3);
3013
3014 let mut found_tx_change_memo = false;
3015 let mut found_tx_empty_memo = false;
3016 T::with_decrypted_pool_memos(&d_tx, |memo| {
3017 if Memo::try_from(memo).unwrap() == change_memo {
3018 found_tx_change_memo = true
3019 }
3020 if Memo::try_from(memo).unwrap() == Memo::Empty {
3021 found_tx_empty_memo = true
3022 }
3023 });
3024 assert!(found_tx_change_memo);
3025 assert!(found_tx_empty_memo);
3026
3027 let sent_note_ids = st
3029 .wallet()
3030 .get_sent_note_ids(&sent_tx_id, T::SHIELDED_PROTOCOL)
3031 .unwrap();
3032 assert_eq!(sent_note_ids.len(), 3);
3033
3034 let mut change_memo_count = 0;
3037 let mut found_sent_empty_memo = false;
3038 for sent_note_id in sent_note_ids {
3039 match st
3040 .wallet()
3041 .get_memo(sent_note_id)
3042 .expect("Note id is valid")
3043 .as_ref()
3044 {
3045 Some(m) if m == &change_memo => {
3046 change_memo_count += 1;
3047 }
3048 Some(m) if m == &Memo::Empty => {
3049 found_sent_empty_memo = true;
3050 }
3051 Some(other) => panic!("Unexpected memo value: {other:?}"),
3052 None => panic!("Memo should not be stored as NULL"),
3053 }
3054 }
3055 assert_eq!(change_memo_count, 2);
3056 assert!(found_sent_empty_memo);
3057
3058 let tx_history = st.wallet().get_tx_history().unwrap();
3059 assert_eq!(tx_history.len(), 2);
3060 {
3061 let tx_0 = &tx_history[0];
3062 assert_eq!(tx_0.total_spent(), Zatoshis::const_from_u64(0));
3063 assert_eq!(tx_0.total_received(), Zatoshis::const_from_u64(650_0000));
3064 }
3065
3066 {
3067 let tx_1 = &tx_history[1];
3068 assert_eq!(tx_1.total_spent(), Zatoshis::const_from_u64(650_0000));
3069 assert_eq!(tx_1.total_received(), Zatoshis::const_from_u64(548_5000));
3070 assert_eq!(tx_1.fee_paid(), Some(Zatoshis::const_from_u64(15000)));
3071 }
3072
3073 let network = *st.network();
3074 assert_matches!(
3075 decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, None),
3076 Ok(_)
3077 );
3078
3079 let (h, _) = st.generate_next_block_including(sent_tx_id);
3080 st.scan_cached_blocks(h, 1);
3081
3082 let change_strategy = fees::zip317::MultiOutputChangeStrategy::new(
3085 Zip317FeeRule::standard(),
3086 Some(change_memo.into()),
3087 T::SHIELDED_PROTOCOL,
3088 DustOutputPolicy::default(),
3089 SplitPolicy::with_min_output_value(
3090 NonZeroUsize::new(8).unwrap(),
3091 Zatoshis::const_from_u64(10_0000),
3092 ),
3093 );
3094
3095 let proposal = st
3096 .propose_transfer(
3097 account.id(),
3098 &input_selector,
3099 &change_strategy,
3100 request,
3101 ConfirmationsPolicy::MIN,
3102 )
3103 .unwrap();
3104
3105 let step = &proposal.steps().head;
3106 assert_eq!(step.balance().proposed_change().len(), 7);
3107}
3108
3109#[cfg(feature = "transparent-inputs")]
3110pub fn send_multi_step_proposed_transfer<T: ShieldedPoolTester, Dsf>(
3111 ds_factory: Dsf,
3112 cache: impl TestCache,
3113 is_reached_gap_limit: impl Fn(&<Dsf::DataStore as WalletRead>::Error, Dsf::AccountId, u32) -> bool,
3114) where
3115 Dsf: DataStoreFactory,
3116{
3117 let gap_limits = GapLimits::new(10, 5, 3);
3118 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache)
3119 .map(|builder| builder.with_gap_limits(gap_limits))
3120 .build::<T>();
3121
3122 let account = st.test_account().cloned().unwrap();
3123 let account_id = account.id();
3124 let dfvk = T::test_account_fvk(&st);
3125 let tex_addr = Address::Tex([0x4; 20]);
3126
3127 let add_funds = |st: &mut TestState<_, Dsf::DataStore, _>, value| {
3128 let (h, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
3129 st.scan_cached_blocks(h, 1);
3130
3131 assert_eq!(
3132 st.wallet()
3133 .block_max_scanned()
3134 .unwrap()
3135 .unwrap()
3136 .block_height(),
3137 h
3138 );
3139 h
3140 };
3141
3142 let value = Zatoshis::const_from_u64(100000);
3143 let transfer_amount = Zatoshis::const_from_u64(50000);
3144
3145 let run_test = |st: &mut TestState<_, Dsf::DataStore, _>, expected_index, prior_balance| {
3146 add_funds(st, value);
3148 let initial_balance: Option<Zatoshis> = prior_balance + value;
3149 assert_eq!(
3150 st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
3151 initial_balance.unwrap()
3152 );
3153
3154 let expected_step0_fee = (marginal_fee_at_target(st) * 3u64).unwrap();
3155 let expected_step1_fee = minimum_fee_at_target(st);
3156 let expected_ephemeral = (transfer_amount + expected_step1_fee).unwrap();
3157 let expected_step0_change =
3158 (initial_balance - expected_ephemeral - expected_step0_fee).expect("sufficient funds");
3159 assert!(expected_step0_change.is_positive());
3160
3161 let total_sent = (expected_step0_fee + expected_step1_fee + transfer_amount).unwrap();
3162
3163 let change_memo = Some(Memo::from_str("change").expect("valid memo").encode());
3166
3167 let proposal = st
3170 .propose_standard_transfer::<Infallible>(
3171 account_id,
3172 StandardFeeRule::Zip317,
3173 ConfirmationsPolicy::MIN,
3174 &tex_addr,
3175 transfer_amount,
3176 None,
3177 change_memo.clone(),
3178 T::SHIELDED_PROTOCOL,
3179 )
3180 .unwrap();
3181
3182 let steps: Vec<_> = proposal.steps().iter().cloned().collect();
3183 assert_eq!(steps.len(), 2);
3184
3185 assert_eq!(steps[0].balance().fee_required(), expected_step0_fee);
3186 assert_eq!(steps[1].balance().fee_required(), expected_step1_fee);
3187 assert_eq!(
3188 steps[0].balance().proposed_change(),
3189 [
3190 ChangeValue::shielded(T::SHIELDED_PROTOCOL, expected_step0_change, change_memo),
3191 ChangeValue::ephemeral_transparent(expected_ephemeral),
3192 ]
3193 );
3194 assert_eq!(steps[1].balance().proposed_change(), []);
3195
3196 let exposed_at_tip = st
3198 .wallet()
3199 .get_ephemeral_transparent_receivers(account.account().id(), 1, false)
3200 .unwrap();
3201 assert_eq!(exposed_at_tip.len(), 0);
3202
3203 let create_proposed_result = st
3204 .create_proposed_transactions::<Infallible, _, Infallible, _>(
3205 account.usk(),
3206 OvkPolicy::Sender,
3207 &proposal,
3208 );
3209 assert_matches!(&create_proposed_result, Ok(txids) if txids.len() == 2);
3210 let txids = create_proposed_result.unwrap();
3211
3212 let exposed_at_tip = st
3214 .wallet()
3215 .get_ephemeral_transparent_receivers(account.account().id(), 1, false)
3216 .unwrap();
3217 assert_eq!(exposed_at_tip.len(), 1);
3218 let cur_height = st.wallet().chain_height().unwrap().unwrap();
3219 assert_matches!(
3220 exposed_at_tip.values().next().map(|m0| m0.exposure()),
3221 Some(Exposure::Exposed { at_height, .. }) if at_height == cur_height
3222 );
3223
3224 let exposed_at_tip = st
3226 .wallet()
3227 .get_ephemeral_transparent_receivers(account.account().id(), 1, true)
3228 .unwrap();
3229 assert!(exposed_at_tip.is_empty());
3230
3231 for txid in txids.iter() {
3233 let (h, _) = st.generate_next_block_including(*txid);
3234 st.scan_cached_blocks(h, 1);
3235 }
3236
3237 let confirmed_sent: Vec<Vec<_>> = txids
3239 .iter()
3240 .map(|sent_txid| st.wallet().get_sent_outputs(sent_txid).unwrap())
3241 .collect();
3242
3243 let tx_data_requests = st.wallet().transaction_data_requests().unwrap();
3246 assert!(tx_data_requests.contains(&TransactionDataRequest::GetStatus(*txids.last())));
3247
3248 assert!(expected_step0_change < expected_ephemeral);
3249 assert_eq!(confirmed_sent.len(), 2);
3250 assert_eq!(confirmed_sent[0].len(), 2);
3251 assert_eq!(confirmed_sent[0][0].value, expected_step0_change);
3252 let OutputOfSentTx {
3253 value: ephemeral_v,
3254 external_recipient: to_addr,
3255 ephemeral_address,
3256 } = confirmed_sent[0][1].clone();
3257 assert_eq!(ephemeral_v, expected_ephemeral);
3258 assert!(to_addr.is_some());
3259 assert_eq!(
3260 ephemeral_address,
3261 to_addr.map(|addr| (
3262 addr,
3263 NonHardenedChildIndex::const_from_index(expected_index)
3264 )),
3265 );
3266
3267 assert_eq!(confirmed_sent[1].len(), 1);
3268 assert_matches!(
3269 &confirmed_sent[1][0],
3270 OutputOfSentTx { value: sent_v, external_recipient: sent_to_addr, ephemeral_address: None }
3271 if sent_v == &transfer_amount && sent_to_addr.as_ref() == Some(&tex_addr));
3272
3273 let tx_history = st.wallet().get_tx_history().unwrap();
3275
3276 let tx_0 = tx_history
3277 .iter()
3278 .find(|tx| tx.txid() == *txids.first())
3279 .unwrap();
3280 let tx_1 = tx_history
3281 .iter()
3282 .find(|tx| tx.txid() == *txids.last())
3283 .unwrap();
3284
3285 assert_eq!(tx_0.account_id(), &account_id);
3286 assert!(!tx_0.expired_unmined());
3287 assert_eq!(tx_0.has_change(), expected_step0_change.is_positive());
3288 assert!(!tx_0.is_shielding());
3289 assert_eq!(
3290 tx_0.account_value_delta(),
3291 -ZatBalance::from(expected_step0_fee),
3292 );
3293
3294 assert_eq!(tx_1.account_id(), &account_id);
3295 assert!(!tx_1.expired_unmined());
3296 assert!(!tx_1.has_change());
3297 assert!(!tx_0.is_shielding());
3298 assert_eq!(
3299 tx_1.account_value_delta(),
3300 -ZatBalance::from(expected_ephemeral),
3301 );
3302
3303 let ending_balance = st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN);
3304 assert_eq!(initial_balance - total_sent, ending_balance.into());
3305
3306 (ephemeral_address.unwrap().0, txids, ending_balance)
3307 };
3308
3309 let (ephemeral0, _, bal_0) = run_test(&mut st, 0, Zatoshis::ZERO);
3311 let (ephemeral1, _, _) = run_test(&mut st, 1, bal_0);
3312 assert_ne!(ephemeral0, ephemeral1);
3313
3314 add_funds(&mut st, value);
3315
3316 assert_matches!(
3317 ephemeral0,
3318 Address::Transparent(TransparentAddress::PublicKeyHash(_))
3319 );
3320
3321 let known_addrs = st
3324 .wallet()
3325 .get_known_ephemeral_addresses(account_id, None)
3326 .unwrap();
3327 assert_eq!(
3328 known_addrs.len(),
3329 usize::try_from(gap_limits.ephemeral() + 2).unwrap()
3330 );
3331
3332 let known_set: HashSet<_> = known_addrs.iter().map(|(addr, _)| addr).collect();
3334 assert_eq!(known_set.len(), known_addrs.len());
3335 for (i, (_, meta)) in known_addrs.iter().enumerate() {
3337 assert_eq!(
3338 meta.source(),
3339 &TransparentAddressSource::Derived {
3340 scope: TransparentKeyScope::EPHEMERAL,
3341 address_index: NonHardenedChildIndex::from_index(i.try_into().unwrap()).unwrap(),
3342 }
3343 );
3344 }
3345
3346 let (colliding_addr, _) = &known_addrs[usize::try_from(gap_limits.ephemeral() - 1).unwrap()];
3347 let utxo_value = (value - minimum_fee_at_target(&st)).unwrap();
3348 let to = Address::from(*colliding_addr);
3349 let proposal = st.propose_transfer_to(&to, utxo_value);
3350
3351 let txids = st
3354 .create_proposed_transactions::<Infallible, _, Infallible, _>(
3355 account.usk(),
3356 OvkPolicy::Sender,
3357 &proposal,
3358 )
3359 .unwrap();
3360
3361 let (h, _) = st.generate_next_block_including(txids.head);
3364 st.scan_cached_blocks(h, 1);
3365 st.wallet_mut()
3366 .set_transaction_status(txids.head, TransactionStatus::Mined(h))
3367 .unwrap();
3368
3369 let new_known_addrs = st
3372 .wallet()
3373 .get_known_ephemeral_addresses(account_id, None)
3374 .unwrap();
3375 assert_eq!(
3376 new_known_addrs.len(),
3377 usize::try_from(gap_limits.ephemeral() * 2).unwrap()
3378 );
3379
3380 assert!(
3383 new_known_addrs
3384 .iter()
3385 .map(|a| a.0)
3386 .zip(known_addrs.iter().map(|a| a.0))
3387 .all(|(a, b)| a == b),
3388 "new_known_addrs must have known_addrs as its prefix"
3389 );
3390
3391 let reservation_should_succeed = |st: &mut TestState<_, Dsf::DataStore, _>, n: u32| {
3392 let reserved = st
3393 .wallet_mut()
3394 .reserve_next_n_ephemeral_addresses(account_id, n.try_into().unwrap())
3395 .unwrap();
3396 assert_eq!(reserved.len(), usize::try_from(n).unwrap());
3397 reserved
3398 };
3399 let reservation_should_fail =
3400 |st: &mut TestState<_, Dsf::DataStore, _>, n: u32, expected_bad_index| {
3401 assert_matches!(st
3402 .wallet_mut()
3403 .reserve_next_n_ephemeral_addresses(account_id, n.try_into().unwrap()),
3404 Err(e) if is_reached_gap_limit(&e, account_id, expected_bad_index));
3405 };
3406
3407 assert_matches!(
3408 known_addrs[usize::try_from(gap_limits.ephemeral()).unwrap()]
3409 .1
3410 .exposure(),
3411 Exposure::Unknown
3412 );
3413
3414 let next_reserved = reservation_should_succeed(&mut st, 1);
3415
3416 let gap_position = 0;
3418 let expected = &known_addrs[usize::try_from(gap_limits.ephemeral()).unwrap()];
3419 let actual = &next_reserved[usize::try_from(gap_position).unwrap()];
3420 assert_eq!(actual.0, expected.0);
3421 assert_eq!(actual.1.source(), expected.1.source());
3422 assert_eq!(expected.1.exposure(), Exposure::Unknown);
3423 assert_eq!(
3424 actual.1.exposure(),
3425 Exposure::Exposed {
3426 at_height: st.latest_block_height.unwrap(),
3427 gap_metadata: crate::wallet::GapMetadata::InGap {
3428 gap_position,
3429 gap_limit: gap_limits.ephemeral(),
3430 }
3431 }
3432 );
3433
3434 reservation_should_fail(&mut st, gap_limits.ephemeral(), gap_limits.ephemeral() * 2);
3439 reservation_should_succeed(&mut st, gap_limits.ephemeral() - 1);
3440 reservation_should_fail(&mut st, 1, gap_limits.ephemeral() * 2);
3442}
3443
3444pub fn spend_all_funds_single_step_proposed_transfer<T: ShieldedPoolTester>(
3455 dsf: impl DataStoreFactory,
3456 cache: impl TestCache,
3457) {
3458 let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
3459
3460 let value = Zatoshis::const_from_u64(60000);
3462 let (h, _, _) = st.add_a_single_note_checking_balance(value);
3463
3464 let spend_amount = Zatoshis::const_from_u64(50000);
3465 let to_extsk = T::sk(&[0xf5; 32]);
3466 let to: Address = T::sk_default_address(&to_extsk);
3467 let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
3468 to.to_zcash_address(st.network()),
3469 spend_amount,
3470 )])
3471 .unwrap();
3472
3473 let fee_rule = StandardFeeRule::Zip317;
3474
3475 let change_memo = "Test change memo".parse::<Memo>().unwrap();
3476 let change_strategy = standard::SingleOutputChangeStrategy::new(
3477 fee_rule,
3478 Some(change_memo.clone().into()),
3479 T::SHIELDED_PROTOCOL,
3480 DustOutputPolicy::default(),
3481 );
3482 let input_selector = GreedyInputSelector::new();
3483
3484 let account = st.test_account().cloned().unwrap();
3485 let proposal = st
3486 .propose_transfer(
3487 account.id(),
3488 &input_selector,
3489 &change_strategy,
3490 request,
3491 ConfirmationsPolicy::MIN,
3492 )
3493 .unwrap();
3494
3495 let sent_tx_id = st.create_proposed_expecting(&proposal, 1)[0];
3496
3497 let tx = st
3499 .wallet()
3500 .get_transaction(sent_tx_id)
3501 .unwrap()
3502 .expect("Created transaction was stored.");
3503 let ufvks = [(account.id(), account.usk().to_unified_full_viewing_key())]
3504 .into_iter()
3505 .collect();
3506 let d_tx = decrypt_transaction(st.network(), None, Some(h), &tx, &ufvks);
3507 assert_eq!(T::decrypted_pool_outputs_count(&d_tx), 2);
3508
3509 let mut found_tx_change_memo = false;
3510 let mut found_tx_empty_memo = false;
3511 T::with_decrypted_pool_memos(&d_tx, |memo| {
3512 if Memo::try_from(memo).unwrap() == change_memo {
3513 found_tx_change_memo = true
3514 }
3515 if Memo::try_from(memo).unwrap() == Memo::Empty {
3516 found_tx_empty_memo = true
3517 }
3518 });
3519 assert!(found_tx_change_memo);
3520 assert!(found_tx_empty_memo);
3521
3522 let sent_note_ids = st
3524 .wallet()
3525 .get_sent_note_ids(&sent_tx_id, T::SHIELDED_PROTOCOL)
3526 .unwrap();
3527 assert_eq!(sent_note_ids.len(), 2);
3528
3529 let mut found_sent_change_memo = false;
3532 let mut found_sent_empty_memo = false;
3533 for sent_note_id in sent_note_ids {
3534 match st
3535 .wallet()
3536 .get_memo(sent_note_id)
3537 .expect("Note id is valid")
3538 .as_ref()
3539 {
3540 Some(m) if m == &change_memo => {
3541 found_sent_change_memo = true;
3542 }
3543 Some(m) if m == &Memo::Empty => {
3544 found_sent_empty_memo = true;
3545 }
3546 Some(other) => panic!("Unexpected memo value: {other:?}"),
3547 None => panic!("Memo should not be stored as NULL"),
3548 }
3549 }
3550 assert!(found_sent_change_memo);
3551 assert!(found_sent_empty_memo);
3552
3553 assert_matches!(
3555 st.wallet()
3556 .get_memo(NoteId::new(sent_tx_id, T::SHIELDED_PROTOCOL, 12345)),
3557 Ok(None)
3558 );
3559
3560 let tx_history = st.wallet().get_tx_history().unwrap();
3561 assert_eq!(tx_history.len(), 2);
3562 {
3563 let tx_0 = &tx_history[0];
3564 assert_eq!(tx_0.total_spent(), Zatoshis::const_from_u64(0));
3565 assert_eq!(tx_0.total_received(), Zatoshis::const_from_u64(60000));
3566 }
3567
3568 {
3569 let tx_1 = &tx_history[1];
3570 assert_eq!(tx_1.total_spent(), Zatoshis::const_from_u64(60000));
3571 assert_eq!(tx_1.total_received(), Zatoshis::ZERO);
3572 }
3573
3574 let network = *st.network();
3575 assert_matches!(
3576 decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, None),
3577 Ok(_)
3578 );
3579}
3580#[cfg(feature = "transparent-inputs")]
3594pub fn spend_all_funds_multi_step_proposed_transfer<T: ShieldedPoolTester, Dsf>(
3595 ds_factory: Dsf,
3596 cache: impl TestCache,
3597) where
3598 Dsf: DataStoreFactory,
3599 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
3600{
3601 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache)
3602 .map(|builder| builder.with_gap_limits(GapLimits::new(10, 5, 3)))
3603 .build::<T>();
3604
3605 let account = st.test_account().cloned().unwrap();
3606 let account_id = account.id();
3607 let dfvk = T::test_account_fvk(&st);
3608
3609 let value = Zatoshis::const_from_u64(100000);
3610 let transfer_amount = Zatoshis::const_from_u64(75000);
3611
3612 let (h, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
3614 st.scan_cached_blocks(h, 1);
3615
3616 let initial_balance = value;
3617 assert_eq!(
3618 st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
3619 initial_balance
3620 );
3621
3622 let expected_step0_fee = (marginal_fee_at_target(&st) * 3u64).unwrap();
3623 let expected_step1_fee = minimum_fee_at_target(&st);
3624 let expected_ephemeral = (transfer_amount + expected_step1_fee).unwrap();
3625 let expected_step0_change =
3626 (initial_balance - expected_ephemeral - expected_step0_fee).expect("sufficient funds");
3627 assert!(expected_step0_change.is_zero());
3628
3629 let total_sent = (expected_step0_fee + expected_step1_fee + transfer_amount).unwrap();
3630
3631 let tex_addr = Address::Tex([0x4; 20]);
3633
3634 let change_memo: Option<MemoBytes> = None;
3635 let proposal = st.propose_transfer_to(&tex_addr, transfer_amount);
3638
3639 let steps: Vec<_> = proposal.steps().iter().cloned().collect();
3640 assert_eq!(steps.len(), 2);
3641
3642 assert_eq!(steps[0].balance().fee_required(), expected_step0_fee);
3643 assert_eq!(steps[1].balance().fee_required(), expected_step1_fee);
3644 assert_eq!(
3645 steps[0].balance().proposed_change(),
3646 [
3647 ChangeValue::shielded(T::SHIELDED_PROTOCOL, expected_step0_change, change_memo),
3648 ChangeValue::ephemeral_transparent(expected_ephemeral),
3649 ]
3650 );
3651 assert_eq!(steps[1].balance().proposed_change(), []);
3652
3653 let txids = st.create_proposed_expecting(&proposal, 2);
3654
3655 for txid in txids.iter() {
3657 let (h, _) = st.generate_next_block_including(*txid);
3658 st.scan_cached_blocks(h, 1);
3659 }
3660
3661 let confirmed_sent: Vec<Vec<_>> = txids
3663 .iter()
3664 .map(|sent_txid| st.wallet().get_sent_outputs(sent_txid).unwrap())
3665 .collect();
3666
3667 let tx_data_requests = st.wallet().transaction_data_requests().unwrap();
3670 assert!(tx_data_requests.contains(&TransactionDataRequest::GetStatus(*txids.last())));
3671
3672 assert!(expected_step0_change < expected_ephemeral);
3673 assert_eq!(confirmed_sent.len(), 2);
3674 assert_eq!(confirmed_sent[0].len(), 2);
3675 assert_eq!(confirmed_sent[0][0].value, expected_step0_change);
3676 let OutputOfSentTx {
3677 value: ephemeral_v,
3678 external_recipient: to_addr,
3679 ephemeral_address: _,
3680 } = confirmed_sent[0][1].clone();
3681 assert_eq!(ephemeral_v, expected_ephemeral);
3682 assert!(to_addr.is_some());
3683
3684 assert_eq!(confirmed_sent[1].len(), 1);
3685 assert_matches!(
3686 &confirmed_sent[1][0],
3687 OutputOfSentTx { value: sent_v, external_recipient: sent_to_addr, ephemeral_address: None }
3688 if sent_v == &transfer_amount && sent_to_addr == &Some(tex_addr));
3689
3690 let tx_history = st.wallet().get_tx_history().unwrap();
3692
3693 let tx_0 = tx_history
3694 .iter()
3695 .find(|tx| tx.txid() == *txids.first())
3696 .unwrap();
3697 let tx_1 = tx_history
3698 .iter()
3699 .find(|tx| tx.txid() == *txids.last())
3700 .unwrap();
3701
3702 assert_eq!(tx_0.account_id(), &account_id);
3703 assert!(!tx_0.expired_unmined());
3704 assert_eq!(tx_0.has_change(), expected_step0_change.is_zero());
3705 assert!(!tx_0.is_shielding());
3706 assert_eq!(
3707 tx_0.account_value_delta(),
3708 -ZatBalance::from(expected_step0_fee),
3709 );
3710
3711 assert_eq!(tx_1.account_id(), &account_id);
3712 assert!(!tx_1.expired_unmined());
3713 assert!(!tx_1.has_change());
3714 assert!(!tx_0.is_shielding());
3715 assert_eq!(
3716 tx_1.account_value_delta(),
3717 -ZatBalance::from(expected_ephemeral),
3718 );
3719
3720 let ending_balance = st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN);
3721 assert_eq!(initial_balance - total_sent, ending_balance.into());
3722}
3723
3724#[cfg(feature = "transparent-inputs")]
3725pub fn proposal_fails_if_not_all_ephemeral_outputs_consumed<T: ShieldedPoolTester, Dsf>(
3726 ds_factory: Dsf,
3727 cache: impl TestCache,
3728) where
3729 Dsf: DataStoreFactory,
3730{
3731 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
3732
3733 let account = st.test_account().cloned().unwrap();
3734 let account_id = account.id();
3735 let dfvk = T::test_account_fvk(&st);
3736
3737 let add_funds = |st: &mut TestState<_, Dsf::DataStore, _>, value| {
3738 let (h, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
3739 st.scan_cached_blocks(h, 1);
3740
3741 assert_eq!(
3742 st.wallet()
3743 .block_max_scanned()
3744 .unwrap()
3745 .unwrap()
3746 .block_height(),
3747 h
3748 );
3749 assert_eq!(
3750 st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
3751 value
3752 );
3753 };
3754
3755 let value = Zatoshis::const_from_u64(100000);
3756 let transfer_amount = Zatoshis::const_from_u64(50000);
3757
3758 add_funds(&mut st, value);
3760
3761 let tex_addr = Address::Tex([0x4; 20]);
3763 let proposal = st.propose_transfer_to(&tex_addr, transfer_amount);
3764
3765 let create_proposed_result = st.create_proposed_transactions::<Infallible, _, Infallible, _>(
3769 account.usk(),
3770 OvkPolicy::Sender,
3771 &proposal,
3772 );
3773 assert_matches!(create_proposed_result, Ok(_));
3774
3775 let frobbed_proposal = Proposal::multi_step(
3778 *proposal.fee_rule(),
3779 proposal.min_target_height(),
3780 proposal.confirmations_policy(),
3781 NonEmpty::singleton(proposal.steps().first().clone()),
3782 )
3783 .unwrap();
3784
3785 let create_proposed_result = st.create_proposed_transactions::<Infallible, _, Infallible, _>(
3786 account.usk(),
3787 OvkPolicy::Sender,
3788 &frobbed_proposal,
3789 );
3790 assert_matches!(
3791 create_proposed_result,
3792 Err(Error::Proposal(ProposalError::EphemeralOutputLeftUnspent(so)))
3793 if so == StepOutput::new(0, StepOutputIndex::Change(1))
3794 );
3795}
3796
3797pub fn create_to_address_fails_on_incorrect_usk<T: ShieldedPoolTester, Dsf: DataStoreFactory>(
3798 ds_factory: Dsf,
3799) {
3800 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, ()).build::<T>();
3801 let dfvk = T::test_account_fvk(&st);
3802 let to = T::fvk_default_address(&dfvk);
3803
3804 let acct1 = zip32::AccountId::try_from(1).unwrap();
3806 let usk1 = UnifiedSpendingKey::from_seed(st.network(), &[1u8; 32], acct1).unwrap();
3807
3808 let input_selector = GreedyInputSelector::<Dsf::DataStore>::new();
3809 let change_strategy =
3810 single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
3811
3812 let req = TransactionRequest::new(vec![Payment::without_memo(
3813 to.to_zcash_address(st.network()),
3814 Zatoshis::const_from_u64(1),
3815 )])
3816 .unwrap();
3817
3818 assert_matches!(
3820 st.spend(
3821 &input_selector,
3822 &change_strategy,
3823 &usk1,
3824 req,
3825 OvkPolicy::Sender,
3826 ConfirmationsPolicy::MIN,
3827 ),
3828 Err(data_api::error::Error::KeyNotRecognized)
3829 );
3830}
3831
3832pub fn proposal_fails_with_no_blocks<T: ShieldedPoolTester, Dsf>(ds_factory: Dsf)
3833where
3834 Dsf: DataStoreFactory,
3835 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
3836{
3837 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, ()).build::<T>();
3838
3839 let account_id = st.test_account().unwrap().id();
3840 let dfvk = T::test_account_fvk(&st);
3841 let to = T::fvk_default_address(&dfvk);
3842
3843 assert_eq!(st.get_wallet_summary(ConfirmationsPolicy::MIN), None);
3845
3846 assert_matches!(
3848 st.propose_standard_transfer::<Infallible>(
3849 account_id,
3850 StandardFeeRule::Zip317,
3851 ConfirmationsPolicy::MIN,
3852 &to,
3853 Zatoshis::const_from_u64(1),
3854 None,
3855 None,
3856 T::SHIELDED_PROTOCOL,
3857 ),
3858 Err(data_api::error::Error::ScanRequired)
3859 );
3860}
3861
3862pub fn spend_fails_on_unverified_notes<T: ShieldedPoolTester>(
3863 ds_factory: impl DataStoreFactory,
3864 cache: impl TestCache,
3865) {
3866 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
3867
3868 let account = st.test_account().cloned().unwrap();
3869 let account_id = account.id();
3870 let dfvk = T::test_account_fvk(&st);
3871
3872 let value = Zatoshis::const_from_u64(50000);
3874 st.add_a_single_note_checking_balance(value);
3875
3876 assert_eq!(
3878 st.get_pending_shielded_balance(account_id, ConfirmationsPolicy::default()),
3879 value
3880 );
3881 assert_eq!(
3882 st.get_spendable_balance(account_id, ConfirmationsPolicy::default()),
3883 Zatoshis::ZERO
3884 );
3885
3886 let no_recovery = Some(Ratio::new(0, 0));
3890
3891 let summary = st.get_wallet_summary(ConfirmationsPolicy::MIN);
3893 assert_eq!(
3894 summary.as_ref().and_then(|s| s.progress().recovery()),
3895 no_recovery,
3896 );
3897 assert_eq!(summary.map(|s| s.progress().scan()), Some(Ratio::new(1, 1)));
3898
3899 let (h2, _, _) = st.add_a_single_note_checking_balance(value);
3901
3902 let total = (value + value).unwrap();
3904 assert_eq!(
3905 st.get_spendable_balance(
3906 account_id,
3907 ConfirmationsPolicy::new_symmetrical_unchecked(
3908 2,
3909 #[cfg(feature = "transparent-inputs")]
3910 false
3911 )
3912 ),
3913 value
3914 );
3915 assert_eq!(
3916 st.get_pending_shielded_balance(
3917 account_id,
3918 ConfirmationsPolicy::new_symmetrical_unchecked(
3919 2,
3920 #[cfg(feature = "transparent-inputs")]
3921 false
3922 )
3923 ),
3924 value
3925 );
3926 assert_eq!(st.get_total_balance(account_id), total);
3927
3928 let summary = st.get_wallet_summary(ConfirmationsPolicy::MIN);
3930 assert_eq!(
3931 summary.as_ref().and_then(|s| s.progress().recovery()),
3932 no_recovery
3933 );
3934 assert_eq!(summary.map(|s| s.progress().scan()), Some(Ratio::new(2, 2)));
3935
3936 let extsk2 = T::sk(&[0xf5; 32]);
3938 let to = T::sk_default_address(&extsk2);
3939 st.expect_insufficient_funds_with(
3940 &to,
3941 Zatoshis::const_from_u64(70000),
3942 ConfirmationsPolicy::new_symmetrical_unchecked(
3943 2,
3944 #[cfg(feature = "transparent-inputs")]
3945 false,
3946 ),
3947 Zatoshis::const_from_u64(50000),
3948 Zatoshis::const_from_u64(80000),
3949 );
3950
3951 for _ in 2..10 {
3954 st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
3955 }
3956 st.scan_cached_blocks(h2 + 1, 8);
3957
3958 assert_eq!(st.get_total_balance(account_id), (value * 10u64).unwrap());
3960
3961 st.expect_insufficient_funds_with(
3963 &to,
3964 Zatoshis::const_from_u64(70000),
3965 ConfirmationsPolicy::default(),
3966 Zatoshis::const_from_u64(50000),
3967 Zatoshis::const_from_u64(80000),
3968 );
3969
3970 let (h11, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
3972 st.scan_cached_blocks(h11, 1);
3973
3974 assert_eq!(st.get_total_balance(account_id), (value * 11u64).unwrap());
3976 assert_eq!(
3978 st.get_spendable_balance(account_id, ConfirmationsPolicy::default()),
3979 (value * 2u64).unwrap()
3980 );
3981 assert_eq!(
3982 st.get_pending_shielded_balance(account_id, ConfirmationsPolicy::default()),
3983 (value * 9u64).unwrap()
3984 );
3985
3986 let amount_sent = Zatoshis::from_u64(70000).unwrap();
3988 let proposal = st
3989 .propose_standard_transfer::<Infallible>(
3990 account_id,
3991 StandardFeeRule::Zip317,
3992 ConfirmationsPolicy::default(),
3993 &to,
3994 amount_sent,
3995 None,
3996 None,
3997 T::SHIELDED_PROTOCOL,
3998 )
3999 .unwrap();
4000
4001 let txid = st
4003 .create_proposed_transactions::<Infallible, _, Infallible, _>(
4004 account.usk(),
4005 OvkPolicy::Sender,
4006 &proposal,
4007 )
4008 .unwrap()[0];
4009
4010 let (h, _) = st.generate_next_block_including(txid);
4011 st.scan_cached_blocks(h, 1);
4012
4013 assert_eq!(
4015 st.get_total_balance(account_id),
4016 ((value * 11u64).unwrap() - (amount_sent + Zatoshis::from_u64(10000).unwrap()).unwrap())
4017 .unwrap()
4018 );
4019}
4020
4021pub fn ovk_policy_prevents_recovery_from_chain<T: ShieldedPoolTester, Dsf>(
4022 ds_factory: Dsf,
4023 cache: impl TestCache,
4024) where
4025 Dsf: DataStoreFactory,
4026{
4027 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
4028
4029 let account = st.test_account().cloned().unwrap();
4030 let account_id = account.id();
4031 let dfvk = T::test_account_fvk(&st);
4032
4033 let value = Zatoshis::const_from_u64(50000);
4035 let (h1, _, _) = st.add_a_single_note_checking_balance(value);
4036
4037 let extsk2 = T::sk(&[0xf5; 32]);
4038 let addr2 = T::sk_default_address(&extsk2);
4039
4040 let fee_rule = StandardFeeRule::Zip317;
4041
4042 #[allow(clippy::type_complexity)]
4043 let send_and_recover_with_policy = |st: &mut TestState<_, Dsf::DataStore, _>,
4044 ovk_policy|
4045 -> Result<
4046 Option<(Note, Address, MemoBytes)>,
4047 TransferErrT<
4048 Dsf::DataStore,
4049 GreedyInputSelector<Dsf::DataStore>,
4050 SingleOutputChangeStrategy<Dsf::DataStore>,
4051 >,
4052 > {
4053 let proposal = st.propose_standard_transfer(
4054 account_id,
4055 fee_rule,
4056 ConfirmationsPolicy::MIN,
4057 &addr2,
4058 Zatoshis::const_from_u64(15000),
4059 None,
4060 None,
4061 T::SHIELDED_PROTOCOL,
4062 )?;
4063
4064 let txid = st.create_proposed_transactions(account.usk(), ovk_policy, &proposal)?[0];
4066
4067 let tx = st
4069 .wallet()
4070 .get_transaction(txid)
4071 .map_err(Error::DataSource)?
4072 .unwrap();
4073
4074 Ok(T::try_output_recovery(st.network(), h1, &tx, &dfvk))
4075 };
4076
4077 assert_matches!(
4080 send_and_recover_with_policy(&mut st, OvkPolicy::Sender),
4081 Ok(Some((_, recovered_to, _))) if recovered_to == addr2
4082 );
4083
4084 for i in 1..=42 {
4087 st.generate_next_block(
4088 &T::sk_to_fvk(&T::sk(&[i as u8; 32])),
4089 AddressType::DefaultExternal,
4090 value,
4091 );
4092 }
4093 st.scan_cached_blocks(h1 + 1, 42);
4094
4095 assert_matches!(
4098 send_and_recover_with_policy(&mut st, OvkPolicy::Discard),
4099 Ok(None)
4100 );
4101}
4102
4103pub fn spend_succeeds_to_t_addr_zero_change<T: ShieldedPoolTester>(
4104 ds_factory: impl DataStoreFactory,
4105 cache: impl TestCache,
4106) {
4107 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
4108
4109 let value = Zatoshis::const_from_u64(70000);
4111 st.add_a_single_note_checking_balance(value);
4112
4113 let to = TransparentAddress::PublicKeyHash([7; 20]).into();
4115 let account = st.test_account().cloned().unwrap();
4116 let amount_sent = Zatoshis::const_from_u64(50000);
4117 let proposal = st.propose_transfer_to(&to, amount_sent);
4118
4119 assert_matches!(
4121 st.create_proposed_transactions::<Infallible, _, Infallible, _>(account.usk(), OvkPolicy::Sender, &proposal),
4122 Ok(txids) if txids.len() == 1
4123 );
4124}
4125
4126pub fn change_note_spends_succeed<T: ShieldedPoolTester>(
4127 ds_factory: impl DataStoreFactory,
4128 cache: impl TestCache,
4129) {
4130 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
4131
4132 let value = Zatoshis::const_from_u64(70000);
4134 st.add_a_single_note_checking_balance(
4135 TestNoteConfig::from(value).with_address_type(AddressType::Internal),
4136 );
4137
4138 let account = st.test_account().cloned().unwrap();
4140 let account_id = account.id();
4141 assert_eq!(
4142 st.get_pending_shielded_balance(account_id, ConfirmationsPolicy::default()),
4143 value
4144 );
4145 assert_eq!(
4146 st.get_spendable_balance(account_id, ConfirmationsPolicy::default()),
4147 Zatoshis::ZERO
4148 );
4149
4150 let change_note_scope = st
4151 .wallet()
4152 .get_notes(T::SHIELDED_PROTOCOL)
4153 .unwrap()
4154 .iter()
4155 .find_map(|note| (note.note().value() == value).then_some(note.spending_key_scope()));
4156 assert_matches!(change_note_scope, Some(Scope::Internal));
4157
4158 let to = TransparentAddress::PublicKeyHash([7; 20]).into();
4160 let amount_sent = Zatoshis::const_from_u64(50000);
4161 let proposal = st.propose_transfer_to(&to, amount_sent);
4162
4163 assert_matches!(
4165 st.create_proposed_transactions::<Infallible, _, Infallible, _>(account.usk(), OvkPolicy::Sender, &proposal),
4166 Ok(txids) if txids.len() == 1
4167 );
4168}
4169
4170pub fn account_deletion<T: ShieldedPoolTester, DSF>(ds_factory: DSF, cache: impl TestCache)
4171where
4172 DSF: DataStoreFactory,
4173 <DSF as DataStoreFactory>::DataStore: Reset,
4174{
4175 let mut st = TestBuilder::new()
4176 .with_data_store_factory(ds_factory)
4177 .with_block_cache(cache)
4178 .build();
4179
4180 let seed = Secret::new([0u8; 32].to_vec());
4182 let birthday = AccountBirthday::from_sapling_activation(st.network(), BlockHash([0; 32]));
4183 let (account1, usk) = st
4184 .wallet_mut()
4185 .create_account("account1", &seed, &birthday, None)
4186 .unwrap();
4187 let dfvk = T::sk_to_fvk(T::usk_to_sk(&usk));
4188
4189 let (account2, usk2) = st
4190 .wallet_mut()
4191 .create_account("account2", &seed, &birthday, None)
4192 .unwrap();
4193 let dfvk2 = T::sk_to_fvk(T::usk_to_sk(&usk2));
4194
4195 let value = Zatoshis::from_u64(100000).unwrap();
4197 let (h, b0_result, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
4198 st.scan_cached_blocks(h, 1);
4199 let txid0 = *b0_result
4200 .txids()
4201 .first()
4202 .expect("A transaction was created.");
4203
4204 assert_eq!(st.get_total_balance(account1), value);
4206 assert_eq!(
4207 st.get_spendable_balance(account1, ConfirmationsPolicy::MIN),
4208 value
4209 );
4210 assert_eq!(st.get_total_balance(account2), Zatoshis::ZERO);
4211
4212 let bal_2 = Zatoshis::from_u64(50000).unwrap();
4213 let addr2 = T::fvk_default_address(&dfvk2);
4214 let req = TransactionRequest::new(vec![
4215 Payment::without_memo(addr2.to_zcash_address(st.network()), bal_2),
4217 ])
4218 .unwrap();
4219
4220 let change_strategy =
4221 single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
4222 let input_selector = GreedyInputSelector::new();
4223
4224 let txid1 = st
4225 .spend(
4226 &input_selector,
4227 &change_strategy,
4228 &usk,
4229 req,
4230 OvkPolicy::Sender,
4231 ConfirmationsPolicy::MIN,
4232 )
4233 .unwrap()[0];
4234
4235 let bal_1 = (value - (bal_2 + minimum_fee_at_target(&st)).unwrap()).unwrap();
4236 assert_eq!(st.get_total_balance(account1), bal_1);
4237
4238 let (h, _) = st.generate_next_block_including(txid1);
4239 st.scan_cached_blocks(h, 1);
4240
4241 assert_eq!(st.get_total_balance(account2), bal_2);
4242 assert_eq!(st.get_total_balance(account1), bal_1);
4243
4244 assert_matches!(st.wallet_mut().get_tx_height(txid0), Ok(Some(_)));
4247
4248 assert_matches!(st.wallet_mut().delete_account(account1), Ok(_));
4250
4251 assert_matches!(st.wallet_mut().get_tx_height(txid0), Ok(None));
4253
4254 assert_matches!(st.wallet_mut().get_transaction(txid1), Ok(Some(_)));
4256
4257 let summary = st
4258 .wallet()
4259 .get_wallet_summary(ConfirmationsPolicy::MIN)
4260 .unwrap()
4261 .unwrap();
4262 assert!(summary.account_balances().get(&account1).is_none());
4263 assert_eq!(
4264 summary.account_balances().get(&account2).unwrap().total(),
4265 bal_2
4266 );
4267 assert_eq!(
4268 summary
4269 .account_balances()
4270 .get(&account2)
4271 .unwrap()
4272 .spendable_value(),
4273 bal_2
4274 );
4275
4276 let (account3, usk3) = st
4278 .wallet_mut()
4279 .create_account("account3", &seed, &birthday, None)
4280 .unwrap();
4281 let dfvk3 = T::sk_to_fvk(T::usk_to_sk(&usk3));
4282
4283 st.scan_cached_blocks(birthday.height(), 2);
4285
4286 let bal_3 = Zatoshis::from_u64(20000).unwrap();
4287 let addr3 = T::fvk_default_address(&dfvk3);
4288 let req = TransactionRequest::new(vec![
4289 Payment::without_memo(addr3.to_zcash_address(st.network()), bal_3),
4291 ])
4292 .unwrap();
4293
4294 let txid2 = st
4295 .spend(
4296 &input_selector,
4297 &change_strategy,
4298 &usk2,
4299 req,
4300 OvkPolicy::Sender,
4301 ConfirmationsPolicy::MIN,
4302 )
4303 .unwrap()[0];
4304
4305 let bal_2_final = (bal_2 - (bal_3 + minimum_fee_at_target(&st)).unwrap()).unwrap();
4306 assert_eq!(st.get_total_balance(account2), bal_2_final);
4307
4308 let (h, _) = st.generate_next_block_including(txid2);
4309 st.scan_cached_blocks(h, 1);
4310
4311 assert_eq!(st.get_total_balance(account2), bal_2_final);
4312 assert_eq!(st.get_total_balance(account3), bal_3);
4313
4314 assert_matches!(st.wallet_mut().get_tx_height(txid2), Ok(Some(_)));
4317
4318 assert_matches!(st.wallet_mut().delete_account(account3), Ok(_));
4320
4321 assert_matches!(st.wallet_mut().get_transaction(txid2), Ok(Some(_)));
4323
4324 let summary = st
4325 .wallet()
4326 .get_wallet_summary(ConfirmationsPolicy::default())
4327 .unwrap()
4328 .unwrap();
4329 assert!(summary.account_balances().get(&account3).is_none());
4330 assert_eq!(
4331 summary.account_balances().get(&account2).unwrap().total(),
4332 bal_2_final
4333 );
4334}
4335
4336pub fn account_deletion_with_internal_transfer<T: ShieldedPoolTester, DSF>(
4349 ds_factory: DSF,
4350 cache: impl TestCache,
4351) where
4352 DSF: DataStoreFactory,
4353 <DSF as DataStoreFactory>::DataStore: Reset,
4354{
4355 let mut st = TestBuilder::new()
4356 .with_data_store_factory(ds_factory)
4357 .with_block_cache(cache)
4358 .build();
4359
4360 let seed = Secret::new([0u8; 32].to_vec());
4362 let birthday = AccountBirthday::from_sapling_activation(st.network(), BlockHash([0; 32]));
4363 let (account1, usk1) = st
4364 .wallet_mut()
4365 .create_account("account1", &seed, &birthday, None)
4366 .unwrap();
4367 let dfvk1 = T::sk_to_fvk(T::usk_to_sk(&usk1));
4368
4369 let (account2, usk2) = st
4370 .wallet_mut()
4371 .create_account("account2", &seed, &birthday, None)
4372 .unwrap();
4373 let dfvk2 = T::sk_to_fvk(T::usk_to_sk(&usk2));
4374
4375 let value = Zatoshis::from_u64(100000).unwrap();
4377 let (h, _, _) = st.generate_next_block(&dfvk1, AddressType::DefaultExternal, value);
4378 st.scan_cached_blocks(h, 1);
4379
4380 assert_eq!(st.get_total_balance(account1), value);
4381 assert_eq!(st.get_total_balance(account2), Zatoshis::ZERO);
4382
4383 let bal_2 = Zatoshis::from_u64(50000).unwrap();
4385 let addr2 = T::fvk_default_address(&dfvk2);
4386 let req = TransactionRequest::new(vec![Payment::without_memo(
4387 addr2.to_zcash_address(st.network()),
4388 bal_2,
4389 )])
4390 .unwrap();
4391
4392 let change_strategy =
4393 single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
4394 let input_selector = GreedyInputSelector::new();
4395
4396 let txid = st
4397 .spend(
4398 &input_selector,
4399 &change_strategy,
4400 &usk1,
4401 req,
4402 OvkPolicy::Sender,
4403 ConfirmationsPolicy::MIN,
4404 )
4405 .unwrap()[0];
4406
4407 let (h, _) = st.generate_next_block_including(txid);
4408 st.scan_cached_blocks(h, 1);
4409
4410 assert_eq!(st.get_total_balance(account2), bal_2);
4411
4412 let tx = st.wallet().get_transaction(txid).unwrap().unwrap();
4418 let params = *st.network();
4419 decrypt_and_store_transaction(¶ms, st.wallet_mut(), &tx, Some(h)).unwrap();
4420
4421 assert_matches!(st.wallet_mut().delete_account(account2), Ok(_));
4425
4426 let summary = st
4428 .wallet()
4429 .get_wallet_summary(ConfirmationsPolicy::MIN)
4430 .unwrap()
4431 .unwrap();
4432 assert!(summary.account_balances().get(&account2).is_none());
4433 assert!(summary.account_balances().contains_key(&account1));
4434}
4435
4436pub fn account_rename<T: ShieldedPoolTester, DSF>(ds_factory: DSF, cache: impl TestCache)
4441where
4442 DSF: DataStoreFactory,
4443 <DSF as DataStoreFactory>::DataStore: Reset,
4444{
4445 const ACCOUNT1_NAME: &str = "account1";
4447 const ACCOUNT2_NAME: &str = "account2";
4449 const RENAMED_NAME: &str = "renamed";
4451
4452 let mut st = TestBuilder::new()
4453 .with_data_store_factory(ds_factory)
4454 .with_block_cache(cache)
4455 .build();
4456
4457 let seed = Secret::new([0u8; 32].to_vec());
4459 let birthday = AccountBirthday::from_sapling_activation(st.network(), BlockHash([0; 32]));
4460 let (account1, _) = st
4461 .wallet_mut()
4462 .create_account(ACCOUNT1_NAME, &seed, &birthday, None)
4463 .unwrap();
4464 let (account2, _) = st
4465 .wallet_mut()
4466 .create_account(ACCOUNT2_NAME, &seed, &birthday, None)
4467 .unwrap();
4468
4469 assert_matches!(
4471 st.wallet_mut().set_account_name(account1, RENAMED_NAME),
4472 Ok(())
4473 );
4474 let renamed1 = st.wallet().get_account(account1).unwrap().unwrap();
4475 let untouched2 = st.wallet().get_account(account2).unwrap().unwrap();
4476 assert_eq!(renamed1.name(), Some(RENAMED_NAME));
4477 assert_eq!(untouched2.name(), Some(ACCOUNT2_NAME));
4478
4479 assert_matches!(
4481 st.wallet_mut().set_account_name(account2, RENAMED_NAME),
4482 Ok(())
4483 );
4484 let renamed1 = st.wallet().get_account(account1).unwrap().unwrap();
4485 let renamed2 = st.wallet().get_account(account2).unwrap().unwrap();
4486 assert_eq!(renamed1.name(), Some(RENAMED_NAME));
4487 assert_eq!(renamed2.name(), Some(RENAMED_NAME));
4488}
4489
4490pub fn external_address_change_spends_detected_in_restore_from_seed<T: ShieldedPoolTester, Dsf>(
4491 ds_factory: Dsf,
4492 cache: impl TestCache,
4493) where
4494 Dsf: DataStoreFactory,
4495 <Dsf as DataStoreFactory>::DataStore: Reset,
4496{
4497 let mut st = TestBuilder::new()
4498 .with_data_store_factory(ds_factory)
4499 .with_block_cache(cache)
4500 .build();
4501
4502 let seed = Secret::new([0u8; 32].to_vec());
4504 let birthday = AccountBirthday::from_sapling_activation(st.network(), BlockHash([0; 32]));
4505 let (account1, usk) = st
4506 .wallet_mut()
4507 .create_account("account1", &seed, &birthday, None)
4508 .unwrap();
4509 let dfvk = T::sk_to_fvk(T::usk_to_sk(&usk));
4510
4511 let (account2, usk2) = st
4512 .wallet_mut()
4513 .create_account("account2", &seed, &birthday, None)
4514 .unwrap();
4515 let dfvk2 = T::sk_to_fvk(T::usk_to_sk(&usk2));
4516
4517 let value = Zatoshis::from_u64(100000).unwrap();
4519 let (h, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
4520 st.scan_cached_blocks(h, 1);
4521
4522 assert_eq!(st.get_total_balance(account1), value);
4524 assert_eq!(
4525 st.get_spendable_balance(account1, ConfirmationsPolicy::MIN),
4526 value
4527 );
4528 assert_eq!(st.get_total_balance(account2), Zatoshis::ZERO);
4529
4530 let amount_sent = Zatoshis::from_u64(20000).unwrap();
4531 let amount_legacy_change = Zatoshis::from_u64(30000).unwrap();
4532 let addr = T::fvk_default_address(&dfvk);
4533 let addr2 = T::fvk_default_address(&dfvk2);
4534 let req = TransactionRequest::new(vec![
4535 Payment::without_memo(addr2.to_zcash_address(st.network()), amount_sent),
4537 Payment::without_memo(addr.to_zcash_address(st.network()), amount_legacy_change),
4539 ])
4540 .unwrap();
4541
4542 let change_strategy =
4543 single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
4544 let input_selector = GreedyInputSelector::new();
4545
4546 let txid = st
4547 .spend(
4548 &input_selector,
4549 &change_strategy,
4550 &usk,
4551 req,
4552 OvkPolicy::Sender,
4553 ConfirmationsPolicy::MIN,
4554 )
4555 .unwrap()[0];
4556
4557 let amount_left = (value
4558 - (amount_sent + minimum_fee_at_target(&st) + marginal_fee_at_target(&st)).unwrap())
4559 .unwrap();
4560 let pending_change = (amount_left - amount_legacy_change).unwrap();
4561
4562 assert_eq!(
4564 st.get_pending_change(account1, ConfirmationsPolicy::MIN),
4565 pending_change
4566 );
4567 assert_eq!(st.get_total_balance(account1), pending_change);
4569
4570 let (h, _) = st.generate_next_block_including(txid);
4571 st.scan_cached_blocks(h, 1);
4572
4573 assert_eq!(st.get_total_balance(account2), amount_sent,);
4574 assert_eq!(st.get_total_balance(account1), amount_left);
4575
4576 st.reset();
4577
4578 let (account1, restored_usk) = st
4580 .wallet_mut()
4581 .create_account("account1_restored", &seed, &birthday, None)
4582 .unwrap();
4583 assert!(T::fvks_equal(
4584 &T::sk_to_fvk(T::usk_to_sk(&restored_usk)),
4585 &dfvk,
4586 ));
4587
4588 let (account2, restored_usk2) = st
4589 .wallet_mut()
4590 .create_account("account2_restored", &seed, &birthday, None)
4591 .unwrap();
4592 assert!(T::fvks_equal(
4593 &T::sk_to_fvk(T::usk_to_sk(&restored_usk2)),
4594 &dfvk2,
4595 ));
4596
4597 st.scan_cached_blocks(st.sapling_activation_height(), 2);
4598
4599 assert_eq!(st.get_total_balance(account2), amount_sent);
4600 assert_eq!(st.get_total_balance(account1), amount_left);
4601}
4602
4603#[allow(dead_code)]
4604pub fn zip317_spend<T: ShieldedPoolTester, Dsf: DataStoreFactory>(
4605 ds_factory: Dsf,
4606 cache: impl TestCache,
4607) {
4608 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
4609
4610 let account = st.test_account().cloned().unwrap();
4611 let account_id = account.id();
4612 let dfvk = T::test_account_fvk(&st);
4613
4614 st.add_notes_checking_balance([Some(Zatoshis::const_from_u64(50000))]);
4616
4617 for _ in 1..=10 {
4619 st.add_notes_checking_balance([Some(Zatoshis::const_from_u64(1000))]);
4620 }
4621
4622 let total = Zatoshis::const_from_u64(60000);
4624 assert_eq!(st.get_total_balance(account_id), total);
4625 assert_eq!(
4626 st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
4627 total
4628 );
4629
4630 let input_selector = GreedyInputSelector::<Dsf::DataStore>::new();
4631 let change_strategy =
4632 single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
4633
4634 let req = TransactionRequest::new(vec![Payment::without_memo(
4636 T::fvk_default_address(&dfvk).to_zcash_address(st.network()),
4637 Zatoshis::const_from_u64(50000),
4638 )])
4639 .unwrap();
4640
4641 assert_matches!(
4642 st.spend(
4643 &input_selector,
4644 &change_strategy,
4645 account.usk(),
4646 req,
4647 OvkPolicy::Sender,
4648 ConfirmationsPolicy::MIN,
4649 ),
4650 Err(Error::InsufficientFunds { available, required })
4651 if available == Zatoshis::const_from_u64(51000)
4652 && required == Zatoshis::const_from_u64(60000)
4653 );
4654
4655 let req = TransactionRequest::new(vec![Payment::without_memo(
4658 T::fvk_default_address(&dfvk).to_zcash_address(st.network()),
4659 Zatoshis::const_from_u64(41000),
4660 )])
4661 .unwrap();
4662
4663 let txid = st
4664 .spend(
4665 &input_selector,
4666 &change_strategy,
4667 account.usk(),
4668 req,
4669 OvkPolicy::Sender,
4670 ConfirmationsPolicy::MIN,
4671 )
4672 .unwrap()[0];
4673
4674 let (h, _) = st.generate_next_block_including(txid);
4675 st.scan_cached_blocks(h, 1);
4676
4677 assert_eq!(
4681 st.get_total_balance(account_id),
4682 (total - Zatoshis::const_from_u64(10000)).unwrap()
4683 );
4684}
4685
4686#[cfg(feature = "transparent-inputs")]
4687pub fn shield_transparent<T: ShieldedPoolTester, Dsf>(ds_factory: Dsf, cache: impl TestCache)
4688where
4689 Dsf: DataStoreFactory,
4690 <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
4691{
4692 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
4693
4694 let account = st.test_account().cloned().unwrap();
4695 let dfvk = T::test_account_fvk(&st);
4696
4697 let uaddr = st
4698 .wallet()
4699 .get_last_generated_address_matching(account.id(), UnifiedAddressRequest::AllAvailableKeys)
4700 .unwrap()
4701 .unwrap();
4702 let taddr = uaddr.transparent().unwrap();
4703
4704 let (h, _, _) = st.generate_next_block(
4706 &dfvk,
4707 AddressType::Internal,
4708 Zatoshis::const_from_u64(50000),
4709 );
4710 st.scan_cached_blocks(h, 1);
4711
4712 let spent_outpoint = OutPoint::fake();
4713 let utxo = WalletTransparentOutput::from_parts(
4714 spent_outpoint.clone(),
4715 TxOut::new(Zatoshis::const_from_u64(100000), taddr.script().into()),
4716 Some(h),
4717 Some(account.id()),
4718 Some(TransparentKeyScope::EXTERNAL),
4719 None,
4720 )
4721 .unwrap();
4722
4723 let res0 = st.wallet_mut().put_received_transparent_utxo(&utxo);
4724 assert_matches!(res0, Ok(_));
4725
4726 let input_selector = GreedyInputSelector::new();
4727 let change_strategy =
4728 single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
4729
4730 let txids = st
4731 .shield_transparent_funds(
4732 &input_selector,
4733 &change_strategy,
4734 Zatoshis::from_u64(10000).unwrap(),
4735 account.usk(),
4736 &[*taddr],
4737 account.id(),
4738 ConfirmationsPolicy::MIN,
4739 )
4740 .unwrap();
4741 assert_eq!(txids.len(), 1);
4742 let shielding_txid = *txids.first();
4743
4744 assert!(
4745 !st.wallet()
4746 .transaction_data_requests()
4747 .unwrap()
4748 .contains(&TransactionDataRequest::GetStatus(shielding_txid)),
4749 "a wallet-owned shielded output makes the transaction observable by scanning",
4750 );
4751
4752 let tx_summary = st.get_tx_from_history(shielding_txid).unwrap().unwrap();
4753 assert_eq!(tx_summary.spent_note_count(), 1);
4754 assert!(tx_summary.has_change());
4755 assert_eq!(tx_summary.received_note_count(), 0);
4756 assert_eq!(tx_summary.sent_note_count(), 0);
4757 assert!(tx_summary.is_shielding());
4758
4759 let (h, _) = st.generate_next_block_including(shielding_txid);
4761 let scan_result = st.scan_cached_blocks(h, 1);
4762
4763 let tx_summary = st.get_tx_from_history(shielding_txid).unwrap().unwrap();
4765 assert_eq!(tx_summary.spent_note_count(), 1);
4766 assert!(tx_summary.has_change());
4767 assert_eq!(tx_summary.received_note_count(), 0);
4768 assert_eq!(tx_summary.sent_note_count(), 0);
4769 assert!(tx_summary.is_shielding());
4770
4771 let requests = st.wallet().transaction_data_requests().unwrap();
4774 assert!(
4775 !requests.iter().any(|req| req
4776 == &TransactionDataRequest::Enhancement(TxId::from_bytes(*spent_outpoint.hash())))
4777 );
4778
4779 let tx = st
4782 .wallet()
4783 .get_transaction(*txids.first())
4784 .unwrap()
4785 .unwrap();
4786 let params = *st.network();
4787 decrypt_and_store_transaction(¶ms, st.wallet_mut(), &tx, Some(h)).unwrap();
4788
4789 let requests = st.wallet().transaction_data_requests().unwrap();
4791 assert!(
4792 requests.iter().any(|req| req
4793 == &TransactionDataRequest::Enhancement(TxId::from_bytes(*spent_outpoint.hash())))
4794 );
4795
4796 for _ in 0..BLOSSOM_DEFAULT_TX_EXPIRY_DELTA {
4800 st.generate_next_block(
4801 &dfvk,
4802 AddressType::DefaultExternal,
4803 Zatoshis::const_from_u64(10000),
4804 );
4805 }
4806 st.scan_cached_blocks(
4807 scan_result.scanned_range().end,
4808 usize::try_from(BLOSSOM_DEFAULT_TX_EXPIRY_DELTA).unwrap(),
4809 );
4810
4811 st.wallet_mut()
4813 .set_transaction_status(
4814 TxId::from_bytes(*spent_outpoint.hash()),
4815 data_api::TransactionStatus::TxidNotRecognized,
4816 )
4817 .unwrap();
4818
4819 let requests = st.wallet().transaction_data_requests().unwrap();
4821 assert!(
4822 !requests.iter().any(|req| req
4823 == &TransactionDataRequest::Enhancement(TxId::from_bytes(*spent_outpoint.hash())))
4824 );
4825}
4826
4827#[allow(dead_code)]
4829pub fn birthday_in_anchor_shard<T: ShieldedPoolTester>(
4830 ds_factory: impl DataStoreFactory,
4831 cache: impl TestCache,
4832) {
4833 let frontier_tree_size: u32 = (0x1 << 16) + 1234;
4841 let mut st = TestBuilder::new()
4842 .with_data_store_factory(ds_factory)
4843 .with_block_cache(cache)
4844 .with_initial_chain_state(|rng, network| {
4845 let birthday_height = network.activation_height(NetworkUpgrade::Nu5).unwrap() + 1000;
4846
4847 let (prior_sapling_roots, sapling_initial_tree) =
4850 Frontier::random_with_prior_subtree_roots(
4851 rng,
4852 frontier_tree_size.into(),
4853 NonZeroU8::new(16).unwrap(),
4854 );
4855 let prior_sapling_roots = prior_sapling_roots
4857 .into_iter()
4858 .map(|root| CommitmentTreeRoot::from_parts(birthday_height - 500, root))
4859 .collect::<Vec<_>>();
4860
4861 #[cfg(feature = "orchard")]
4862 let (prior_orchard_roots, orchard_initial_tree) =
4863 Frontier::random_with_prior_subtree_roots(
4864 rng,
4865 frontier_tree_size.into(),
4866 NonZeroU8::new(16).unwrap(),
4867 );
4868 #[cfg(feature = "orchard")]
4870 let prior_orchard_roots = prior_orchard_roots
4871 .into_iter()
4872 .map(|root| CommitmentTreeRoot::from_parts(birthday_height - 500, root))
4873 .collect::<Vec<_>>();
4874
4875 #[cfg(feature = "orchard")]
4877 let ironwood_initial_tree = Frontier::empty();
4878
4879 InitialChainState {
4880 chain_state: ChainState::new(
4881 birthday_height - 1,
4882 BlockHash([5; 32]),
4883 sapling_initial_tree,
4884 #[cfg(feature = "orchard")]
4885 orchard_initial_tree,
4886 #[cfg(feature = "orchard")]
4887 ironwood_initial_tree,
4888 ),
4889 prior_sapling_roots,
4890 #[cfg(feature = "orchard")]
4891 prior_orchard_roots,
4892 }
4893 })
4894 .with_account_having_current_birthday()
4895 .build();
4896
4897 let not_our_value = Zatoshis::const_from_u64(10000);
4899 let not_our_key = T::random_fvk(st.rng_mut());
4900 let (initial_height, _, _) =
4901 st.generate_next_block(¬_our_key, AddressType::DefaultExternal, not_our_value);
4902 for _ in 1..9 {
4903 st.generate_next_block(¬_our_key, AddressType::DefaultExternal, not_our_value);
4904 }
4905
4906 let (received_tx_height, _, _) = st.generate_next_block(
4908 &T::test_account_fvk(&st),
4909 AddressType::DefaultExternal,
4910 Zatoshis::const_from_u64(500000),
4911 );
4912
4913 for _ in 0..15 {
4915 st.generate_next_block(¬_our_key, AddressType::DefaultExternal, not_our_value);
4916 }
4917
4918 st.scan_cached_blocks(initial_height + 5, 20);
4921
4922 let account = st.test_account().unwrap();
4924 let account_id = account.id();
4925 let spendable = T::select_spendable_notes(
4926 &st,
4927 account_id,
4928 TargetValue::AtLeast(Zatoshis::const_from_u64(300000)),
4929 TargetHeight::from(received_tx_height + 10),
4930 ConfirmationsPolicy::default(),
4931 &[],
4932 )
4933 .unwrap();
4934
4935 assert_eq!(spendable.len(), 0);
4936
4937 st.scan_cached_blocks(initial_height, 5);
4939
4940 let spendable = T::select_spendable_notes(
4942 &st,
4943 account_id,
4944 TargetValue::AtLeast(Zatoshis::const_from_u64(300000)),
4945 TargetHeight::from(received_tx_height + 10),
4946 ConfirmationsPolicy::default(),
4947 &[],
4948 )
4949 .unwrap();
4950
4951 assert_eq!(spendable.len(), 1);
4952}
4953
4954pub fn checkpoint_gaps<T: ShieldedPoolTester, Dsf: DataStoreFactory>(
4959 ds_factory: Dsf,
4960 cache: impl TestCache,
4961) {
4962 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
4963
4964 st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(500000));
4965
4966 let account = st.test_account().cloned().unwrap();
4967 let birthday = account.birthday().height();
4968 let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
4969 let not_our_value = Zatoshis::const_from_u64(10000);
4970
4971 const GAP_BLOCKS: u32 = 9;
4975 for _ in 0..GAP_BLOCKS {
4976 st.generate_empty_block();
4977 }
4978 let (checkpoint_above_gap, _, _) =
4979 st.generate_next_block(¬_our_key, AddressType::DefaultExternal, not_our_value);
4980 assert_eq!(checkpoint_above_gap, birthday + GAP_BLOCKS + 1);
4981 st.scan_cached_blocks(checkpoint_above_gap, 1);
4982
4983 let selection_policy = ConfirmationsPolicy::new_unchecked(
4984 1,
4985 5,
4986 #[cfg(feature = "transparent-inputs")]
4987 false,
4988 );
4989 let spend_policy = ConfirmationsPolicy::new_symmetrical_unchecked(
4990 5,
4991 #[cfg(feature = "transparent-inputs")]
4992 false,
4993 );
4994 let input_selector = GreedyInputSelector::<Dsf::DataStore>::new();
4995 let change_strategy =
4996 single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
4997 let to = T::fvk_default_address(¬_our_key).to_zcash_address(st.network());
4998 let request = || {
4999 TransactionRequest::new(vec![Payment::without_memo(
5000 to.clone(),
5001 Zatoshis::const_from_u64(10000),
5002 )])
5003 .unwrap()
5004 };
5005
5006 let spendable = T::select_spendable_notes(
5009 &st,
5010 account.id(),
5011 TargetValue::AtLeast(Zatoshis::const_from_u64(300000)),
5012 TargetHeight::from(birthday + 5),
5013 selection_policy,
5014 &[],
5015 )
5016 .unwrap();
5017 assert!(
5018 spendable.is_empty(),
5019 "the policy depth lies in the unscanned gap, so there is no anchor"
5020 );
5021 assert_matches!(
5022 st.spend(
5023 &input_selector,
5024 &change_strategy,
5025 account.usk(),
5026 request(),
5027 OvkPolicy::Sender,
5028 spend_policy,
5029 ),
5030 Err(Error::ScanRequired)
5031 );
5032
5033 st.scan_cached_blocks(birthday + 1, GAP_BLOCKS as usize);
5036
5037 let spendable = T::select_spendable_notes(
5038 &st,
5039 account.id(),
5040 TargetValue::AtLeast(Zatoshis::const_from_u64(300000)),
5041 TargetHeight::from(birthday + 5),
5042 selection_policy,
5043 &[],
5044 )
5045 .unwrap();
5046 assert_eq!(spendable.len(), 1);
5047 assert_matches!(
5048 st.spend(
5049 &input_selector,
5050 &change_strategy,
5051 account.usk(),
5052 request(),
5053 OvkPolicy::Sender,
5054 spend_policy,
5055 ),
5056 Ok(_)
5057 );
5058}
5059
5060#[allow(clippy::type_complexity)]
5064fn tree_anchor_state<S, const DEPTH: u8, const SHARD_HEIGHT: u8>(
5065 tree: &mut ShardTree<S, DEPTH, SHARD_HEIGHT>,
5066 note_position: Position,
5067 anchor_height: BlockHeight,
5068) -> Result<(bool, BTreeSet<BlockHeight>, BTreeSet<BlockHeight>), ShardTreeError<S::Error>>
5069where
5070 S: ShardStore<CheckpointId = BlockHeight>,
5071 S::H: Hashable + Clone + PartialEq,
5072{
5073 let witness_computable = tree
5074 .witness_at_checkpoint_id(note_position, &anchor_height)?
5075 .is_some();
5076 let retained = tree
5077 .store()
5078 .retained_checkpoints()
5079 .map_err(ShardTreeError::Storage)?;
5080 let checkpoint_count = tree
5081 .store()
5082 .checkpoint_count()
5083 .map_err(ShardTreeError::Storage)?;
5084 let mut survivors = BTreeSet::new();
5085 tree.store()
5086 .for_each_checkpoint(checkpoint_count, |cid, _| {
5087 survivors.insert(*cid);
5088 Ok(())
5089 })
5090 .map_err(ShardTreeError::Storage)?;
5091 Ok((witness_computable, survivors, retained))
5092}
5093
5094pub fn anchor_checkpoints_retained_across_deep_scan<
5118 T: ShieldedPoolTester,
5119 Dsf: DataStoreFactory,
5120>(
5121 ds_factory: Dsf,
5122 cache: impl TestCache,
5123 interval: AnchorRetentionInterval,
5124) {
5125 let interval_blocks = interval.block_count().get();
5126
5127 let activation = BlockHeight::from_u32(100_000);
5130 let ironwood_active_network = LocalNetwork {
5131 nu6: Some(activation),
5132 nu6_1: Some(activation),
5133 nu6_2: Some(activation),
5134 nu6_3: Some(activation),
5135 ..TestBuilder::<(), ()>::DEFAULT_NETWORK
5136 };
5137
5138 let mut st = TestDsl::from(
5139 TestBuilder::new()
5140 .with_network(ironwood_active_network)
5141 .with_data_store_factory(ds_factory)
5142 .with_block_cache(cache)
5143 .with_anchor_retention_interval(interval)
5144 .with_account_from_sapling_activation(BlockHash([0; 32])),
5145 )
5146 .build::<T>();
5147
5148 let (received_height, _, _) =
5150 st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(500_000));
5151 let received = u32::from(received_height);
5152 let floor = u32::from(activation);
5153
5154 let mut anchor = u32::from(
5157 anchor_grid(st.network(), interval).boundary_at_or_above(BlockHeight::from(floor)),
5158 );
5159 while anchor <= received {
5160 anchor += interval_blocks;
5161 }
5162
5163 let tip = anchor + PRUNING_DEPTH + 10;
5166
5167 let not_our_fvk = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
5170 let filler_count = tip - received;
5171 for _ in 0..filler_count {
5172 st.generate_next_block(
5173 ¬_our_fvk,
5174 AddressType::DefaultExternal,
5175 Zatoshis::const_from_u64(10_000),
5176 );
5177 }
5178 st.scan_cached_blocks(received_height + 1, filler_count as usize);
5179
5180 let account_id = st.get_account().id();
5182 let spendable = T::select_spendable_notes(
5183 &st,
5184 account_id,
5185 TargetValue::AtLeast(Zatoshis::const_from_u64(1)),
5186 TargetHeight::from(BlockHeight::from(tip + 1)),
5187 ConfirmationsPolicy::MIN,
5188 &[],
5189 )
5190 .unwrap();
5191 let note_position = spendable
5192 .first()
5193 .expect("the received note is spendable")
5194 .note_commitment_tree_position();
5195
5196 let anchor_height = BlockHeight::from(anchor);
5197 let (witness_computable, survivors, retained) = match T::SHIELDED_PROTOCOL {
5198 ShieldedPool::Sapling => st
5199 .wallet_mut()
5200 .with_sapling_tree_mut(|tree| tree_anchor_state(tree, note_position, anchor_height))
5201 .unwrap(),
5202 #[cfg(feature = "orchard")]
5203 ShieldedPool::Orchard => st
5204 .wallet_mut()
5205 .with_orchard_tree_mut(|tree| tree_anchor_state(tree, note_position, anchor_height))
5206 .unwrap(),
5207 other => {
5208 unreachable!("anchor retention test covers only Sapling and Orchard, got {other:?}")
5209 }
5210 };
5211
5212 assert!(
5215 witness_computable,
5216 "a witness for the received note as of the retained anchor at height {anchor} \
5217 must still be constructible",
5218 );
5219
5220 let expected_anchors: BTreeSet<BlockHeight> = (floor..=tip)
5222 .map(BlockHeight::from)
5223 .filter(|h| anchor_grid(st.network(), interval).is_boundary(*h))
5224 .collect();
5225 assert_eq!(
5226 retained, expected_anchors,
5227 "only the interval-aligned anchors at/above the NU6.3 floor should be retained",
5228 );
5229
5230 assert!(
5233 survivors.contains(&anchor_height),
5234 "the buried anchor checkpoint must survive",
5235 );
5236 assert!(
5237 !survivors.contains(&BlockHeight::from(anchor + 1)),
5238 "the ordinary checkpoint just above the buried anchor must have been pruned",
5239 );
5240
5241 for h in (tip - PRUNING_DEPTH + 1)..=tip {
5244 assert!(
5245 survivors.contains(&BlockHeight::from(h)),
5246 "checkpoint at tip-window height {h} must be retained",
5247 );
5248 }
5249}
5250
5251#[cfg(feature = "orchard")]
5262pub fn empty_boundary_blocks_are_checkpointed_and_retained<
5263 T: ShieldedPoolTester,
5264 Dsf: DataStoreFactory,
5265>(
5266 ds_factory: Dsf,
5267 cache: impl TestCache,
5268 interval: AnchorRetentionInterval,
5269) {
5270 let interval_blocks = interval.block_count().get();
5271
5272 let activation = BlockHeight::from_u32(100_000);
5275 let ironwood_active_network = LocalNetwork {
5276 nu6: Some(activation),
5277 nu6_1: Some(activation),
5278 nu6_2: Some(activation),
5279 nu6_3: Some(activation),
5280 ..TestBuilder::<(), ()>::DEFAULT_NETWORK
5281 };
5282
5283 let mut st = TestDsl::from(
5284 TestBuilder::new()
5285 .with_network(ironwood_active_network)
5286 .with_data_store_factory(ds_factory)
5287 .with_block_cache(cache)
5288 .with_anchor_retention_interval(interval)
5289 .with_account_from_sapling_activation(BlockHash([0; 32])),
5290 )
5291 .build::<T>();
5292
5293 let (received_height, _, _) =
5295 st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(500_000));
5296 let received = u32::from(received_height);
5297
5298 let first_boundary = {
5301 let mut b = u32::from(anchor_grid(st.network(), interval).boundary_at_or_above(activation));
5302 while b <= received {
5303 b += interval_blocks;
5304 }
5305 b
5306 };
5307 let boundaries = [first_boundary, first_boundary + interval_blocks];
5308 let tip = boundaries[1] + 2;
5309
5310 let not_our_fvk = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
5314 for height in (received + 1)..=tip {
5315 let generated =
5316 if anchor_grid(st.network(), interval).is_boundary(BlockHeight::from_u32(height)) {
5317 st.generate_empty_block().0
5318 } else {
5319 st.generate_next_block(
5320 ¬_our_fvk,
5321 AddressType::DefaultExternal,
5322 Zatoshis::const_from_u64(10_000),
5323 )
5324 .0
5325 };
5326 assert_eq!(u32::from(generated), height, "cache height must track");
5327 }
5328 st.scan_cached_blocks(received_height + 1, (tip - received) as usize);
5330
5331 let account_id = st.get_account().id();
5333 let spendable = T::select_spendable_notes(
5334 &st,
5335 account_id,
5336 TargetValue::AtLeast(Zatoshis::const_from_u64(1)),
5337 TargetHeight::from(BlockHeight::from_u32(tip + 1)),
5338 ConfirmationsPolicy::MIN,
5339 &[],
5340 )
5341 .unwrap();
5342 let note_position = spendable
5343 .first()
5344 .expect("the received note is spendable")
5345 .note_commitment_tree_position();
5346
5347 for boundary in boundaries {
5348 let anchor_height = BlockHeight::from_u32(boundary);
5349 let (witness_computable, survivors, retained) = match T::SHIELDED_PROTOCOL {
5350 ShieldedPool::Sapling => st
5351 .wallet_mut()
5352 .with_sapling_tree_mut(|tree| tree_anchor_state(tree, note_position, anchor_height))
5353 .unwrap(),
5354 ShieldedPool::Orchard => st
5355 .wallet_mut()
5356 .with_orchard_tree_mut(|tree| tree_anchor_state(tree, note_position, anchor_height))
5357 .unwrap(),
5358 other => {
5359 unreachable!("this test covers only Sapling and Orchard, got {other:?}")
5360 }
5361 };
5362
5363 assert!(
5364 survivors.contains(&anchor_height),
5365 "the empty boundary block at height {boundary} must be checkpointed",
5366 );
5367 assert!(
5368 retained.contains(&anchor_height),
5369 "the checkpoint at the empty boundary height {boundary} must be retained",
5370 );
5371 assert!(
5374 witness_computable,
5375 "a witness for the received note as of the empty boundary at height {boundary} \
5376 must be constructible",
5377 );
5378 }
5379
5380 let ironwood_retained = st
5383 .wallet_mut()
5384 .with_ironwood_tree_mut(|tree| {
5385 tree.store()
5386 .retained_checkpoints()
5387 .map_err(ShardTreeError::Storage)
5388 })
5389 .unwrap()
5390 .expect("the data store maintains an Ironwood tree");
5391 for boundary in boundaries {
5392 assert!(
5393 ironwood_retained.contains(&BlockHeight::from_u32(boundary)),
5394 "the Ironwood tree must retain the empty boundary at height {boundary}",
5395 );
5396 }
5397}
5398
5399#[cfg(feature = "orchard")]
5402#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5403pub enum BoundaryScanOrder {
5404 Forward,
5407 TipFirst,
5410}
5411
5412#[cfg(feature = "orchard")]
5415#[derive(Debug, PartialEq, Eq)]
5416struct RetainedAnchorState {
5417 checkpointed: bool,
5418 retained: bool,
5419 witness_computable: bool,
5420}
5421
5422#[cfg(feature = "orchard")]
5426fn retained_anchor_state<S, const DEPTH: u8, const SHARD_HEIGHT: u8>(
5427 tree: &mut ShardTree<S, DEPTH, SHARD_HEIGHT>,
5428 note_position: Position,
5429 anchor_height: BlockHeight,
5430) -> Result<RetainedAnchorState, ShardTreeError<S::Error>>
5431where
5432 S: ShardStore<CheckpointId = BlockHeight>,
5433 S::H: Hashable + Clone + PartialEq,
5434{
5435 let checkpointed = tree
5436 .store()
5437 .get_checkpoint(&anchor_height)
5438 .map_err(ShardTreeError::Storage)?
5439 .is_some();
5440 let retained = tree
5441 .store()
5442 .retained_checkpoints()
5443 .map_err(ShardTreeError::Storage)?
5444 .contains(&anchor_height);
5445 let witness_computable = matches!(
5446 tree.witness_at_checkpoint_id(note_position, &anchor_height),
5447 Ok(Some(_))
5448 );
5449 Ok(RetainedAnchorState {
5450 checkpointed,
5451 retained,
5452 witness_computable,
5453 })
5454}
5455
5456#[cfg(feature = "orchard")]
5458fn retained_checkpoint_roots<S, const DEPTH: u8, const SHARD_HEIGHT: u8>(
5459 tree: &mut ShardTree<S, DEPTH, SHARD_HEIGHT>,
5460) -> Result<BTreeMap<BlockHeight, bool>, ShardTreeError<S::Error>>
5461where
5462 S: ShardStore<CheckpointId = BlockHeight>,
5463 S::H: Hashable + Clone + PartialEq,
5464{
5465 let retained = tree
5466 .store()
5467 .retained_checkpoints()
5468 .map_err(ShardTreeError::Storage)?;
5469 let mut roots = BTreeMap::new();
5470 for height in retained {
5471 let computable = matches!(tree.root_at_checkpoint_id(&height), Ok(Some(_)));
5472 roots.insert(height, computable);
5473 }
5474 Ok(roots)
5475}
5476
5477#[cfg(feature = "orchard")]
5482pub fn retained_boundaries_below_window_are_usable_anchors<
5483 T: ShieldedPoolTester,
5484 Dsf: DataStoreFactory,
5485>(
5486 ds_factory: Dsf,
5487 cache: impl TestCache,
5488 interval: AnchorRetentionInterval,
5489 scan_order: BoundaryScanOrder,
5490) {
5491 const BLOCKS_BELOW_WINDOW: u32 = 20;
5493 const TIP_ADVANCE: u32 = 20;
5497
5498 let interval_blocks = interval.block_count().get();
5499
5500 let activation = BlockHeight::from_u32(100_000);
5503 let ironwood_active_network = LocalNetwork {
5504 nu6: Some(activation),
5505 nu6_1: Some(activation),
5506 nu6_2: Some(activation),
5507 nu6_3: Some(activation),
5508 ..TestBuilder::<(), ()>::DEFAULT_NETWORK
5509 };
5510
5511 let mut st = TestDsl::from(
5512 TestBuilder::new()
5513 .with_network(ironwood_active_network)
5514 .with_data_store_factory(ds_factory)
5515 .with_block_cache(cache)
5516 .with_anchor_retention_interval(interval)
5517 .with_account_from_sapling_activation(BlockHash([0; 32])),
5518 )
5519 .build::<T>();
5520
5521 let (received_height, _, _) =
5522 st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(500_000));
5523 let received = u32::from(received_height);
5524 let account_id = st.get_account().id();
5525 let note_position = T::select_spendable_notes(
5526 &st,
5527 account_id,
5528 TargetValue::AtLeast(Zatoshis::const_from_u64(1)),
5529 TargetHeight::from(received_height + 1),
5530 ConfirmationsPolicy::MIN,
5531 &[],
5532 )
5533 .unwrap()
5534 .first()
5535 .expect("the received note is selectable")
5536 .note_commitment_tree_position();
5537
5538 const BOUNDARY_COUNT: u32 = 6;
5543 const MAX_OUTPUTS_BELOW_BOUNDARY: u32 = 3;
5544 let first_boundary = {
5545 let mut b = u32::from(anchor_grid(st.network(), interval).boundary_at_or_above(activation));
5546 while b <= received + 1 {
5547 b += interval_blocks;
5548 }
5549 b
5550 };
5551 let boundaries = (0..BOUNDARY_COUNT)
5552 .map(|i| first_boundary + i * interval_blocks)
5553 .collect::<Vec<_>>();
5554 let batch_end = boundaries[boundaries.len() - 1] + 2;
5555 let tip = batch_end + BLOCKS_BELOW_WINDOW + PRUNING_DEPTH;
5556
5557 let not_our_fvk = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
5560 let filler = || {
5561 FakeCompactOutput::new(
5562 not_our_fvk.clone(),
5563 AddressType::DefaultExternal,
5564 Zatoshis::const_from_u64(10_000),
5565 )
5566 };
5567 for height in (received + 1)..=(tip + TIP_ADVANCE) {
5568 let below_batch_end = height <= batch_end;
5569 let generated = if below_batch_end
5570 && anchor_grid(st.network(), interval).is_boundary(BlockHeight::from_u32(height))
5571 {
5572 st.generate_empty_block().0
5573 } else if let Some(index) = boundaries
5574 .iter()
5575 .position(|boundary| below_batch_end && *boundary == height + 1)
5576 {
5577 let output_count = (index as u32 % MAX_OUTPUTS_BELOW_BOUNDARY) + 1;
5578 let outputs = (0..output_count).map(|_| filler()).collect::<Vec<_>>();
5579 st.generate_next_block_multi(&outputs).0
5580 } else {
5581 st.generate_next_block_multi(&[filler()]).0
5582 };
5583 assert_eq!(u32::from(generated), height, "cache height must track");
5584 }
5585
5586 st.wallet_mut()
5587 .update_chain_tip(BlockHeight::from_u32(tip))
5588 .unwrap();
5589 let window_start = tip - (PRUNING_DEPTH - 1);
5590 if scan_order == BoundaryScanOrder::TipFirst {
5591 st.scan_cached_blocks(BlockHeight::from_u32(window_start), PRUNING_DEPTH as usize);
5592 st.wallet_mut()
5593 .update_chain_tip(BlockHeight::from_u32(tip + TIP_ADVANCE))
5594 .unwrap();
5595 st.scan_cached_blocks(BlockHeight::from_u32(tip + 1), TIP_ADVANCE as usize);
5596 let min_checkpoint = match T::SHIELDED_PROTOCOL {
5597 ShieldedPool::Sapling => st
5598 .wallet_mut()
5599 .with_sapling_tree_mut(|tree| {
5600 tree.store()
5601 .min_checkpoint_id()
5602 .map_err(ShardTreeError::Storage)
5603 })
5604 .unwrap(),
5605 ShieldedPool::Orchard => st
5606 .wallet_mut()
5607 .with_orchard_tree_mut(|tree| {
5608 tree.store()
5609 .min_checkpoint_id()
5610 .map_err(ShardTreeError::Storage)
5611 })
5612 .unwrap(),
5613 other => {
5614 unreachable!("this test covers only Sapling and Orchard, got {other:?}")
5615 }
5616 };
5617 assert!(
5618 min_checkpoint > Some(BlockHeight::from_u32(batch_end)),
5619 "test invariant: the oldest checkpoint must lie above the boundary batch, \
5620 found {min_checkpoint:?}",
5621 );
5622 }
5623 st.scan_cached_blocks(received_height + 1, (batch_end - received) as usize);
5625
5626 for &boundary in &boundaries {
5627 let anchor_height = BlockHeight::from_u32(boundary);
5628 let state = match T::SHIELDED_PROTOCOL {
5629 ShieldedPool::Sapling => st
5630 .wallet_mut()
5631 .with_sapling_tree_mut(|tree| {
5632 retained_anchor_state(tree, note_position, anchor_height)
5633 })
5634 .unwrap(),
5635 ShieldedPool::Orchard => st
5636 .wallet_mut()
5637 .with_orchard_tree_mut(|tree| {
5638 retained_anchor_state(tree, note_position, anchor_height)
5639 })
5640 .unwrap(),
5641 other => {
5642 unreachable!("this test covers only Sapling and Orchard, got {other:?}")
5643 }
5644 };
5645 assert_eq!(
5646 state,
5647 RetainedAnchorState {
5648 checkpointed: true,
5649 retained: true,
5650 witness_computable: true,
5651 },
5652 "the empty boundary at height {boundary} must be a retained checkpoint at which the \
5653 received note has a witness ({scan_order:?})",
5654 );
5655 }
5656
5657 #[allow(clippy::redundant_closure)]
5660 let roots = [
5661 (
5662 "Sapling",
5663 st.wallet_mut()
5664 .with_sapling_tree_mut(|tree| retained_checkpoint_roots(tree))
5665 .unwrap(),
5666 ),
5667 (
5668 "Orchard",
5669 st.wallet_mut()
5670 .with_orchard_tree_mut(|tree| retained_checkpoint_roots(tree))
5671 .unwrap(),
5672 ),
5673 (
5674 "Ironwood",
5675 st.wallet_mut()
5676 .with_ironwood_tree_mut(|tree| retained_checkpoint_roots(tree))
5677 .unwrap()
5678 .expect("the data store maintains an Ironwood tree"),
5679 ),
5680 ];
5681 for (pool, roots) in roots {
5682 for &boundary in &boundaries {
5683 assert!(
5684 roots.contains_key(&BlockHeight::from_u32(boundary)),
5685 "the {pool} tree must retain the boundary at height {boundary} ({scan_order:?})",
5686 );
5687 }
5688 let unusable = roots
5689 .iter()
5690 .filter(|(_, computable)| !**computable)
5691 .map(|(height, _)| *height)
5692 .collect::<Vec<_>>();
5693 assert!(
5694 unusable.is_empty(),
5695 "the {pool} tree cannot compute the root of retained checkpoints {unusable:?} \
5696 ({scan_order:?})",
5697 );
5698 }
5699}
5700
5701#[cfg(feature = "orchard")]
5702pub fn pool_crossing_required<P0: ShieldedPoolTester, P1: ShieldedPoolTester>(
5703 ds_factory: impl DataStoreFactory,
5704 cache: impl TestCache,
5705) {
5706 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<P0>();
5710
5711 let account = st.test_account().cloned().unwrap();
5712
5713 let p0_fvk = P0::test_account_fvk(&st);
5714
5715 let p1_fvk = P1::test_account_fvk(&st);
5716 let p1_to = P1::fvk_default_address(&p1_fvk);
5717
5718 let note_value = Zatoshis::const_from_u64(350000);
5719 st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
5720 st.scan_cached_blocks(account.birthday().height(), 2);
5721
5722 let initial_balance = note_value;
5723 assert_eq!(st.get_total_balance(account.id()), initial_balance);
5724 assert_eq!(
5725 st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
5726 initial_balance
5727 );
5728
5729 let transfer_amount = Zatoshis::const_from_u64(200000);
5730 let p0_to_p1 = TransactionRequest::new(vec![Payment::without_memo(
5731 p1_to.to_zcash_address(st.network()),
5732 transfer_amount,
5733 )])
5734 .unwrap();
5735
5736 let input_selector = GreedyInputSelector::new();
5737 let change_strategy =
5738 single_output_change_strategy(StandardFeeRule::Zip317, None, P1::SHIELDED_PROTOCOL);
5739 let proposal0 = st
5740 .propose_transfer(
5741 account.id(),
5742 &input_selector,
5743 &change_strategy,
5744 p0_to_p1,
5745 ConfirmationsPolicy::MIN,
5746 )
5747 .unwrap();
5748
5749 let _min_target_height = proposal0.min_target_height();
5750 assert_eq!(proposal0.steps().len(), 1);
5751 let step0 = &proposal0.steps().head;
5752
5753 let expected_fee = Zatoshis::const_from_u64(20000);
5755 assert_eq!(step0.balance().fee_required(), expected_fee);
5756
5757 let expected_change = (note_value - transfer_amount - expected_fee).unwrap();
5758 let proposed_change = step0.balance().proposed_change();
5759 assert_eq!(proposed_change.len(), 1);
5760 let change_output = proposed_change.first().unwrap();
5761 assert_eq!(
5763 change_output.output_pool(),
5764 PoolType::Shielded(std::cmp::max(ShieldedPool::Sapling, ShieldedPool::Orchard))
5765 );
5766 assert_eq!(change_output.value(), expected_change);
5767
5768 let txids = st.create_proposed_expecting(&proposal0, 1);
5769
5770 let (h, _) = st.generate_next_block_including(txids[0]);
5771 st.scan_cached_blocks(h, 1);
5772
5773 assert_eq!(
5774 st.get_total_balance(account.id()),
5775 (initial_balance - expected_fee).unwrap()
5776 );
5777 assert_eq!(
5778 st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
5779 (initial_balance - expected_fee).unwrap()
5780 );
5781}
5782
5783#[cfg(feature = "orchard")]
5784pub fn fully_funded_fully_private<P0: ShieldedPoolTester, P1: ShieldedPoolTester>(
5785 ds_factory: impl DataStoreFactory,
5786 cache: impl TestCache,
5787) {
5788 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<P0>();
5790
5791 let account = st.test_account().cloned().unwrap();
5792
5793 let p0_fvk = P0::test_account_fvk(&st);
5794
5795 let p1_fvk = P1::test_account_fvk(&st);
5796 let p1_to = P1::fvk_default_address(&p1_fvk);
5797
5798 let note_value = Zatoshis::const_from_u64(350000);
5799 st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
5800 st.generate_next_block(&p1_fvk, AddressType::DefaultExternal, note_value);
5801 st.scan_cached_blocks(account.birthday().height(), 2);
5802
5803 let initial_balance = (note_value * 2u64).unwrap();
5804 assert_eq!(st.get_total_balance(account.id()), initial_balance);
5805 assert_eq!(
5806 st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
5807 initial_balance
5808 );
5809
5810 let transfer_amount = Zatoshis::const_from_u64(200000);
5811 let p0_to_p1 = TransactionRequest::new(vec![Payment::without_memo(
5812 p1_to.to_zcash_address(st.network()),
5813 transfer_amount,
5814 )])
5815 .unwrap();
5816
5817 let input_selector = GreedyInputSelector::new();
5818 let change_strategy =
5821 single_output_change_strategy(StandardFeeRule::Zip317, None, P0::SHIELDED_PROTOCOL);
5822 let proposal0 = st
5823 .propose_transfer(
5824 account.id(),
5825 &input_selector,
5826 &change_strategy,
5827 p0_to_p1,
5828 ConfirmationsPolicy::MIN,
5829 )
5830 .unwrap();
5831
5832 let _min_target_height = proposal0.min_target_height();
5833 assert_eq!(proposal0.steps().len(), 1);
5834 let step0 = &proposal0.steps().head;
5835
5836 let expected_fee = Zatoshis::const_from_u64(10000);
5839 assert_eq!(step0.balance().fee_required(), expected_fee);
5840
5841 let expected_change = (note_value - transfer_amount - expected_fee).unwrap();
5842 let proposed_change = step0.balance().proposed_change();
5843 assert_eq!(proposed_change.len(), 1);
5844 let change_output = proposed_change.first().unwrap();
5845 assert_eq!(
5848 change_output.output_pool(),
5849 PoolType::Shielded(P1::SHIELDED_PROTOCOL)
5850 );
5851 assert_eq!(change_output.value(), expected_change);
5852
5853 let txids = st.create_proposed_expecting(&proposal0, 1);
5854
5855 let (h, _) = st.generate_next_block_including(txids[0]);
5856 st.scan_cached_blocks(h, 1);
5857
5858 assert_eq!(
5859 st.get_total_balance(account.id()),
5860 (initial_balance - expected_fee).unwrap()
5861 );
5862 assert_eq!(
5863 st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
5864 (initial_balance - expected_fee).unwrap()
5865 );
5866}
5867
5868#[cfg(all(feature = "orchard", feature = "transparent-inputs"))]
5869pub fn fully_funded_send_to_t<P0: ShieldedPoolTester, P1: ShieldedPoolTester>(
5870 ds_factory: impl DataStoreFactory,
5871 cache: impl TestCache,
5872) {
5873 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<P0>();
5875
5876 let account = st.test_account().cloned().unwrap();
5877
5878 let p0_fvk = P0::test_account_fvk(&st);
5879 let p1_fvk = P1::test_account_fvk(&st);
5880 let (p1_to, _) = account.usk().default_transparent_address();
5881
5882 let note_value = Zatoshis::const_from_u64(350000);
5883 st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
5884 st.generate_next_block(&p1_fvk, AddressType::DefaultExternal, note_value);
5885 st.scan_cached_blocks(account.birthday().height(), 2);
5886
5887 let initial_balance = (note_value * 2u64).unwrap();
5888 assert_eq!(st.get_total_balance(account.id()), initial_balance);
5889 assert_eq!(
5890 st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
5891 initial_balance
5892 );
5893
5894 let transfer_amount = Zatoshis::const_from_u64(200000);
5895 let p0_to_p1 = TransactionRequest::new(vec![Payment::without_memo(
5896 Address::Transparent(p1_to).to_zcash_address(st.network()),
5897 transfer_amount,
5898 )])
5899 .unwrap();
5900
5901 let input_selector = GreedyInputSelector::new();
5902 let change_strategy =
5905 single_output_change_strategy(StandardFeeRule::Zip317, None, P0::SHIELDED_PROTOCOL);
5906 let proposal0 = st
5907 .propose_transfer(
5908 account.id(),
5909 &input_selector,
5910 &change_strategy,
5911 p0_to_p1,
5912 ConfirmationsPolicy::MIN,
5913 )
5914 .unwrap();
5915
5916 let _min_target_height = proposal0.min_target_height();
5917 assert_eq!(proposal0.steps().len(), 1);
5918 let step0 = &proposal0.steps().head;
5919
5920 let expected_fee = Zatoshis::const_from_u64(15000);
5922 assert_eq!(step0.balance().fee_required(), expected_fee);
5923
5924 let expected_change = (note_value - transfer_amount - expected_fee).unwrap();
5925 let proposed_change = step0.balance().proposed_change();
5926 assert_eq!(proposed_change.len(), 1);
5927 let change_output = proposed_change.first().unwrap();
5928 assert_eq!(change_output.output_pool(), PoolType::SAPLING);
5932 assert_eq!(change_output.value(), expected_change);
5933
5934 let txids = st.create_proposed_expecting(&proposal0, 1);
5935
5936 let (h, _) = st.generate_next_block_including(txids[0]);
5937 st.scan_cached_blocks(h, 1);
5938
5939 assert_eq!(
5942 st.get_total_balance(account.id()),
5943 (initial_balance - expected_fee).unwrap()
5944 );
5945 assert_eq!(
5948 st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
5949 (initial_balance - transfer_amount - expected_fee).unwrap()
5950 );
5951}
5952
5953#[cfg(feature = "orchard")]
5954pub fn multi_pool_checkpoint<P0: ShieldedPoolTester, P1: ShieldedPoolTester>(
5955 ds_factory: impl DataStoreFactory,
5956 cache: impl TestCache,
5957) {
5958 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<P0>();
5960
5961 let account = st.test_account().cloned().unwrap();
5962 let acct_id = account.id();
5963
5964 let p0_fvk = P0::test_account_fvk(&st);
5965 let p1_fvk = P1::test_account_fvk(&st);
5966
5967 let note_value = Zatoshis::const_from_u64(500000);
5970 let (start_height, _, _) =
5971 st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
5972 st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
5973 st.generate_next_block(&p1_fvk, AddressType::DefaultExternal, note_value);
5974 let scanned = st.scan_cached_blocks(start_height, 3);
5975
5976 let next_to_scan = scanned.scanned_range().end;
5977
5978 let initial_balance = (note_value * 3u64).unwrap();
5979 assert_eq!(st.get_total_balance(acct_id), initial_balance);
5980 assert_eq!(
5981 st.get_spendable_balance(acct_id, ConfirmationsPolicy::MIN),
5982 initial_balance
5983 );
5984
5985 for _ in 0..10 {
5987 st.generate_empty_block();
5988 }
5989
5990 let scanned = st.scan_cached_blocks(next_to_scan, 5);
5992 let next_to_scan = scanned.scanned_range().end;
5993
5994 assert_eq!(st.get_total_balance(acct_id), initial_balance);
5996 assert_eq!(
5997 st.get_spendable_balance(acct_id, ConfirmationsPolicy::MIN),
5998 initial_balance
5999 );
6000
6001 let input_selector = GreedyInputSelector::new();
6003 let change_strategy =
6004 single_output_change_strategy(StandardFeeRule::Zip317, None, P1::SHIELDED_PROTOCOL);
6005
6006 let transfer_amount = Zatoshis::const_from_u64(200000);
6008 let p0_transfer = TransactionRequest::new(vec![Payment::without_memo(
6009 P0::random_address(st.rng_mut()).to_zcash_address(st.network()),
6010 transfer_amount,
6011 )])
6012 .unwrap();
6013 let res = st
6014 .spend(
6015 &input_selector,
6016 &change_strategy,
6017 account.usk(),
6018 p0_transfer,
6019 OvkPolicy::Sender,
6020 ConfirmationsPolicy::MIN,
6021 )
6022 .unwrap();
6023 st.generate_next_block_including(*res.first());
6024
6025 let expected_fee = Zatoshis::const_from_u64(10000);
6026 let expected_change = (note_value - transfer_amount - expected_fee).unwrap();
6027 assert_eq!(
6028 st.get_total_balance(acct_id),
6029 ((note_value * 2u64).unwrap() + expected_change).unwrap()
6030 );
6031 assert_eq!(
6032 st.get_pending_change(acct_id, ConfirmationsPolicy::MIN),
6033 expected_change
6034 );
6035
6036 let both_transfer = TransactionRequest::new(vec![
6038 Payment::without_memo(
6039 P0::random_address(st.rng_mut()).to_zcash_address(st.network()),
6040 transfer_amount,
6041 ),
6042 Payment::without_memo(
6043 P1::random_address(st.rng_mut()).to_zcash_address(st.network()),
6044 transfer_amount,
6045 ),
6046 ])
6047 .unwrap();
6048 let res = st
6049 .spend(
6050 &input_selector,
6051 &change_strategy,
6052 account.usk(),
6053 both_transfer,
6054 OvkPolicy::Sender,
6055 ConfirmationsPolicy::MIN,
6056 )
6057 .unwrap();
6058 st.generate_next_block_including(*res.first());
6059
6060 for _ in 0..5 {
6062 st.generate_empty_block();
6063 }
6064
6065 let (max_height, _, _) =
6067 st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
6068
6069 st.scan_cached_blocks(
6071 next_to_scan,
6072 usize::try_from(u32::from(max_height) - u32::from(next_to_scan) + 1).unwrap(),
6073 );
6074
6075 let expected_final = (initial_balance + note_value
6076 - (transfer_amount * 3u64).unwrap()
6077 - (expected_fee * 3u64).unwrap())
6078 .unwrap();
6079 assert_eq!(st.get_total_balance(acct_id), expected_final);
6080
6081 let expected_checkpoints_p0: Vec<(BlockHeight, Option<Position>)> = [(99999u32, None)]
6085 .into_iter()
6086 .chain([(100000, Some(0u64))])
6087 .chain((100001..=100012).map(|h| (h, Some(1))))
6088 .chain([(100013, Some(3))])
6089 .chain((100014..=100019).map(|h| (h, Some(5))))
6090 .chain([(100020, Some(6))])
6091 .map(|(h, pos)| (BlockHeight::from(h), pos.map(Position::from)))
6092 .collect();
6093
6094 let expected_checkpoints_p1: Vec<(BlockHeight, Option<Position>)> = [(99999u32, None)]
6095 .into_iter()
6096 .chain([(100000, None), (100001, None)])
6097 .chain((100002..=100013).map(|h| (h, Some(0u64))))
6098 .chain((100014..=100020).map(|h| (h, Some(2))))
6099 .map(|(h, pos)| (BlockHeight::from(h), pos.map(Position::from)))
6100 .collect();
6101
6102 let p0_checkpoints = st
6103 .wallet()
6104 .get_checkpoint_history(&P0::SHIELDED_PROTOCOL)
6105 .unwrap();
6106 assert_eq!(p0_checkpoints.to_vec(), expected_checkpoints_p0);
6107
6108 let p1_checkpoints = st
6109 .wallet()
6110 .get_checkpoint_history(&P1::SHIELDED_PROTOCOL)
6111 .unwrap();
6112 assert_eq!(p1_checkpoints.to_vec(), expected_checkpoints_p1);
6113}
6114
6115#[cfg(feature = "orchard")]
6116pub fn multi_pool_checkpoints_with_pruning<P0: ShieldedPoolTester, P1: ShieldedPoolTester>(
6117 ds_factory: impl DataStoreFactory,
6118 cache: impl TestCache,
6119) {
6120 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<P0>();
6122
6123 let account = st.test_account().cloned().unwrap();
6124
6125 let p0_fvk = P0::random_fvk(st.rng_mut());
6126 let p1_fvk = P1::random_fvk(st.rng_mut());
6127
6128 let note_value = Zatoshis::const_from_u64(10000);
6129 for _ in 0..10 {
6131 for _ in 0..10 {
6132 st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
6133 }
6134 for _ in 0..10 {
6135 st.generate_next_block(&p1_fvk, AddressType::DefaultExternal, note_value);
6136 }
6137 }
6138 st.scan_cached_blocks(account.birthday().height(), 200);
6139 for _ in 0..100 {
6140 st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
6141 st.generate_next_block(&p1_fvk, AddressType::DefaultExternal, note_value);
6142 }
6143 st.scan_cached_blocks(account.birthday().height() + 200, 200);
6144}
6145
6146pub fn valid_chain_states<T: ShieldedPoolTester>(
6147 ds_factory: impl DataStoreFactory,
6148 cache: impl TestCache,
6149) {
6150 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
6151
6152 let dfvk = T::test_account_fvk(&st);
6153
6154 assert_matches!(st.wallet().chain_height(), Ok(None));
6156
6157 let (h1, _, _) = st.generate_next_block(
6159 &dfvk,
6160 AddressType::DefaultExternal,
6161 Zatoshis::const_from_u64(5),
6162 );
6163
6164 st.scan_cached_blocks(h1, 1);
6166
6167 let (h2, _, _) = st.generate_next_block(
6169 &dfvk,
6170 AddressType::DefaultExternal,
6171 Zatoshis::const_from_u64(7),
6172 );
6173
6174 st.scan_cached_blocks(h2, 1);
6176}
6177
6178#[allow(dead_code)]
6180pub fn invalid_chain_cache_disconnected<T: ShieldedPoolTester>(
6181 ds_factory: impl DataStoreFactory,
6182 cache: impl TestCache,
6183) {
6184 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
6185
6186 let dfvk = T::test_account_fvk(&st);
6187
6188 let (h, _, _) = st.generate_next_block(
6190 &dfvk,
6191 AddressType::DefaultExternal,
6192 Zatoshis::const_from_u64(5),
6193 );
6194 let (last_contiguous_height, _, _) = st.generate_next_block(
6195 &dfvk,
6196 AddressType::DefaultExternal,
6197 Zatoshis::const_from_u64(7),
6198 );
6199
6200 st.scan_cached_blocks(h, 2);
6202
6203 let disconnect_height = last_contiguous_height + 1;
6205 st.generate_block_at(
6206 disconnect_height,
6207 BlockHash([1; 32]),
6208 &[FakeCompactOutput::new(
6209 &dfvk,
6210 AddressType::DefaultExternal,
6211 Zatoshis::const_from_u64(8),
6212 )],
6213 2,
6214 2,
6215 0,
6216 true,
6217 );
6218 st.generate_next_block(
6219 &dfvk,
6220 AddressType::DefaultExternal,
6221 Zatoshis::const_from_u64(3),
6222 );
6223
6224 assert_matches!(
6226 st.try_scan_cached_blocks(
6227 disconnect_height,
6228 2
6229 ),
6230 Err(chain::error::Error::Scan(ScanError::PrevHashMismatch { at_height }))
6231 if at_height == disconnect_height
6232 );
6233}
6234
6235pub fn data_db_truncation<T: ShieldedPoolTester, Dsf>(ds_factory: Dsf, cache: impl TestCache)
6236where
6237 Dsf: DataStoreFactory,
6238 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
6239{
6240 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
6241
6242 let account = st.test_account().cloned().unwrap();
6243 let dfvk = T::test_account_fvk(&st);
6244
6245 assert_eq!(st.get_wallet_summary(ConfirmationsPolicy::MIN), None);
6247
6248 let value = Zatoshis::const_from_u64(50000);
6250 let value2 = Zatoshis::const_from_u64(70000);
6251 let (h, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
6252 st.generate_next_block(&dfvk, AddressType::DefaultExternal, value2);
6253
6254 st.scan_cached_blocks(h, 2);
6256
6257 assert_eq!(
6259 st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
6260 (value + value2).unwrap()
6261 );
6262
6263 st.wallet_mut().truncate_to_height(h + 1).unwrap();
6265
6266 assert_eq!(
6268 st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
6269 (value + value2).unwrap()
6270 );
6271
6272 st.wallet_mut().truncate_to_height(h).unwrap();
6274
6275 assert_eq!(
6278 st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
6279 value
6280 );
6281 assert_eq!(
6282 st.get_pending_shielded_balance(account.id(), ConfirmationsPolicy::MIN),
6283 value2
6284 );
6285
6286 st.scan_cached_blocks(h, 2);
6288
6289 assert_eq!(
6291 st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
6292 (value + value2).unwrap()
6293 );
6294}
6295
6296pub fn truncate_to_chain_state<T: ShieldedPoolTester, Dsf>(ds_factory: Dsf, cache: impl TestCache)
6297where
6298 Dsf: DataStoreFactory,
6299 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
6300{
6301 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
6311
6312 let sapling_activation = st
6313 .network()
6314 .activation_height(consensus::NetworkUpgrade::Sapling)
6315 .unwrap();
6316
6317 let account_fvk = T::test_account_fvk(&st);
6324 let seed = [1u8; 32];
6325 let other_sk = T::sk(&seed);
6326 let other_fvk = T::sk_to_fvk(&other_sk);
6327
6328 let initial_block_count = 8u32;
6329 st.generate_next_block(
6330 &account_fvk,
6331 AddressType::DefaultExternal,
6332 Zatoshis::const_from_u64(10000),
6333 );
6334 for _ in 1..initial_block_count {
6335 st.generate_next_block(
6336 &other_fvk,
6337 AddressType::DefaultExternal,
6338 Zatoshis::const_from_u64(10000),
6339 );
6340 }
6341 let scan_start = sapling_activation;
6342 st.scan_cached_blocks(scan_start, initial_block_count as usize);
6343
6344 let capture_height = sapling_activation + initial_block_count - 1;
6347 let captured_chain_state = st
6348 .latest_cached_block()
6349 .expect("should have cached blocks")
6350 .chain_state()
6351 .clone();
6352 assert_eq!(captured_chain_state.block_height(), capture_height);
6353
6354 let extra_blocks = PRUNING_DEPTH + 10;
6357 for _ in 0..extra_blocks {
6358 st.generate_next_block(
6359 &other_fvk,
6360 AddressType::DefaultExternal,
6361 Zatoshis::const_from_u64(5000),
6362 );
6363 }
6364 st.scan_cached_blocks(capture_height + 1, extra_blocks as usize);
6365
6366 let tip = st
6367 .wallet()
6368 .chain_height()
6369 .unwrap()
6370 .expect("chain tip should be set");
6371 assert!(
6372 tip >= capture_height + PRUNING_DEPTH,
6373 "tip should be beyond pruning depth from capture height"
6374 );
6375
6376 let truncation_result = st.wallet_mut().truncate_to_height(capture_height);
6380 assert!(
6381 truncation_result.is_err(),
6382 "truncate_to_height should fail when checkpoint has been pruned"
6383 );
6384
6385 st.wallet_mut()
6388 .truncate_to_chain_state(captured_chain_state.clone())
6389 .expect("truncate_to_chain_state should succeed");
6390
6391 let new_tip = st
6394 .wallet()
6395 .chain_height()
6396 .unwrap()
6397 .expect("chain tip should still be set after truncation");
6398 assert_eq!(new_tip, capture_height);
6399
6400 let hash_at_capture = st
6402 .wallet()
6403 .get_block_hash(capture_height)
6404 .unwrap()
6405 .expect("block hash should exist at capture height");
6406 assert_eq!(hash_at_capture, captured_chain_state.block_hash());
6407
6408 assert_eq!(
6410 st.wallet().get_block_hash(capture_height + 1).unwrap(),
6411 None,
6412 "blocks above capture height should be removed"
6413 );
6414}
6415
6416pub fn truncate_to_chain_state_below_birthday<T: ShieldedPoolTester, Dsf>(
6417 ds_factory: Dsf,
6418 cache: impl TestCache,
6419) where
6420 Dsf: DataStoreFactory,
6421 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
6422{
6423 let mut st = TestBuilder::new()
6429 .with_data_store_factory(ds_factory)
6430 .with_block_cache(cache)
6431 .with_initial_chain_state(|rng, network| {
6432 let birthday_height = network.activation_height(NetworkUpgrade::Sapling).unwrap() + 200;
6433
6434 let (prior_sapling_roots, sapling_initial_tree) =
6435 Frontier::random_with_prior_subtree_roots(rng, 1u64, NonZeroU8::new(16).unwrap());
6436 let prior_sapling_roots = prior_sapling_roots
6437 .into_iter()
6438 .map(|root| CommitmentTreeRoot::from_parts(birthday_height - 100, root))
6439 .collect::<Vec<_>>();
6440
6441 #[cfg(feature = "orchard")]
6442 let (prior_orchard_roots, orchard_initial_tree) =
6443 Frontier::random_with_prior_subtree_roots(rng, 1u64, NonZeroU8::new(16).unwrap());
6444 #[cfg(feature = "orchard")]
6445 let prior_orchard_roots = prior_orchard_roots
6446 .into_iter()
6447 .map(|root| CommitmentTreeRoot::from_parts(birthday_height - 100, root))
6448 .collect::<Vec<_>>();
6449
6450 #[cfg(feature = "orchard")]
6452 let ironwood_initial_tree = Frontier::empty();
6453
6454 InitialChainState {
6455 chain_state: ChainState::new(
6456 birthday_height - 1,
6457 BlockHash([5; 32]),
6458 sapling_initial_tree,
6459 #[cfg(feature = "orchard")]
6460 orchard_initial_tree,
6461 #[cfg(feature = "orchard")]
6462 ironwood_initial_tree,
6463 ),
6464 prior_sapling_roots,
6465 #[cfg(feature = "orchard")]
6466 prior_orchard_roots,
6467 }
6468 })
6469 .with_account_having_current_birthday()
6470 .build();
6471
6472 let other_fvk = T::random_fvk(st.rng_mut());
6474 let birthday_height = st.test_account().unwrap().birthday().height();
6475
6476 for _ in 0..5 {
6477 st.generate_next_block(
6478 &other_fvk,
6479 AddressType::DefaultExternal,
6480 Zatoshis::const_from_u64(10000),
6481 );
6482 }
6483 st.scan_cached_blocks(birthday_height, 5);
6484
6485 let extra_blocks = PRUNING_DEPTH + 10;
6488 for _ in 0..extra_blocks {
6489 st.generate_next_block(
6490 &other_fvk,
6491 AddressType::DefaultExternal,
6492 Zatoshis::const_from_u64(5000),
6493 );
6494 }
6495 st.scan_cached_blocks(birthday_height + 5, extra_blocks as usize);
6496
6497 let prior_chain_state = st
6501 .test_account()
6502 .unwrap()
6503 .birthday()
6504 .prior_chain_state()
6505 .clone();
6506
6507 let _target_height = prior_chain_state.block_height();
6511 st.wallet_mut()
6512 .truncate_to_chain_state(prior_chain_state)
6513 .expect("truncate_to_chain_state below birthday should succeed");
6514
6515 assert_eq!(
6517 st.wallet().get_block_hash(birthday_height).unwrap(),
6518 None,
6519 "blocks at birthday height should be removed after truncating below birthday"
6520 );
6521}
6522
6523pub fn truncate_to_chain_state_above_scanned<T: ShieldedPoolTester, Dsf>(
6524 ds_factory: Dsf,
6525 cache: impl TestCache,
6526) where
6527 Dsf: DataStoreFactory,
6528 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
6529{
6530 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
6537
6538 let birthday_height = st.test_account().unwrap().birthday().height();
6539
6540 let other_fvk = T::random_fvk(st.rng_mut());
6543 let initial_blocks = 5u32;
6544 for _ in 0..initial_blocks {
6545 st.generate_next_block(
6546 &other_fvk,
6547 AddressType::DefaultExternal,
6548 Zatoshis::const_from_u64(10000),
6549 );
6550 }
6551 st.scan_cached_blocks(birthday_height, initial_blocks as usize);
6552
6553 let extra_blocks = PRUNING_DEPTH + 10;
6554 for _ in 0..extra_blocks {
6555 st.generate_next_block(
6556 &other_fvk,
6557 AddressType::DefaultExternal,
6558 Zatoshis::const_from_u64(5000),
6559 );
6560 }
6561 st.scan_cached_blocks(birthday_height + initial_blocks, extra_blocks as usize);
6562 let max_scanned = birthday_height + initial_blocks + extra_blocks - 1;
6563
6564 T::put_subtree_roots(
6568 &mut st,
6569 0,
6570 &[CommitmentTreeRoot::from_parts(
6571 birthday_height,
6572 T::empty_tree_leaf(),
6573 )],
6574 )
6575 .unwrap();
6576
6577 let chain_tip = max_scanned + 500;
6579 st.wallet_mut().update_chain_tip(chain_tip).unwrap();
6580
6581 let target_height = max_scanned + 50;
6586 let shard_2_tree_size: u64 = (0x2 << 16) + 2;
6587 let (_, shard2_sapling_frontier) = Frontier::random_with_prior_subtree_roots(
6588 st.rng_mut(),
6589 shard_2_tree_size,
6590 NonZeroU8::new(16).unwrap(),
6591 );
6592 #[cfg(feature = "orchard")]
6593 let (_, shard2_orchard_frontier) = Frontier::random_with_prior_subtree_roots(
6594 st.rng_mut(),
6595 shard_2_tree_size,
6596 NonZeroU8::new(16).unwrap(),
6597 );
6598 #[cfg(feature = "orchard")]
6600 let shard2_ironwood_frontier = Frontier::empty();
6601
6602 let target_chain_state = ChainState::new(
6603 target_height,
6604 BlockHash([7; 32]),
6605 shard2_sapling_frontier,
6606 #[cfg(feature = "orchard")]
6607 shard2_orchard_frontier,
6608 #[cfg(feature = "orchard")]
6609 shard2_ironwood_frontier,
6610 );
6611
6612 let pre_truncation_tip = st
6614 .wallet()
6615 .chain_height()
6616 .unwrap()
6617 .expect("chain tip should be set");
6618 assert!(pre_truncation_tip > target_height);
6619
6620 st.wallet_mut()
6625 .truncate_to_chain_state(target_chain_state)
6626 .expect("truncate_to_chain_state above max scanned should succeed");
6627
6628 let post_truncation_tip = st
6630 .wallet()
6631 .chain_height()
6632 .unwrap()
6633 .expect("chain tip should still be set after truncation");
6634 assert_eq!(
6635 post_truncation_tip, target_height,
6636 "scan queue should be trimmed to target height, not extend to the old chain tip"
6637 );
6638
6639 assert!(
6641 st.wallet().get_block_hash(max_scanned).unwrap().is_some(),
6642 "blocks at max_scanned should be preserved"
6643 );
6644}
6645
6646pub fn rewind_to_chain_state_deep<T: ShieldedPoolTester, Dsf>(
6647 ds_factory: Dsf,
6648 cache: impl TestCache,
6649) where
6650 Dsf: DataStoreFactory,
6651 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
6652{
6653 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
6665
6666 let sapling_activation = st
6667 .network()
6668 .activation_height(consensus::NetworkUpgrade::Sapling)
6669 .unwrap();
6670
6671 let seed = [1u8; 32];
6674 let other_fvk = T::sk_to_fvk(&T::sk(&seed));
6675
6676 let initial_block_count = 8u32;
6677 for _ in 0..initial_block_count {
6678 st.generate_next_block(
6679 &other_fvk,
6680 AddressType::DefaultExternal,
6681 Zatoshis::const_from_u64(10000),
6682 );
6683 }
6684 st.scan_cached_blocks(sapling_activation, initial_block_count as usize);
6685
6686 let rewind_target = sapling_activation + initial_block_count - 1;
6688
6689 let extra_blocks = PRUNING_DEPTH + 10;
6692 for _ in 0..extra_blocks {
6693 st.generate_next_block(
6694 &other_fvk,
6695 AddressType::DefaultExternal,
6696 Zatoshis::const_from_u64(5000),
6697 );
6698 }
6699 st.scan_cached_blocks(rewind_target + 1, extra_blocks as usize);
6700
6701 let pre_rewind_tip = st
6702 .wallet()
6703 .chain_height()
6704 .unwrap()
6705 .expect("chain tip should be set");
6706 assert!(
6707 pre_rewind_tip > rewind_target + PRUNING_DEPTH,
6708 "tip should be strictly beyond pruning depth from the rewind target"
6709 );
6710
6711 let prune_boundary = pre_rewind_tip - (PRUNING_DEPTH - 1);
6714 let boundary_hash_before = st
6715 .wallet()
6716 .get_block_hash(prune_boundary)
6717 .unwrap()
6718 .expect("block at prune boundary should be present before rewind");
6719
6720 st.wallet_mut()
6722 .rewind_to_chain_state(
6723 ChainState::empty(rewind_target, BlockHash([0; 32])),
6724 HashSet::new(),
6725 )
6726 .expect("rewind_to_chain_state should succeed for a deep target");
6727
6728 let new_tip = st
6732 .wallet()
6733 .chain_height()
6734 .unwrap()
6735 .expect("chain tip should still be set after rewind");
6736 assert_eq!(new_tip, pre_rewind_tip);
6737
6738 let wallet = st.wallet();
6743 assert_eq!(
6744 wallet.get_block_hash(prune_boundary).unwrap(),
6745 Some(boundary_hash_before),
6746 "block hash at (tip - (PRUNING_DEPTH - 1)) should be preserved unchanged by a deep rewind"
6747 );
6748 assert!(
6749 wallet.get_block_hash(prune_boundary + 1).unwrap().is_none(),
6750 "block entries above (tip - (PRUNING_DEPTH - 1)) must be removed by a deep rewind"
6751 );
6752 assert!(
6753 wallet.get_block_hash(pre_rewind_tip).unwrap().is_none(),
6754 "block entries up to the pre-rewind tip must be removed by a deep rewind"
6755 );
6756 assert_eq!(
6757 wallet
6758 .block_max_scanned()
6759 .unwrap()
6760 .map(|m| m.block_height()),
6761 Some(prune_boundary),
6762 "block_max_scanned should equal (tip - (PRUNING_DEPTH - 1)) after a deep rewind"
6763 );
6764}
6765
6766pub fn rewind_to_chain_state_shallow<T: ShieldedPoolTester, Dsf>(
6767 ds_factory: Dsf,
6768 cache: impl TestCache,
6769) where
6770 Dsf: DataStoreFactory,
6771 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
6772{
6773 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
6784
6785 let sapling_activation = st
6786 .network()
6787 .activation_height(consensus::NetworkUpgrade::Sapling)
6788 .unwrap();
6789
6790 let seed = [1u8; 32];
6791 let other_fvk = T::sk_to_fvk(&T::sk(&seed));
6792
6793 let initial_block_count = 8u32;
6794 for _ in 0..initial_block_count {
6795 st.generate_next_block(
6796 &other_fvk,
6797 AddressType::DefaultExternal,
6798 Zatoshis::const_from_u64(10000),
6799 );
6800 }
6801 st.scan_cached_blocks(sapling_activation, initial_block_count as usize);
6802
6803 let rewind_target = sapling_activation + initial_block_count - 1;
6804
6805 let extra_blocks = PRUNING_DEPTH - 1;
6809 for _ in 0..extra_blocks {
6810 st.generate_next_block(
6811 &other_fvk,
6812 AddressType::DefaultExternal,
6813 Zatoshis::const_from_u64(5000),
6814 );
6815 }
6816 st.scan_cached_blocks(rewind_target + 1, extra_blocks as usize);
6817
6818 let tip = st
6819 .wallet()
6820 .chain_height()
6821 .unwrap()
6822 .expect("chain tip should be set");
6823 assert_eq!(
6824 tip,
6825 rewind_target + (PRUNING_DEPTH - 1),
6826 "tip should be exactly at the shallow boundary from the rewind target"
6827 );
6828
6829 let target_hash_before = st
6830 .wallet()
6831 .get_block_hash(rewind_target)
6832 .unwrap()
6833 .expect("block at the rewind target should be present before rewind");
6834
6835 st.wallet_mut()
6836 .rewind_to_chain_state(
6837 ChainState::empty(rewind_target, BlockHash([0; 32])),
6838 HashSet::new(),
6839 )
6840 .expect("rewind_to_chain_state should succeed for a shallow target");
6841
6842 let new_tip = st
6846 .wallet()
6847 .chain_height()
6848 .unwrap()
6849 .expect("chain tip should still be set after rewind");
6850 assert_eq!(new_tip, tip);
6851
6852 let wallet = st.wallet();
6856 assert_eq!(
6857 wallet.get_block_hash(rewind_target).unwrap(),
6858 Some(target_hash_before),
6859 "block hash at the rewind target should be preserved unchanged"
6860 );
6861 assert!(
6862 wallet.get_block_hash(rewind_target + 1).unwrap().is_none(),
6863 "block entries above the rewind target should be removed by a shallow rewind"
6864 );
6865 assert_eq!(
6866 wallet
6867 .block_max_scanned()
6868 .unwrap()
6869 .map(|m| m.block_height()),
6870 Some(rewind_target),
6871 "block_max_scanned should equal the rewind target after a shallow rewind"
6872 );
6873}
6874
6875pub fn rewind_after_non_contiguous_scan<T: ShieldedPoolTester, Dsf>(
6876 ds_factory: Dsf,
6877 cache: impl TestCache,
6878) where
6879 Dsf: DataStoreFactory,
6880 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
6881{
6882 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
6891
6892 let sapling_activation = st
6893 .network()
6894 .activation_height(consensus::NetworkUpgrade::Sapling)
6895 .unwrap();
6896
6897 let seed = [1u8; 32];
6901 let other_fvk = T::sk_to_fvk(&T::sk(&seed));
6902 let filler_value = Zatoshis::const_from_u64(10_000);
6903
6904 let low_count: u32 = 10;
6905 let gap_size: u32 = PRUNING_DEPTH + 5; let high_count: u32 = 10;
6907 let total_generated = low_count + gap_size + high_count;
6908
6909 for _ in 0..total_generated {
6910 st.generate_next_block(&other_fvk, AddressType::DefaultExternal, filler_value);
6911 }
6912
6913 let low_start = sapling_activation;
6914 let low_end_inclusive = low_start + low_count - 1;
6915 let high_start = low_end_inclusive + gap_size + 1;
6916
6917 st.scan_cached_blocks(low_start, low_count as usize);
6919
6920 st.scan_cached_blocks(high_start, high_count as usize);
6925
6926 let max_scanned_height = st
6927 .wallet()
6928 .block_max_scanned()
6929 .unwrap()
6930 .map(|m| m.block_height())
6931 .expect("block_max_scanned should report the high-range tip");
6932 let high_end_inclusive = high_start + high_count - 1;
6933 assert_eq!(max_scanned_height, high_end_inclusive);
6934 let pd_floor = max_scanned_height - (PRUNING_DEPTH - 1);
6935 assert!(
6936 pd_floor > low_end_inclusive && pd_floor < high_start,
6937 "test invariant: PD floor must lie in the unscanned gap (got {pd_floor}, \
6938 gap is ({low_end_inclusive}, {high_start}))"
6939 );
6940
6941 st.wallet_mut()
6945 .rewind_to_chain_state(
6946 ChainState::empty(low_end_inclusive, BlockHash([0; 32])),
6947 HashSet::new(),
6948 )
6949 .expect("rewind_to_chain_state should succeed across a non-contiguous scan");
6950}
6951
6952fn assert_recovered_balance_spends<T, Cache, DbT, ParamsT, AccountIdT, ErrT>(
6957 st: &mut TestState<Cache, DbT, ParamsT>,
6958 account_id: AccountIdT,
6959 usk: &UnifiedSpendingKey,
6960 expected_balance: Zatoshis,
6961) where
6962 T: ShieldedPoolTester,
6963 Cache: TestCache,
6964 <Cache::BlockSource as BlockSource>::Error: std::fmt::Debug,
6965 ParamsT: consensus::Parameters + Send + 'static,
6966 AccountIdT: std::fmt::Debug + std::cmp::Eq + std::hash::Hash + Copy,
6967 ErrT: std::fmt::Debug,
6968 DbT: InputSource<AccountId = AccountIdT, Error = ErrT>
6969 + WalletTest
6970 + WalletWrite
6971 + WalletRead<AccountId = AccountIdT, Error = ErrT>
6972 + WalletCommitmentTrees,
6973 <DbT as WalletRead>::AccountId: ConditionallySelectable + Default + Send + Sync + 'static,
6974 <DbT as WalletRead>::Account: data_api::Account<AccountId = AccountIdT>,
6975{
6976 assert_send_max_consumes_balance::<T, _, _, _, _, _>(st, account_id, expected_balance);
6978
6979 let to_extsk = T::sk(&[0xcc; 32]);
6981 let to: Address = T::sk_default_address(&to_extsk);
6982 let send_value = Zatoshis::const_from_u64(10_000);
6983 let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
6984 to.to_zcash_address(st.network()),
6985 send_value,
6986 )])
6987 .unwrap();
6988 let change_strategy =
6989 single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
6990 let input_selector = GreedyInputSelector::new();
6991 let proposal = st
6992 .propose_transfer(
6993 account_id,
6994 &input_selector,
6995 &change_strategy,
6996 request,
6997 ConfirmationsPolicy::MIN,
6998 )
6999 .expect("propose_transfer should succeed against stabilized notes after the recovery scan");
7000 let txids = st
7001 .create_proposed_transactions::<std::convert::Infallible, _, std::convert::Infallible, _>(
7002 usk,
7003 OvkPolicy::Sender,
7004 &proposal,
7005 )
7006 .expect("transaction construction should succeed");
7007 assert_eq!(
7008 txids.len(),
7009 1,
7010 "the spend should produce exactly one transaction",
7011 );
7012}
7013
7014pub fn b_note_stable_across_rewind_below_birthday<T, Dsf>(ds_factory: Dsf, cache: impl TestCache)
7031where
7032 T: ShieldedPoolTester,
7033 Dsf: DataStoreFactory,
7034 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
7035{
7036 let (mut st, account_b_id, usk_b) =
7037 build_two_account_recovery_fixture::<T, Dsf>(ds_factory, cache);
7038 let account_a = st.test_account().unwrap().clone();
7039 let birthday_a = account_a.birthday().height();
7040 let birthday_b = birthday_a + 5;
7041
7042 assert_eq!(
7044 st.get_spendable_balance(account_a.id(), ConfirmationsPolicy::MIN),
7045 RECOVERY_A_NOTE_VALUE,
7046 "account A's note must be spendable in the freshly-built fixture",
7047 );
7048 assert_eq!(
7049 st.get_spendable_balance(account_b_id, ConfirmationsPolicy::MIN),
7050 RECOVERY_B_NOTE_VALUE,
7051 "account B's note must be spendable in the freshly-built fixture",
7052 );
7053
7054 let rewind_target = birthday_a + 2;
7057 assert!(
7058 rewind_target < birthday_b,
7059 "the rewind target must sit below account B's birthday",
7060 );
7061 st.wallet_mut()
7062 .rewind_to_chain_state(
7063 ChainState::empty(rewind_target, BlockHash([0; 32])),
7064 HashSet::from([account_b_id]),
7065 )
7066 .expect("rewind_to_chain_state should succeed");
7067
7068 assert_eq!(
7069 st.get_spendable_balance(account_b_id, ConfirmationsPolicy::MIN),
7070 Zatoshis::ZERO,
7071 "immediately after the rewind account B's note must not be spendable",
7072 );
7073
7074 let chain_tip = st
7078 .wallet()
7079 .chain_height()
7080 .unwrap()
7081 .expect("chain tip should still be set after rewind");
7082 let rescan_from = rewind_target + 1;
7083 let rescan_count = u32::from(chain_tip) - u32::from(rescan_from) + 1;
7084 st.scan_cached_blocks(rescan_from, rescan_count as usize);
7085
7086 assert_eq!(
7087 st.get_spendable_balance(account_b_id, ConfirmationsPolicy::MIN),
7088 RECOVERY_B_NOTE_VALUE,
7089 "after re-scanning the dirty range account B's note must be spendable again",
7090 );
7091 assert_eq!(
7092 st.get_spendable_balance(account_a.id(), ConfirmationsPolicy::MIN),
7093 RECOVERY_A_NOTE_VALUE,
7094 "account A's note is unaffected by a rewind that stays above its shard",
7095 );
7096
7097 assert_recovered_balance_spends::<T, _, _, _, _, _>(
7098 &mut st,
7099 account_b_id,
7100 &usk_b,
7101 RECOVERY_B_NOTE_VALUE,
7102 );
7103}
7104
7105pub fn completed_shard_note_spendable_after_rewind_once_window_rescanned<T, Dsf>(
7119 ds_factory: Dsf,
7120 cache: impl TestCache,
7121) where
7122 T: ShieldedPoolTester,
7123 Dsf: DataStoreFactory,
7124 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
7125{
7126 let (mut st, account_b_id, _) = build_two_account_recovery_fixture::<T, Dsf>(ds_factory, cache);
7127 let account_a = st.test_account().unwrap().clone();
7128 let birthday_a = account_a.birthday().height();
7129 let block_a1_height = birthday_a;
7130
7131 assert_eq!(
7133 st.get_spendable_balance(account_a.id(), ConfirmationsPolicy::MIN),
7134 RECOVERY_A_NOTE_VALUE,
7135 "account A's note must be spendable in the freshly-built fixture",
7136 );
7137
7138 let rewind_target = birthday_a - 1;
7141 st.wallet_mut()
7142 .rewind_to_chain_state(
7143 ChainState::empty(rewind_target, BlockHash([0; 32])),
7144 HashSet::from([account_a.id(), account_b_id]),
7145 )
7146 .expect("rewind_to_chain_state should succeed");
7147
7148 assert_eq!(
7149 st.get_spendable_balance(account_a.id(), ConfirmationsPolicy::MIN),
7150 Zatoshis::ZERO,
7151 "immediately after the rewind account A's note must not be spendable",
7152 );
7153
7154 let chain_tip = st
7156 .wallet()
7157 .chain_height()
7158 .unwrap()
7159 .expect("chain tip should still be set after rewind");
7160 let pruning_window_start = chain_tip - (PRUNING_DEPTH - 1);
7161 st.scan_cached_blocks(pruning_window_start, PRUNING_DEPTH as usize);
7162
7163 let unscanned = st.wallet().suggest_scan_ranges().unwrap();
7164 assert!(
7165 unscanned
7166 .iter()
7167 .any(|range| range.block_range().contains(&block_a1_height)),
7168 "test invariant: Block A1 must still be queued for scanning: {unscanned:?}",
7169 );
7170 assert_eq!(
7171 st.get_spendable_balance(account_a.id(), ConfirmationsPolicy::MIN),
7172 RECOVERY_A_NOTE_VALUE,
7173 "once the pruning window is rescanned account A's note is spendable again",
7174 );
7175
7176 assert_recovered_balance_spends::<T, _, _, _, _, _>(
7177 &mut st,
7178 account_a.id(),
7179 account_a.usk(),
7180 RECOVERY_A_NOTE_VALUE,
7181 );
7182}
7183
7184fn import_account_below_wallet_birthday<Cache, DbT, ParamsT>(
7188 st: &mut TestState<Cache, DbT, ParamsT>,
7189) where
7190 Cache: TestCache,
7191 DbT: WalletTest + WalletWrite,
7192 ParamsT: consensus::Parameters + Send + 'static,
7193{
7194 const IMPORTED_SEED: [u8; 32] = [7u8; 32];
7195 let wallet_birthday = st
7196 .wallet()
7197 .get_wallet_birthday()
7198 .unwrap()
7199 .expect("the wallet has a birthday");
7200 let prior_height = wallet_birthday - PRE_BIRTHDAY_BLOCKS / 2 - 1;
7201 let prior_chain_state = st
7202 .cached_blocks
7203 .get(&prior_height)
7204 .expect("the block below the new birthday is cached")
7205 .chain_state()
7206 .clone();
7207 let birthday = AccountBirthday::from_parts(prior_chain_state, None);
7208 st.wallet_mut()
7209 .import_account_hd(
7210 "imported",
7211 &Secret::new(IMPORTED_SEED.to_vec()),
7212 zip32::AccountId::ZERO,
7213 &birthday,
7214 None,
7215 )
7216 .expect("account import should succeed");
7217}
7218
7219pub fn completed_shard_note_spendable_across_older_birthday_import<T, Dsf>(
7224 ds_factory: Dsf,
7225 cache: impl TestCache,
7226) where
7227 T: ShieldedPoolTester,
7228 Dsf: DataStoreFactory,
7229 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
7230{
7231 let (mut st, account_id, usk) = build_stable_shard_fixture::<T, Dsf>(ds_factory, cache);
7232 assert_eq!(
7233 st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
7234 SHARD_1_NOTE_VALUE
7235 );
7236
7237 import_account_below_wallet_birthday(&mut st);
7238 assert_eq!(
7239 st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
7240 Zatoshis::ZERO,
7241 "immediately after the import the pruning window is unscanned",
7242 );
7243
7244 let chain_tip = st
7245 .wallet()
7246 .chain_height()
7247 .unwrap()
7248 .expect("chain tip is known");
7249 let pruning_window_start = chain_tip - (PRUNING_DEPTH - 1);
7250 st.scan_cached_blocks(pruning_window_start, PRUNING_DEPTH as usize);
7251
7252 let unscanned = st.wallet().suggest_scan_ranges().unwrap();
7253 assert!(
7254 unscanned
7255 .iter()
7256 .any(|range| range.block_range().start < pruning_window_start),
7257 "test invariant: blocks below the pruning window must remain queued: {unscanned:?}",
7258 );
7259 assert_eq!(
7260 st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
7261 SHARD_1_NOTE_VALUE,
7262 "once the pruning window is rescanned the completed-shard note is spendable again",
7263 );
7264 assert_recovered_balance_spends::<T, _, _, _, _, _>(
7265 &mut st,
7266 account_id,
7267 &usk,
7268 SHARD_1_NOTE_VALUE,
7269 );
7270}
7271
7272pub fn open_shard_note_spendable_across_older_birthday_import<T, Dsf>(
7277 ds_factory: Dsf,
7278 cache: impl TestCache,
7279) where
7280 T: ShieldedPoolTester,
7281 Dsf: DataStoreFactory,
7282 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
7283{
7284 const OPEN_SHARD_NOTE_VALUE: Zatoshis = Zatoshis::const_from_u64(70_000);
7285
7286 let (mut st, account_id, usk) = build_stable_shard_fixture::<T, Dsf>(ds_factory, cache);
7287 let dfvk = T::sk_to_fvk(T::usk_to_sk(&usk));
7288
7289 let (note_height, _, _) =
7292 st.generate_next_block(&dfvk, AddressType::DefaultExternal, OPEN_SHARD_NOTE_VALUE);
7293 let burial = PRUNING_DEPTH + 10;
7294 for _ in 0..burial {
7295 st.generate_empty_block();
7296 }
7297 st.scan_cached_blocks(note_height, (burial + 1) as usize);
7298 let total = (SHARD_1_NOTE_VALUE + OPEN_SHARD_NOTE_VALUE).unwrap();
7299 assert_eq!(
7300 st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
7301 total
7302 );
7303
7304 import_account_below_wallet_birthday(&mut st);
7305 assert_eq!(
7306 st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
7307 Zatoshis::ZERO,
7308 "immediately after the import the pruning window is unscanned",
7309 );
7310
7311 let chain_tip = st
7312 .wallet()
7313 .chain_height()
7314 .unwrap()
7315 .expect("chain tip is known");
7316 let pruning_window_start = chain_tip - (PRUNING_DEPTH - 1);
7317 st.scan_cached_blocks(pruning_window_start, PRUNING_DEPTH as usize);
7318
7319 let unscanned = st.wallet().suggest_scan_ranges().unwrap();
7320 assert!(
7321 unscanned
7322 .iter()
7323 .any(|range| range.block_range().start < pruning_window_start),
7324 "test invariant: blocks below the pruning window must remain queued: {unscanned:?}",
7325 );
7326 assert_eq!(
7327 st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
7328 total,
7329 "once the pruning window is rescanned both existing notes are spendable again",
7330 );
7331 assert_recovered_balance_spends::<T, _, _, _, _, _>(&mut st, account_id, &usk, total);
7332}
7333
7334pub fn stabilized_note_rewind_above_shard_end<T, Dsf>(ds_factory: Dsf, cache: impl TestCache)
7352where
7353 T: ShieldedPoolTester,
7354 Dsf: DataStoreFactory,
7355 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
7356{
7357 let (mut st, account_id, usk) = build_stable_shard_fixture::<T, Dsf>(ds_factory, cache);
7358 let birthday_height = st
7359 .wallet()
7360 .get_wallet_birthday()
7361 .unwrap()
7362 .expect("account birthday should be set");
7363
7364 assert_eq!(
7366 st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
7367 SHARD_1_NOTE_VALUE,
7368 "fixture must report the stabilized note as spendable",
7369 );
7370
7371 let rewind_target = birthday_height + 5;
7376 st.wallet_mut()
7377 .rewind_to_chain_state(
7378 ChainState::empty(rewind_target, BlockHash([0; 32])),
7379 HashSet::new(),
7380 )
7381 .expect("rewind_to_chain_state should succeed");
7382
7383 assert_eq!(
7384 st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
7385 Zatoshis::ZERO,
7386 "immediately after rewind the window's `Anchor` priority blocks the balance",
7387 );
7388
7389 let chain_tip = st
7394 .wallet()
7395 .chain_height()
7396 .unwrap()
7397 .expect("chain tip should still be set after rewind");
7398 let pruning_window_start = chain_tip - (PRUNING_DEPTH - 1);
7399 st.scan_cached_blocks(pruning_window_start, PRUNING_DEPTH as usize);
7400
7401 assert_eq!(
7402 st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
7403 SHARD_1_NOTE_VALUE,
7404 "shard 1's extent is below the rewrite range; pruning-window rescan must restore the note",
7405 );
7406
7407 assert_recovered_balance_spends::<T, _, _, _, _, _>(
7408 &mut st,
7409 account_id,
7410 &usk,
7411 SHARD_1_NOTE_VALUE,
7412 );
7413}
7414
7415pub fn stabilized_note_rewind_un_mines_shard_completion<T, Dsf>(
7436 ds_factory: Dsf,
7437 cache: impl TestCache,
7438) where
7439 T: ShieldedPoolTester,
7440 Dsf: DataStoreFactory,
7441 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
7442{
7443 let (mut st, account_id, usk) = build_tip_shard_fixture::<T, Dsf>(ds_factory, cache);
7444 let birthday_height = st
7445 .wallet()
7446 .get_wallet_birthday()
7447 .unwrap()
7448 .expect("account birthday should be set");
7449
7450 assert_eq!(
7454 st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
7455 SHARD_1_NOTE_VALUE,
7456 "tip-shard fixture must report the active-shard-stabilized note as spendable",
7457 );
7458
7459 let rewind_target = birthday_height - 50;
7468 st.wallet_mut()
7469 .rewind_to_chain_state(
7470 ChainState::empty(rewind_target, BlockHash([0; 32])),
7471 HashSet::from([account_id]),
7472 )
7473 .expect("rewind_to_chain_state should succeed");
7474
7475 assert_eq!(
7476 st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
7477 Zatoshis::ZERO,
7478 "after rewind the cleared settled height withholds the note",
7479 );
7480
7481 let new_birthday = rewind_target + 1;
7488 let recovery_block_count = 49 + 1 + 1 + 5;
7489 st.scan_cached_blocks(new_birthday, recovery_block_count as usize);
7490
7491 assert_eq!(
7492 st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
7493 SHARD_1_NOTE_VALUE,
7494 "after re-scanning from the lowered birthday through the chain tip, shard 1 is \
7495 complete and the note is spendable again",
7496 );
7497
7498 assert_recovered_balance_spends::<T, _, _, _, _, _>(
7499 &mut st,
7500 account_id,
7501 &usk,
7502 SHARD_1_NOTE_VALUE,
7503 );
7504}
7505
7506pub fn stabilized_note_spendable_across_small_tip_advance<T, Dsf>(
7523 ds_factory: Dsf,
7524 cache: impl TestCache,
7525) where
7526 T: ShieldedPoolTester,
7527 Dsf: DataStoreFactory,
7528 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
7529{
7530 let (mut st, account_id, _usk) = build_stable_shard_fixture::<T, Dsf>(ds_factory, cache);
7531
7532 let policy = ConfirmationsPolicy::default();
7533 let anchor_depth = u32::from(policy.trusted());
7534 assert!(
7535 anchor_depth > 1,
7536 "this test requires a trusted anchor depth of at least 2 so that a nonzero tip \
7537 advance can stay below it",
7538 );
7539
7540 assert_eq!(
7542 st.get_spendable_balance(account_id, policy),
7543 SHARD_1_NOTE_VALUE,
7544 "fixture must report the stabilized note as spendable under the default policy",
7545 );
7546
7547 let scanned_tip = st
7548 .wallet()
7549 .chain_height()
7550 .unwrap()
7551 .expect("chain tip is known");
7552
7553 st.wallet_mut()
7558 .update_chain_tip(scanned_tip + (anchor_depth - 1))
7559 .unwrap();
7560 assert_eq!(
7561 st.get_spendable_balance(account_id, policy),
7562 SHARD_1_NOTE_VALUE,
7563 "a tip advance smaller than the anchor depth must not suspend spendability",
7564 );
7565
7566 st.wallet_mut()
7570 .update_chain_tip(scanned_tip + anchor_depth)
7571 .unwrap();
7572 assert_eq!(
7573 st.get_spendable_balance(account_id, policy),
7574 Zatoshis::ZERO,
7575 "a tip advance reaching the anchor depth must suspend spendability until the \
7576 wallet has scanned to the new anchor",
7577 );
7578}
7579
7580pub fn note_in_recently_completed_shard_spendable_once_confirmed<T, Dsf>(
7585 ds_factory: Dsf,
7586 cache: impl TestCache,
7587) where
7588 T: ShieldedPoolTester,
7589 Dsf: DataStoreFactory,
7590 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
7591{
7592 let confirmations = ConfirmationsPolicy::default().untrusted();
7593 let policy = ConfirmationsPolicy::new_symmetrical(
7594 confirmations,
7595 #[cfg(feature = "transparent-inputs")]
7596 false,
7597 );
7598
7599 let trailing_blocks = confirmations.get() - 3;
7602 let (mut st, account_id, usk) = build_shard_1_note_fixture::<T, Dsf>(
7603 ds_factory,
7604 cache,
7605 trailing_blocks,
7606 Shard1ScanOrder::CompletionFirst,
7607 );
7608 assert_eq!(st.get_spendable_balance(account_id, policy), Zatoshis::ZERO);
7609
7610 let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
7613 let (h, _, _) = st.generate_next_block(
7614 ¬_our_key,
7615 AddressType::DefaultExternal,
7616 Zatoshis::const_from_u64(1000),
7617 );
7618 st.scan_cached_blocks(h, 1);
7619 assert_eq!(
7620 st.get_spendable_balance(account_id, policy),
7621 SHARD_1_NOTE_VALUE
7622 );
7623
7624 let to = T::sk_default_address(&T::sk(&[0xcc; 32]));
7625 let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
7626 to.to_zcash_address(st.network()),
7627 Zatoshis::const_from_u64(10_000),
7628 )])
7629 .unwrap();
7630 let change_strategy =
7631 single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
7632 let proposal = st
7633 .propose_transfer(
7634 account_id,
7635 &GreedyInputSelector::new(),
7636 &change_strategy,
7637 request,
7638 policy,
7639 )
7640 .unwrap();
7641 let txids = st
7642 .create_proposed_transactions::<std::convert::Infallible, _, std::convert::Infallible, _>(
7643 &usk,
7644 OvkPolicy::Sender,
7645 &proposal,
7646 )
7647 .unwrap();
7648 assert_eq!(txids.len(), 1);
7649}
7650
7651pub fn anchor_is_policy_depth_state_or_absent<T, Dsf>(ds_factory: Dsf, cache: impl TestCache)
7657where
7658 T: ShieldedPoolTester,
7659 Dsf: DataStoreFactory,
7660 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
7661{
7662 let (mut st, account_id, _usk) = build_stable_shard_fixture::<T, Dsf>(ds_factory, cache);
7663 let policy = ConfirmationsPolicy::default();
7664
7665 let (target, anchor) = st
7667 .wallet()
7668 .get_target_and_anchor_heights(policy.trusted())
7669 .unwrap()
7670 .expect("a synced wallet has an anchor");
7671 assert_eq!(anchor, policy.anchor_height(target));
7672 assert_eq!(
7673 st.get_spendable_balance(account_id, policy),
7674 SHARD_1_NOTE_VALUE
7675 );
7676
7677 let scanned_tip = st
7680 .wallet()
7681 .chain_height()
7682 .unwrap()
7683 .expect("chain tip is known");
7684 let advance = PRUNING_DEPTH + 10;
7685 st.wallet_mut()
7686 .update_chain_tip(scanned_tip + advance)
7687 .unwrap();
7688
7689 assert_eq!(
7690 st.wallet()
7691 .get_target_and_anchor_heights(policy.trusted())
7692 .unwrap(),
7693 None,
7694 "no checkpoint exists at the policy anchor, so there must be no anchor at all",
7695 );
7696 assert_eq!(st.get_spendable_balance(account_id, policy), Zatoshis::ZERO);
7697
7698 let to = T::sk_default_address(&T::sk(&[0xf5; 32]));
7699 let request = TransactionRequest::new(vec![Payment::without_memo(
7700 to.to_zcash_address(st.network()),
7701 Zatoshis::const_from_u64(10000),
7702 )])
7703 .unwrap();
7704 let change_strategy =
7705 single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
7706 let input_selector = GreedyInputSelector::new();
7707 assert_matches!(
7708 st.propose_transfer(
7709 account_id,
7710 &input_selector,
7711 &change_strategy,
7712 request,
7713 policy
7714 ),
7715 Err(Error::ScanRequired)
7716 );
7717
7718 let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
7721 for _ in 0..advance {
7722 st.generate_next_block(
7723 ¬_our_key,
7724 AddressType::DefaultExternal,
7725 Zatoshis::const_from_u64(1000),
7726 );
7727 }
7728 st.scan_cached_blocks(scanned_tip + 1, advance as usize);
7729 let (target, anchor) = st
7730 .wallet()
7731 .get_target_and_anchor_heights(policy.trusted())
7732 .unwrap()
7733 .expect("a caught-up wallet has an anchor");
7734 assert_eq!(anchor, policy.anchor_height(target));
7735 assert_eq!(
7736 st.get_spendable_balance(account_id, policy),
7737 SHARD_1_NOTE_VALUE
7738 );
7739
7740 let last_filler = st
7743 .wallet()
7744 .chain_height()
7745 .unwrap()
7746 .expect("chain tip is known");
7747 let empty_blocks = u32::from(policy.trusted()) + 2;
7748 for _ in 0..empty_blocks {
7749 st.generate_empty_block();
7750 }
7751 st.scan_cached_blocks(last_filler + 1, empty_blocks as usize);
7752 let (target, anchor) = st
7753 .wallet()
7754 .get_target_and_anchor_heights(policy.trusted())
7755 .unwrap()
7756 .expect("a wallet synced across empty blocks has an anchor");
7757 assert!(
7758 policy.anchor_height(target) > last_filler,
7759 "test invariant: the policy depth must lie among the empty blocks",
7760 );
7761 assert_eq!(anchor, policy.anchor_height(target));
7762 assert_eq!(
7763 st.get_spendable_balance(account_id, policy),
7764 SHARD_1_NOTE_VALUE
7765 );
7766}
7767
7768pub fn spendable_balance_agrees_with_note_selection<T, Dsf>(ds_factory: Dsf, cache: impl TestCache)
7774where
7775 T: ShieldedPoolTester,
7776 Dsf: DataStoreFactory,
7777 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
7778{
7779 const RECEIVED_NOTES: u32 = 3;
7781 const SMALL_TIP_ADVANCE: u32 = 2;
7784 const FAR_TIP_ADVANCE_BEYOND_WINDOW: u32 = 20;
7787
7788 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
7789 let account_id = st.test_account().unwrap().id();
7790 let policy = ConfirmationsPolicy::default();
7791 let fvk = T::test_account_fvk(&st);
7792 let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
7793 let note_value = Zatoshis::const_from_u64(100_000);
7794 let filler_value = Zatoshis::const_from_u64(1000);
7795
7796 macro_rules! assert_agreement {
7797 ($state:expr) => {{
7798 let chain_tip = st
7799 .wallet()
7800 .chain_height()
7801 .unwrap()
7802 .expect("chain tip is known");
7803 let target_height = TargetHeight::from(chain_tip + 1);
7804 let summary = st.get_spendable_balance(account_id, policy);
7805 let selected_value = |target_value| {
7806 T::select_spendable_notes(&st, account_id, target_value, target_height, policy, &[])
7807 .unwrap()
7808 .iter()
7809 .map(|note| T::note_value(note.note()))
7810 .try_fold(Zatoshis::ZERO, |sum, value| sum + value)
7811 .expect("the selected value is in range")
7812 };
7813 assert_eq!(
7814 selected_value(TargetValue::AllFunds(MaxSpendMode::MaxSpendable)),
7815 summary,
7816 "selection of all spendable funds disagrees with the summary: {}",
7817 $state,
7818 );
7819 assert_eq!(
7820 selected_value(TargetValue::AtLeast(Zatoshis::const_from_u64(MAX_MONEY))),
7821 summary,
7822 "value-targeted selection disagrees with the summary: {}",
7823 $state,
7824 );
7825 summary
7826 }};
7827 }
7828
7829 let first_note_height = st
7830 .wallet()
7831 .chain_height()
7832 .unwrap()
7833 .map_or_else(|| st.sapling_activation_height(), |tip| tip + 1);
7834 for _ in 0..RECEIVED_NOTES {
7835 st.generate_next_block(&fvk, AddressType::DefaultExternal, note_value);
7836 }
7837 let confirming_blocks = u32::from(policy.untrusted());
7838 for _ in 0..confirming_blocks {
7839 st.generate_next_block(¬_our_key, AddressType::DefaultExternal, filler_value);
7840 }
7841 st.scan_cached_blocks(
7842 first_note_height,
7843 (RECEIVED_NOTES + confirming_blocks) as usize,
7844 );
7845 let confirmed_balance = assert_agreement!("confirmed notes");
7846 assert!(
7847 confirmed_balance > Zatoshis::ZERO,
7848 "test invariant: the confirmed notes must be spendable",
7849 );
7850
7851 let (unconfirmed_height, _, _) =
7852 st.generate_next_block(&fvk, AddressType::DefaultExternal, note_value);
7853 st.scan_cached_blocks(unconfirmed_height, 1);
7854 assert_agreement!("an unconfirmed note");
7855
7856 let tip = st
7857 .wallet()
7858 .chain_height()
7859 .unwrap()
7860 .expect("chain tip is known");
7861 st.wallet_mut()
7862 .update_chain_tip(tip + SMALL_TIP_ADVANCE)
7863 .unwrap();
7864 assert_agreement!("a chain tip advance shorter than the anchor depth");
7865
7866 let far_tip = tip + PRUNING_DEPTH + FAR_TIP_ADVANCE_BEYOND_WINDOW;
7867 st.wallet_mut().update_chain_tip(far_tip).unwrap();
7868 assert_eq!(
7869 assert_agreement!("a chain tip advance far beyond the pruning window"),
7870 Zatoshis::ZERO,
7871 "test invariant: no note is spendable before the wallet scans to the new tip",
7872 );
7873
7874 for _ in u32::from(tip)..u32::from(far_tip) {
7875 st.generate_next_block(¬_our_key, AddressType::DefaultExternal, filler_value);
7876 }
7877 st.scan_cached_blocks(tip + 1, (far_tip - tip) as usize);
7878 assert!(
7879 assert_agreement!("after the wallet scans to the new tip") > confirmed_balance,
7880 "test invariant: every received note must be spendable once the wallet is synced",
7881 );
7882}
7883
7884pub fn shard_completeness_derives_from_scan_queue<T, Dsf>(ds_factory: Dsf, cache: impl TestCache)
7890where
7891 T: ShieldedPoolTester,
7892 Dsf: DataStoreFactory,
7893 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
7894{
7895 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
7896 let value = Zatoshis::const_from_u64(500_000);
7897 let (note_height, _, _) = st.add_a_single_note_checking_balance(value);
7898 let account_id = st.test_account().unwrap().id();
7899 let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
7900 let filler_value = Zatoshis::const_from_u64(1000);
7901 let policy = ConfirmationsPolicy::default();
7902
7903 let buried_blocks = PRUNING_DEPTH + 10;
7905 for _ in 0..buried_blocks {
7906 st.generate_next_block(¬_our_key, AddressType::DefaultExternal, filler_value);
7907 }
7908 st.scan_cached_blocks(note_height + 1, buried_blocks as usize);
7909 let scanned_tip = st
7910 .wallet()
7911 .chain_height()
7912 .unwrap()
7913 .expect("chain tip is known");
7914 assert_eq!(st.get_spendable_balance(account_id, policy), value);
7915
7916 let shard_end = scanned_tip + 300;
7920 let new_tip = scanned_tip + 400;
7921 T::put_subtree_roots(
7922 &mut st,
7923 0,
7924 &[CommitmentTreeRoot::from_parts(
7925 shard_end,
7926 T::empty_tree_leaf(),
7927 )],
7928 )
7929 .unwrap();
7930 st.wallet_mut().update_chain_tip(new_tip).unwrap();
7931 for _ in 0..(new_tip - scanned_tip) {
7932 st.generate_next_block(¬_our_key, AddressType::DefaultExternal, filler_value);
7933 }
7934 let window_start = new_tip - (PRUNING_DEPTH - 1);
7935 st.scan_cached_blocks(window_start, PRUNING_DEPTH as usize);
7936
7937 assert_eq!(
7938 st.get_spendable_balance(account_id, policy),
7939 Zatoshis::ZERO,
7940 "the note's shard has unscanned blocks below the pruning window, so the note is not \
7941 witnessable and must not be reported spendable",
7942 );
7943
7944 st.scan_cached_blocks(scanned_tip + 1, (window_start - scanned_tip - 1) as usize);
7946 assert_eq!(st.get_spendable_balance(account_id, policy), value);
7947}
7948
7949pub fn completed_shard_note_spendable_after_scanning_anchor_window<T, Dsf>(
7954 ds_factory: Dsf,
7955 cache: impl TestCache,
7956) where
7957 T: ShieldedPoolTester,
7958 Dsf: DataStoreFactory,
7959 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
7960{
7961 let (mut st, account_id, usk) = build_stable_shard_fixture::<T, Dsf>(ds_factory, cache);
7962 let policy = ConfirmationsPolicy::default();
7963 assert_eq!(
7964 st.get_spendable_balance(account_id, policy),
7965 SHARD_1_NOTE_VALUE
7966 );
7967
7968 let scanned_tip = st
7971 .wallet()
7972 .chain_height()
7973 .unwrap()
7974 .expect("chain tip is known");
7975 let advance = 2 * PRUNING_DEPTH;
7976 let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
7977 let filler_value = Zatoshis::const_from_u64(1000);
7978 for _ in 0..advance {
7979 st.generate_next_block(¬_our_key, AddressType::DefaultExternal, filler_value);
7980 }
7981 let new_tip = scanned_tip + advance;
7982 st.wallet_mut().update_chain_tip(new_tip).unwrap();
7983 assert_eq!(
7984 st.get_spendable_balance(account_id, policy),
7985 Zatoshis::ZERO,
7986 "nothing is spendable until the wallet has scanned to the policy anchor",
7987 );
7988
7989 while let Some(range) = st
7991 .wallet()
7992 .suggest_scan_ranges()
7993 .unwrap()
7994 .into_iter()
7995 .find(|range| range.priority() > ScanPriority::ChainTip)
7996 {
7997 st.scan_cached_blocks(range.block_range().start, range.len());
7998 }
7999
8000 let window_start = new_tip - (PRUNING_DEPTH - 1);
8001 let unscanned = st.wallet().suggest_scan_ranges().unwrap();
8002 assert!(
8003 unscanned
8004 .iter()
8005 .any(|range| range.block_range().start < window_start),
8006 "test invariant: blocks below the pruning window must remain unscanned: {unscanned:?}",
8007 );
8008 assert_eq!(
8009 st.get_spendable_balance(account_id, policy),
8010 SHARD_1_NOTE_VALUE,
8011 "once the pruning window is scanned, the completed-shard note must be spendable",
8012 );
8013 assert_recovered_balance_spends::<T, _, _, _, _, _>(
8014 &mut st,
8015 account_id,
8016 &usk,
8017 SHARD_1_NOTE_VALUE,
8018 );
8019}
8020
8021pub fn open_shard_note_spendable_across_commitment_free_stretch<T, Dsf>(
8026 ds_factory: Dsf,
8027 cache: impl TestCache,
8028) where
8029 T: ShieldedPoolTester,
8030 Dsf: DataStoreFactory,
8031 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
8032{
8033 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
8034 let value = Zatoshis::const_from_u64(500_000);
8035 let (note_height, _, _) = st.add_a_single_note_checking_balance(value);
8036 let account_id = st.test_account().unwrap().id();
8037 let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
8038 let policy = ConfirmationsPolicy::default();
8039
8040 let buried_blocks = PRUNING_DEPTH + 10;
8042 for _ in 0..buried_blocks {
8043 st.generate_next_block(
8044 ¬_our_key,
8045 AddressType::DefaultExternal,
8046 Zatoshis::const_from_u64(1000),
8047 );
8048 }
8049 st.scan_cached_blocks(note_height + 1, buried_blocks as usize);
8050 let last_commitment = st
8051 .wallet()
8052 .chain_height()
8053 .unwrap()
8054 .expect("chain tip is known");
8055 assert_eq!(st.get_spendable_balance(account_id, policy), value);
8056
8057 let stretch = PRUNING_DEPTH + 10;
8060 for _ in 0..stretch {
8061 st.generate_empty_block();
8062 }
8063 st.scan_cached_blocks(last_commitment + 1, stretch as usize);
8064
8065 let (target, anchor) = st
8066 .wallet()
8067 .get_target_and_anchor_heights(policy.trusted())
8068 .unwrap()
8069 .expect("a synced wallet has an anchor");
8070 assert_eq!(
8071 anchor,
8072 policy.anchor_height(target),
8073 "every height within the pruning window is checkpointed, so the anchor is the policy \
8074 depth even though no block there carries a commitment",
8075 );
8076 assert_eq!(st.get_spendable_balance(account_id, policy), value);
8077}
8078
8079pub fn completed_shard_note_spendable_with_unscanned_gap_below_it<T, Dsf>(
8084 ds_factory: Dsf,
8085 cache: impl TestCache,
8086) where
8087 T: ShieldedPoolTester,
8088 Dsf: DataStoreFactory,
8089 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
8090{
8091 const BLOCK_A1_FILLERS: u32 = 35;
8093 const NOTE_VALUE: Zatoshis = Zatoshis::const_from_u64(150_000);
8094
8095 let (mut st, account_id, usk, dfvk) = build_shard_1_prefix_fixture::<T, Dsf>(ds_factory, cache);
8096
8097 let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
8098 let filler_value = Zatoshis::const_from_u64(1000);
8099
8100 let block_a1_outputs: Vec<_> = (0..BLOCK_A1_FILLERS)
8103 .map(|_| {
8104 FakeCompactOutput::new(
8105 not_our_key.clone(),
8106 AddressType::DefaultExternal,
8107 filler_value,
8108 )
8109 })
8110 .collect();
8111 let (block_a1_height, _, _) = st.generate_next_block_multi(&block_a1_outputs);
8112
8113 let block_a2_output_count = SHARD_1_FRONTIER_GAP - BLOCK_A1_FILLERS;
8115 let mut block_a2_outputs = Vec::with_capacity(block_a2_output_count as usize);
8116 block_a2_outputs.push(FakeCompactOutput::new(
8117 dfvk.clone(),
8118 AddressType::DefaultExternal,
8119 NOTE_VALUE,
8120 ));
8121 for _ in 1..block_a2_output_count {
8122 block_a2_outputs.push(FakeCompactOutput::new(
8123 not_our_key.clone(),
8124 AddressType::DefaultExternal,
8125 filler_value,
8126 ));
8127 }
8128 let (block_a2_height, _, _) = st.generate_next_block_multi(&block_a2_outputs);
8129
8130 let trailing_blocks = PRUNING_DEPTH + 10;
8132 for _ in 0..trailing_blocks {
8133 st.generate_next_block(¬_our_key, AddressType::DefaultExternal, filler_value);
8134 }
8135 let chain_tip = block_a2_height + trailing_blocks;
8136
8137 st.wallet_mut().update_chain_tip(chain_tip).unwrap();
8139 st.scan_cached_blocks(block_a2_height, 1);
8140 let shard_1_root = T::shard_root(&mut st, 1).unwrap();
8141 T::put_subtree_roots(
8142 &mut st,
8143 1,
8144 &[CommitmentTreeRoot::from_parts(
8145 block_a2_height,
8146 shard_1_root,
8147 )],
8148 )
8149 .unwrap();
8150 st.scan_cached_blocks(block_a2_height + 1, trailing_blocks as usize);
8151
8152 let unscanned = st.wallet().suggest_scan_ranges().unwrap();
8153 assert!(
8154 unscanned
8155 .iter()
8156 .any(|range| range.block_range().contains(&block_a1_height)),
8157 "test invariant: Block A1 must remain unscanned: {unscanned:?}",
8158 );
8159
8160 assert_eq!(
8161 st.get_spendable_balance(account_id, ConfirmationsPolicy::default()),
8162 NOTE_VALUE,
8163 "every leaf after the note through its shard's end is present, so the note is \
8164 witnessable and must be spendable",
8165 );
8166 assert_recovered_balance_spends::<T, _, _, _, _, _>(&mut st, account_id, &usk, NOTE_VALUE);
8167}
8168
8169pub fn stabilized_note_settled_height_invalidated_by_reorg<T, Dsf>(
8194 ds_factory: Dsf,
8195 cache: impl TestCache,
8196) where
8197 T: ShieldedPoolTester,
8198 Dsf: DataStoreFactory,
8199 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
8200{
8201 let (mut st, account_id, usk) = build_stable_shard_fixture::<T, Dsf>(ds_factory, cache);
8202 let policy = ConfirmationsPolicy::default();
8203
8204 assert_eq!(
8206 st.get_spendable_balance(account_id, policy),
8207 SHARD_1_NOTE_VALUE,
8208 "fixture must report the stabilized note as spendable under the default policy",
8209 );
8210
8211 let to = T::sk_default_address(&T::sk(&[0xf5; 32]));
8219 let request = TransactionRequest::new(vec![Payment::without_memo(
8220 to.to_zcash_address(st.network()),
8221 Zatoshis::const_from_u64(10000),
8222 )])
8223 .unwrap();
8224 let change_strategy =
8225 single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
8226 let input_selector = GreedyInputSelector::new();
8227 let proposal = st
8228 .propose_transfer(
8229 account_id,
8230 &input_selector,
8231 &change_strategy,
8232 request,
8233 policy,
8234 )
8235 .unwrap();
8236 let txid = st
8237 .create_proposed_transactions::<Infallible, _, Infallible, _>(
8238 &usk,
8239 OvkPolicy::Sender,
8240 &proposal,
8241 )
8242 .unwrap()[0];
8243
8244 let dfvk = T::sk_to_fvk(T::usk_to_sk(&usk));
8253 let extra_note_value = Zatoshis::const_from_u64(25000);
8254 let (extra_height, _, _) =
8255 st.generate_next_block(&dfvk, AddressType::DefaultExternal, extra_note_value);
8256
8257 let not_our_fvk = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
8258 let filler_value = Zatoshis::const_from_u64(1000);
8259 st.generate_next_block(¬_our_fvk, AddressType::DefaultExternal, filler_value);
8260
8261 let (tx_height, _) = st.generate_next_block_including(txid);
8262
8263 st.scan_cached_blocks(extra_height, 3);
8271
8272 let change_value = (st.get_total_balance(account_id) - extra_note_value)
8276 .expect("balance covers the extra note value");
8277 assert!(change_value > Zatoshis::ZERO);
8278
8279 let rewind_target = tx_height - 3;
8285 st.wallet_mut()
8286 .rewind_to_chain_state(
8287 ChainState::empty(rewind_target, BlockHash([0; 32])),
8288 HashSet::new(),
8289 )
8290 .expect("rewind_to_chain_state should succeed");
8291 st.truncate_cache_to_height(rewind_target);
8292
8293 let (remine_height, _) = st.generate_next_block_including(txid);
8296 assert_eq!(remine_height, tx_height - 2);
8297
8298 let (gap_height, _, _) =
8303 st.generate_next_block(¬_our_fvk, AddressType::DefaultExternal, filler_value);
8304 assert_eq!(gap_height, tx_height - 1);
8305
8306 let mut new_tip = gap_height;
8312 for _ in 0..(PRUNING_DEPTH + 1) {
8313 new_tip = st
8314 .generate_next_block(¬_our_fvk, AddressType::DefaultExternal, filler_value)
8315 .0;
8316 }
8317
8318 st.scan_cached_blocks(remine_height, 1);
8323 st.wallet_mut().update_chain_tip(new_tip).unwrap();
8324 st.scan_cached_blocks(gap_height + 1, (PRUNING_DEPTH + 1) as usize);
8325
8326 assert_eq!(
8332 st.get_spendable_balance(account_id, policy),
8333 Zatoshis::ZERO,
8334 "a settled height written on the reorged-away chain must not vouch for \
8335 spendability while the new chain has an unscanned gap below the pruning window",
8336 );
8337
8338 st.scan_cached_blocks(gap_height, 1);
8341 assert_eq!(
8342 st.get_spendable_balance(account_id, policy),
8343 change_value,
8344 "closing the gap must restore spendability of the change note",
8345 );
8346}
8347
8348pub fn reorg_to_checkpoint<T: ShieldedPoolTester, Dsf, C>(ds_factory: Dsf, cache: C)
8349where
8350 Dsf: DataStoreFactory,
8351 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
8352 C: TestCache,
8353{
8354 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
8355
8356 let account = st.test_account().cloned().unwrap();
8357
8358 let p0_fvk = T::random_fvk(st.rng_mut());
8360 let gen_random_block = |st: &mut TestState<C, Dsf::DataStore, LocalNetwork>,
8361 output_count: usize| {
8362 let fake_outputs =
8363 std::iter::repeat_with(|| FakeCompactOutput::random(st.rng_mut(), p0_fvk.clone()))
8364 .take(output_count)
8365 .collect::<Vec<_>>();
8366 st.generate_next_block_multi(&fake_outputs[..]);
8367 output_count
8368 };
8369
8370 for _ in 0..10 {
8372 gen_random_block(&mut st, 4);
8373 }
8374
8375 let reorg_height = account.birthday().height() + 4;
8377 let reorg_position = Position::from(19);
8378
8379 st.scan_cached_blocks(account.birthday().height(), 5);
8382 assert_eq!(
8383 st.wallet()
8384 .block_max_scanned()
8385 .unwrap()
8386 .unwrap()
8387 .block_height(),
8388 reorg_height
8389 );
8390
8391 let checkpoints = st
8394 .wallet()
8395 .get_checkpoint_history(&T::SHIELDED_PROTOCOL)
8396 .unwrap();
8397 assert_eq!(checkpoints.len(), 6);
8398 assert_eq!(
8399 checkpoints.last(),
8400 Some(&(reorg_height, Some(reorg_position)))
8401 );
8402
8403 st.scan_cached_blocks(reorg_height + 1, 1);
8405 assert_eq!(
8406 st.wallet()
8407 .block_max_scanned()
8408 .unwrap()
8409 .unwrap()
8410 .block_height(),
8411 reorg_height + 1
8412 );
8413 let checkpoints = st
8414 .wallet()
8415 .get_checkpoint_history(&T::SHIELDED_PROTOCOL)
8416 .unwrap();
8417 assert_eq!(checkpoints.len(), 7);
8418 assert_eq!(
8419 checkpoints.last(),
8420 Some(&(reorg_height + 1, Some(reorg_position + 4)))
8421 );
8422
8423 st.truncate_to_height_retaining_cache(reorg_height);
8429
8430 let checkpoints = st
8438 .wallet()
8439 .get_checkpoint_history(&T::SHIELDED_PROTOCOL)
8440 .unwrap();
8441 assert_eq!(checkpoints.len(), 6);
8442 assert_eq!(
8443 checkpoints.last(),
8444 Some(&(reorg_height, Some(reorg_position)))
8445 );
8446
8447 st.scan_cached_blocks(reorg_height + 2, 1);
8449
8450 let checkpoints = st
8456 .wallet()
8457 .get_checkpoint_history(&T::SHIELDED_PROTOCOL)
8458 .unwrap();
8459 assert_eq!(checkpoints.len(), 8);
8462 assert_eq!(
8463 checkpoints.last(),
8464 Some(&(reorg_height + 2, Some(reorg_position + 8)))
8465 );
8466
8467 st.truncate_to_height(reorg_height);
8470
8471 for _ in 0..10 {
8473 let output_count = st.rng_mut().random_range(2..10);
8474 gen_random_block(&mut st, output_count);
8475 }
8476
8477 st.scan_cached_blocks(reorg_height + 1, 1);
8482}
8483
8484pub fn scan_cached_blocks_allows_blocks_out_of_order<T: ShieldedPoolTester>(
8485 ds_factory: impl DataStoreFactory,
8486 cache: impl TestCache,
8487) {
8488 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
8489
8490 let account = st.test_account().cloned().unwrap();
8491 let dfvk = T::test_account_fvk(&st);
8492
8493 let value = Zatoshis::const_from_u64(50000);
8494 let (h1, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
8495 st.scan_cached_blocks(h1, 1);
8496 assert_eq!(st.get_total_balance(account.id()), value);
8497
8498 let (h2, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
8500 let (h3, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
8501
8502 st.scan_cached_blocks(h3, 1);
8504
8505 st.scan_cached_blocks(h2, 1);
8507 assert_eq!(
8508 st.get_total_balance(account.id()),
8509 Zatoshis::const_from_u64(150_000)
8510 );
8511
8512 let req = TransactionRequest::new(vec![Payment::without_memo(
8514 T::fvk_default_address(&dfvk).to_zcash_address(st.network()),
8515 Zatoshis::const_from_u64(110_000),
8516 )])
8517 .unwrap();
8518
8519 let input_selector = GreedyInputSelector::new();
8520 let change_strategy =
8521 single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
8522
8523 assert_matches!(
8524 st.spend(
8525 &input_selector,
8526 &change_strategy,
8527 account.usk(),
8528 req,
8529 OvkPolicy::Sender,
8530 ConfirmationsPolicy::MIN,
8531 ),
8532 Ok(_)
8533 );
8534}
8535
8536pub fn scan_cached_blocks_finds_received_notes<T: ShieldedPoolTester, Dsf>(
8537 ds_factory: Dsf,
8538 cache: impl TestCache,
8539) where
8540 Dsf: DataStoreFactory,
8541 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
8542{
8543 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
8544
8545 let account = st.test_account().cloned().unwrap();
8546 let dfvk = T::test_account_fvk(&st);
8547
8548 assert_eq!(st.get_wallet_summary(ConfirmationsPolicy::MIN), None);
8550
8551 let value = Zatoshis::const_from_u64(50000);
8553 let (h1, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
8554
8555 let summary = st.scan_cached_blocks(h1, 1);
8557 assert_eq!(summary.scanned_range().start, h1);
8558 assert_eq!(summary.scanned_range().end, h1 + 1);
8559 assert_eq!(T::received_note_count(&summary), 1);
8560
8561 assert_eq!(st.get_total_balance(account.id()), value);
8563
8564 let value2 = Zatoshis::const_from_u64(70000);
8566 let (h2, _, _) = st.generate_next_block(&dfvk, AddressType::DefaultExternal, value2);
8567
8568 let summary = st.scan_cached_blocks(h2, 1);
8570 assert_eq!(summary.scanned_range().start, h2);
8571 assert_eq!(summary.scanned_range().end, h2 + 1);
8572 assert_eq!(T::received_note_count(&summary), 1);
8573
8574 assert_eq!(
8576 st.get_total_balance(account.id()),
8577 (value + value2).unwrap()
8578 );
8579}
8580
8581pub fn scan_cached_blocks_finds_change_notes<T: ShieldedPoolTester, Dsf>(
8582 ds_factory: Dsf,
8583 cache: impl TestCache,
8584) where
8585 Dsf: DataStoreFactory,
8586 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
8587{
8588 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
8589
8590 let account = st.test_account().cloned().unwrap();
8591 let dfvk = T::test_account_fvk(&st);
8592
8593 assert_eq!(st.get_wallet_summary(ConfirmationsPolicy::MIN), None);
8595
8596 let value = Zatoshis::const_from_u64(50000);
8598 let (_, _, nf) = st.add_a_single_note_checking_balance(value);
8599
8600 let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
8602 let to2 = T::fvk_default_address(¬_our_key);
8603 let value2 = Zatoshis::const_from_u64(20000);
8604 let (spent_height, _) = st.generate_next_block_spending(&dfvk, (nf, value), to2, value2);
8605
8606 st.scan_cached_blocks(spent_height, 1);
8608
8609 assert_eq!(
8611 st.get_total_balance(account.id()),
8612 (value - value2).unwrap()
8613 );
8614}
8615
8616pub fn scan_cached_blocks_detects_spends_out_of_order<T: ShieldedPoolTester, Dsf>(
8617 ds_factory: Dsf,
8618 cache: impl TestCache,
8619) where
8620 Dsf: DataStoreFactory,
8621 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
8622{
8623 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
8624
8625 let account = st.test_account().cloned().unwrap();
8626 let dfvk = T::test_account_fvk(&st);
8627
8628 assert_eq!(st.get_wallet_summary(ConfirmationsPolicy::MIN), None);
8630
8631 let value = Zatoshis::const_from_u64(50000);
8633 let (received_height, _, nf) =
8634 st.generate_next_block(&dfvk, AddressType::DefaultExternal, value);
8635
8636 let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
8638 let to2 = T::fvk_default_address(¬_our_key);
8639 let value2 = Zatoshis::const_from_u64(20000);
8640 let (spent_height, _) = st.generate_next_block_spending(&dfvk, (nf, value), to2, value2);
8641
8642 st.scan_cached_blocks(spent_height, 1);
8644
8645 assert_eq!(
8647 st.get_total_balance(account.id()),
8648 (value - value2).unwrap()
8649 );
8650
8651 st.scan_cached_blocks(received_height, 1);
8653
8654 assert_eq!(
8656 st.get_total_balance(account.id()),
8657 (value - value2).unwrap()
8658 );
8659}
8660
8661pub fn oldest_note_is_selected_first<T: ShieldedPoolTester, Dsf>(
8667 ds_factory: Dsf,
8668 cache: impl TestCache,
8669) where
8670 Dsf: DataStoreFactory,
8671{
8672 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
8673 let account = st.test_account().cloned().unwrap();
8674 let dfvk = T::test_account_fvk(&st);
8675
8676 let older_value = Zatoshis::const_from_u64(500_000);
8679 let newer_value = Zatoshis::const_from_u64(300_000);
8680 let (older_height, _, _) =
8681 st.generate_next_block(&dfvk, AddressType::DefaultExternal, older_value);
8682 let (newer_height, _, _) =
8683 st.generate_next_block(&dfvk, AddressType::DefaultExternal, newer_value);
8684
8685 st.scan_cached_blocks(newer_height, 1);
8688 st.scan_cached_blocks(older_height, 1);
8689
8690 let selected = T::select_spendable_notes(
8692 &st,
8693 account.id(),
8694 TargetValue::AtLeast(Zatoshis::const_from_u64(200_000)),
8695 TargetHeight::from(newer_height + 1),
8696 ConfirmationsPolicy::MIN,
8697 &[],
8698 )
8699 .unwrap();
8700 assert_eq!(selected.len(), 1, "a single note covers the target");
8701 assert_eq!(
8702 T::note_value(selected.first().expect("nonempty").note()),
8703 older_value,
8704 "the oldest sufficient note must be drawn first, not the first-discovered"
8705 );
8706}
8707
8708pub fn metadata_queries_exclude_unwanted_notes<T: ShieldedPoolTester, Dsf, TC>(
8709 ds_factory: Dsf,
8710 cache: TC,
8711) where
8712 Dsf: DataStoreFactory,
8713 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
8714 TC: TestCache,
8715{
8716 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
8717
8718 let note_values = (1..=10)
8720 .map(|i| Zatoshis::const_from_u64(i * 100_0000))
8721 .collect::<Vec<_>>();
8722 let h0 = st
8723 .add_notes_checking_balance(note_values.clone().into_iter().map(Some))
8724 .first_block_height()
8725 .unwrap();
8726
8727 let target_height = TargetHeight::from(h0 + 10);
8728 let account = st.test_account().cloned().unwrap();
8729 let test_meta = |st: &TestState<TC, Dsf::DataStore, LocalNetwork>, query, expected_count| {
8730 let metadata = st
8731 .wallet()
8732 .get_account_metadata(
8733 account.id(),
8734 &query,
8735 target_height,
8736 &[],
8737 LockFilter::Unfiltered,
8738 )
8739 .unwrap();
8740
8741 assert_eq!(metadata.note_count(T::SHIELDED_PROTOCOL), expected_count);
8742 };
8743
8744 test_meta(
8745 &st,
8746 NoteFilter::ExceedsMinValue(Zatoshis::const_from_u64(1000_0000)),
8747 Some(0),
8748 );
8749 test_meta(
8750 &st,
8751 NoteFilter::ExceedsMinValue(Zatoshis::const_from_u64(500_0000)),
8752 Some(5),
8753 );
8754 test_meta(
8755 &st,
8756 NoteFilter::ExceedsBalancePercentage(BoundedU8::new_const(10)),
8757 Some(5),
8758 );
8759
8760 test_meta(
8762 &st,
8763 NoteFilter::ExceedsPriorSendPercentile(BoundedU8::new_const(50)),
8764 None,
8765 );
8766
8767 let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
8772 let to = T::fvk_default_address(¬_our_key).to_zcash_address(st.network());
8773 let nz2 = NonZeroU64::new(2).unwrap();
8774
8775 for value in ¬e_values {
8776 let txids = st
8777 .create_standard_transaction(&account, to.clone(), *value / nz2)
8778 .unwrap();
8779 st.generate_next_block_including(txids.head);
8780 }
8781 st.scan_cached_blocks(h0 + 10, 10);
8782
8783 test_meta(
8787 &st,
8788 NoteFilter::ExceedsPriorSendPercentile(BoundedU8::new_const(50)),
8789 Some(5),
8790 );
8791}
8792
8793#[cfg(feature = "pczt")]
8794pub fn pczt_single_step<P0: ShieldedPoolTester, P1: ShieldedPoolTester, Dsf>(
8795 ds_factory: Dsf,
8796 cache: impl TestCache,
8797 pin_expiry_above_target: Option<u32>,
8798) where
8799 Dsf: DataStoreFactory,
8800 <Dsf as DataStoreFactory>::AccountId: serde::Serialize + serde::de::DeserializeOwned,
8801{
8802 let mut st = TestBuilder::new()
8803 .with_data_store_factory(ds_factory)
8804 .with_block_cache(cache)
8805 .with_initial_chain_state(|_, network| {
8806 let birthday_height = std::cmp::max(
8808 network.activation_height(NetworkUpgrade::Nu5).unwrap(),
8809 network.activation_height(NetworkUpgrade::Canopy).unwrap() + ZIP212_GRACE_PERIOD,
8810 );
8811
8812 #[cfg(feature = "orchard")]
8814 let ironwood_initial_tree = Frontier::empty();
8815
8816 InitialChainState {
8817 chain_state: ChainState::new(
8818 birthday_height - 1,
8819 BlockHash([5; 32]),
8820 Frontier::empty(),
8821 #[cfg(feature = "orchard")]
8822 Frontier::empty(),
8823 #[cfg(feature = "orchard")]
8824 ironwood_initial_tree,
8825 ),
8826 prior_sapling_roots: vec![],
8827 #[cfg(feature = "orchard")]
8828 prior_orchard_roots: vec![],
8829 }
8830 })
8831 .with_account_having_current_birthday()
8832 .build();
8833
8834 let account = st.test_account().cloned().unwrap();
8835
8836 let p0_fvk = P0::test_account_fvk(&st);
8837
8838 let p1_fvk = P1::test_account_fvk(&st);
8839 let p1_to = P1::fvk_default_address(&p1_fvk);
8840
8841 let note_value = Zatoshis::const_from_u64(350000);
8843 st.generate_next_block(&p0_fvk, AddressType::DefaultExternal, note_value);
8844 st.scan_cached_blocks(account.birthday().height(), 1);
8845
8846 assert_eq!(st.get_total_balance(account.id()), note_value);
8847 assert_eq!(
8848 st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
8849 note_value
8850 );
8851
8852 let transfer_amount = Zatoshis::const_from_u64(200000);
8853 let p0_to_p1 = TransactionRequest::new(vec![Payment::without_memo(
8854 p1_to.to_zcash_address(st.network()),
8855 transfer_amount,
8856 )])
8857 .unwrap();
8858
8859 let input_selector = GreedyInputSelector::new();
8860 let change_strategy =
8861 single_output_change_strategy(StandardFeeRule::Zip317, None, P0::SHIELDED_PROTOCOL);
8862 let proposal0 = st
8863 .propose_transfer(
8864 account.id(),
8865 &input_selector,
8866 &change_strategy,
8867 p0_to_p1,
8868 ConfirmationsPolicy::MIN,
8869 )
8870 .unwrap();
8871
8872 let min_target_height = proposal0.min_target_height();
8873 assert_eq!(proposal0.steps().len(), 1);
8874
8875 let expiry_height =
8876 pin_expiry_above_target.map(|delta| BlockHeight::from(min_target_height) + delta);
8877
8878 if expiry_height.is_some() {
8879 assert_matches!(
8882 st.create_pczt_from_proposal::<Infallible, _, Infallible>(
8883 account.id(),
8884 OvkPolicy::Sender,
8885 &proposal0,
8886 Some(min_target_height.saturating_sub(1)),
8887 ),
8888 Err(Error::ExpiryHeightBelowTargetHeight { .. })
8889 );
8890 }
8891
8892 let create_proposed_result = st.create_pczt_from_proposal::<Infallible, _, Infallible>(
8893 account.id(),
8894 OvkPolicy::Sender,
8895 &proposal0,
8896 expiry_height,
8897 );
8898 assert_matches!(&create_proposed_result, Ok(_));
8899 let pczt_created = create_proposed_result.unwrap();
8900 let pczt_branch_id =
8901 consensus::BranchId::try_from(*pczt_created.global().consensus_branch_id())
8902 .expect("the PCZT carries a valid consensus branch ID");
8903
8904 fn assert_signable_orchard_bundle(bundle: &orchard::pczt::Bundle) {
8911 for action in bundle.actions() {
8912 assert!(
8913 action.spend().spend_auth_sig().is_some()
8914 || action.spend().dummy_sk().is_some()
8915 || action.spend().zip32_derivation().is_some(),
8916 "unsignable Orchard-protocol spend: no signature, dummy key, or derivation",
8917 );
8918 }
8919 }
8920 pczt::roles::verifier::Verifier::new(pczt_created.clone())
8921 .with_orchard::<Infallible, _>(|bundle| {
8922 assert_signable_orchard_bundle(bundle);
8923 Ok(())
8924 })
8925 .unwrap()
8926 .with_ironwood::<Infallible, _>(|bundle| {
8927 assert_signable_orchard_bundle(bundle);
8928 Ok(())
8929 })
8930 .unwrap()
8931 .with_sapling::<Infallible, _>(|bundle| {
8932 for spend in bundle.spends() {
8933 assert!(
8934 spend.spend_auth_sig().is_some()
8935 || spend.proof_generation_key().is_some()
8936 || spend.zip32_derivation().is_some(),
8937 "unsignable Sapling spend: no signature, dummy proving material, or derivation",
8938 );
8939 }
8940 Ok(())
8941 })
8942 .unwrap();
8943
8944 assert_matches!(
8946 st.extract_and_store_transaction_from_pczt(pczt_created.clone()),
8947 Err(Error::Pczt(data_api::error::PcztError::Extraction(_)))
8948 );
8949
8950 let pczt_updated = P0::add_proof_generation_keys(pczt_created, account.usk()).unwrap();
8952
8953 let sapling_prover = LocalTxProver::bundled();
8959 let orchard_pk = zcash_primitives::transaction::builder::cached_orchard_proving_key(
8960 zcash_primitives::transaction::components::orchard::bundle_version_for_branch(
8961 pczt_branch_id,
8962 ::orchard::ValuePool::Orchard,
8963 )
8964 .expect("the PCZT's consensus branch supports the Orchard pool")
8965 .circuit_version(),
8966 );
8967 let pczt_proven = Prover::new(pczt_updated)
8968 .create_orchard_proof(UnwrapErr(SysRng), orchard_pk)
8969 .unwrap()
8970 .create_sapling_proofs(UnwrapErr(SysRng), &sapling_prover, &sapling_prover)
8971 .unwrap()
8972 .finish();
8973
8974 let original_sighash = Signer::new(pczt_proven.clone()).unwrap().shielded_sighash();
8979 let original_len = pczt_proven.clone().serialize().unwrap().len();
8980 let signer_view = redact_pczt_for_signer(&pczt_proven, SignerView::Compact);
8981 assert_eq!(
8982 *signer_view.global().tx_version(),
8983 zcash_protocol::constants::V5_TX_VERSION,
8984 );
8985 assert_eq!(
8986 signer_view.sapling().anchor(),
8987 pczt_proven.sapling().anchor()
8988 );
8989 assert_eq!(
8990 signer_view.orchard().anchor(),
8991 pczt_proven.orchard().anchor()
8992 );
8993 if !signer_view.orchard().actions().is_empty() {
8994 assert!(pczt::v1::Pczt::try_from(signer_view.clone()).is_err());
8995 assert!(
8996 signer_view
8997 .orchard()
8998 .actions()
8999 .iter()
9000 .all(|action| action.cv_net().is_none() && action.output().cmx().is_none())
9001 );
9002 }
9003
9004 let signer_view_bytes = signer_view.serialize().unwrap();
9005 assert!(signer_view_bytes.len() < original_len);
9006 let signer_view = pczt::Pczt::parse(&signer_view_bytes).unwrap();
9007 assert_eq!(
9008 Signer::new(signer_view.clone()).unwrap().shielded_sighash(),
9009 original_sighash,
9010 );
9011
9012 let full_view = redact_pczt_for_signer(&pczt_proven, SignerView::Full);
9017 assert_eq!(
9018 Signer::new(full_view.clone()).unwrap().shielded_sighash(),
9019 original_sighash,
9020 );
9021 assert_eq!(full_view.orchard().anchor(), pczt_proven.orchard().anchor());
9022 assert_eq!(full_view.sapling().anchor(), pczt_proven.sapling().anchor());
9023 assert_eq!(
9024 full_view.orchard().zkproof().is_some(),
9025 pczt_proven.orchard().zkproof().is_some(),
9026 );
9027 assert!(full_view.orchard().actions().iter().all(|action| {
9028 action.spend().witness().is_none() && action.spend().dummy_sk().is_none()
9029 }));
9030 assert!(
9031 full_view
9032 .sapling()
9033 .spends()
9034 .iter()
9035 .all(|spend| spend.witness().is_none())
9036 );
9037 assert!(
9040 !full_view
9041 .global()
9042 .proprietary()
9043 .contains_key("zcash_client_backend:proposal_info")
9044 );
9045 for bundle in [full_view.orchard(), full_view.ironwood()] {
9046 assert!(bundle.actions().iter().all(|action| {
9047 !action
9048 .output()
9049 .proprietary()
9050 .contains_key("zcash_client_backend:output_info")
9051 }));
9052 }
9053 assert!(full_view.sapling().outputs().iter().all(|output| {
9054 !output
9055 .proprietary()
9056 .contains_key("zcash_client_backend:output_info")
9057 }));
9058 assert!(full_view.transparent().outputs().iter().all(|output| {
9059 !output
9060 .proprietary()
9061 .contains_key("zcash_client_backend:output_info")
9062 }));
9063 if *full_view.global().tx_version() == zcash_protocol::constants::V5_TX_VERSION {
9064 let full_view_bytes = full_view.clone().serialize().unwrap();
9065 assert!(pczt::v1::Pczt::try_from(full_view).is_ok());
9066 assert_eq!(
9067 u32::from_le_bytes(full_view_bytes[4..8].try_into().unwrap()),
9068 1,
9069 "the full signer view of a v5 PCZT serializes in the v1 encoding",
9070 );
9071 }
9072
9073 let mut signer = Signer::new(signer_view).unwrap();
9076 P0::apply_signatures_to_pczt(&mut signer, account.usk()).unwrap();
9077 let pczt_authorized = Combiner::new(vec![pczt_proven, signer.finish()])
9078 .combine()
9079 .unwrap();
9080
9081 let extract_and_store_result = st.extract_and_store_transaction_from_pczt(pczt_authorized);
9083 assert_matches!(&extract_and_store_result, Ok(_));
9084 let txid = extract_and_store_result.unwrap();
9085
9086 if let Some(expiry_height) = expiry_height {
9087 let tx = st.wallet().get_transaction(txid).unwrap().unwrap();
9088 assert_eq!(tx.expiry_height(), expiry_height);
9089 }
9090
9091 let (h, _) = st.generate_next_block_including(txid);
9092 st.scan_cached_blocks(h, 1);
9093}
9094
9095#[cfg(feature = "transparent-inputs")]
9101pub fn wallet_recovery_computes_fees<T: ShieldedPoolTester, DsF: DataStoreFactory>(
9102 ds_factory: DsF,
9103 cache: impl TestCache,
9104 mut intervene: impl FnMut(&mut DsF::DataStore, TxId) -> Result<(), DsF::DsError>,
9105) {
9106 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
9107
9108 let seed = Secret::new(st.test_seed().unwrap().expose_secret().clone());
9109 let source_account = st.test_account().cloned().unwrap();
9110 let (dest_account_id, dest_usk) = st
9111 .wallet_mut()
9112 .create_account("dest", &seed, source_account.birthday(), None)
9113 .unwrap();
9114
9115 let (to, _) = dest_usk.default_transparent_address();
9116
9117 let note_value = Zatoshis::const_from_u64(350000);
9119 let _summary = st.add_notes_checking_balance([Some(note_value), Some(note_value)]);
9120
9121 let input_selector = GreedyInputSelector::new();
9124 let change_strategy =
9125 single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
9126 let transfer_amount = Zatoshis::const_from_u64(200000);
9127 let request = TransactionRequest::new(vec![Payment::without_memo(
9128 Address::from(to).to_zcash_address(st.network()),
9129 transfer_amount,
9130 )])
9131 .unwrap();
9132
9133 let mut send_transparent = || {
9134 let p0 = st
9135 .propose_transfer(
9136 source_account.id(),
9137 &input_selector,
9138 &change_strategy,
9139 request.clone(),
9140 ConfirmationsPolicy::MIN,
9141 )
9142 .unwrap();
9143 let result0 = st
9144 .create_proposed_transactions::<Infallible, _, Infallible, _>(
9145 source_account.usk(),
9146 OvkPolicy::Sender,
9147 &p0,
9148 )
9149 .unwrap();
9150 assert_eq!(result0.len(), 1);
9151 let txid = result0[0];
9152 let (h, _) = st.generate_next_block_including(txid);
9153 st.scan_cached_blocks(h, 1);
9154
9155 let tx = st.wallet().get_transaction(txid).unwrap().unwrap();
9157 let t_bundle = tx.transparent_bundle().unwrap();
9158 assert_eq!(t_bundle.vout.len(), 1);
9159
9160 let outpoint = OutPoint::new(*txid.as_ref(), 0);
9161 let utxo = WalletTransparentOutput::from_parts(
9162 outpoint,
9163 t_bundle.vout[0].clone(),
9164 Some(h),
9165 Some(dest_account_id),
9166 Some(TransparentKeyScope::EXTERNAL),
9167 None,
9168 )
9169 .unwrap();
9170 st.wallet_mut()
9171 .put_received_transparent_utxo(&utxo)
9172 .unwrap();
9173
9174 (txid, h)
9175 };
9176
9177 send_transparent();
9178 let (input_tx_1_txid, input_tx_1_height) = send_transparent();
9179
9180 assert_eq!(
9181 st.get_total_balance(dest_account_id),
9182 (transfer_amount + transfer_amount).unwrap()
9183 );
9184
9185 let p1 = st
9187 .propose_shielding(
9188 &input_selector,
9189 &change_strategy,
9190 Zatoshis::const_from_u64(10000),
9191 &[to],
9192 dest_account_id,
9193 ConfirmationsPolicy::MIN,
9194 CoinbaseFilter::AllTransparentOutputs,
9195 )
9196 .unwrap();
9197 let result1 = st
9198 .create_proposed_transactions::<Infallible, _, Infallible, _>(
9199 &dest_usk,
9200 OvkPolicy::Sender,
9201 &p1,
9202 )
9203 .unwrap();
9204 assert_eq!(result1.len(), 1);
9205 let txid = result1[0];
9206 let (h, _) = st.generate_next_block_including(txid);
9207 st.scan_cached_blocks(h, 1);
9208
9209 let shielding_tx = st.get_tx_from_history(txid).unwrap().unwrap();
9213 assert_matches!(shielding_tx.fee_paid, Some(_));
9214 let created_fee = shielding_tx.fee_paid.unwrap();
9215
9216 intervene(st.wallet_mut(), txid).unwrap();
9217
9218 let shielding_tx = st.get_tx_from_history(txid).unwrap().unwrap();
9220 assert_matches!(shielding_tx.fee_paid, None);
9221
9222 let tx = st.wallet().get_transaction(txid).unwrap().unwrap();
9225 let network = *st.network();
9226 decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, Some(h)).unwrap();
9227
9228 let shielding_tx = st.get_tx_from_history(txid).unwrap().unwrap();
9230 assert_eq!(shielding_tx.fee_paid, Some(created_fee));
9231
9232 intervene(st.wallet_mut(), txid).unwrap();
9235
9236 let shielding_tx = st.get_tx_from_history(txid).unwrap().unwrap();
9237 assert_matches!(shielding_tx.fee_paid, None);
9238
9239 let tx = st
9242 .wallet()
9243 .get_transaction(input_tx_1_txid)
9244 .unwrap()
9245 .unwrap();
9246 let network = *st.network();
9247 decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, Some(input_tx_1_height)).unwrap();
9248
9249 let shielding_tx = st.get_tx_from_history(txid).unwrap().unwrap();
9251 assert_eq!(shielding_tx.fee_paid, Some(created_fee));
9252}
9253
9254pub fn receive_two_notes_with_same_value<T: ShieldedPoolTester>(
9257 dsf: impl DataStoreFactory,
9258 cache: impl TestCache,
9259) {
9260 let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
9261
9262 let value = Zatoshis::const_from_u64(60000);
9264 let h = st
9265 .add_notes_checking_balance([[value, value]])
9266 .block_height()
9267 .unwrap();
9268
9269 let account = st.test_account().cloned().unwrap();
9271 let total_value = (value + value).unwrap();
9272 assert_eq!(
9273 st.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
9274 total_value
9275 );
9276
9277 let target_height = (h + 1).into();
9278
9279 let unspent_notes = T::select_unspent_notes(&st, account.id(), target_height, &[]).unwrap();
9281 assert_eq!(unspent_notes.len(), 2);
9282 for note in unspent_notes {
9283 assert_eq!(T::note_value(note.note()), value);
9284 }
9285
9286 let spendable_notes = T::select_spendable_notes(
9288 &st,
9289 account.id(),
9290 TargetValue::AllFunds(MaxSpendMode::MaxSpendable),
9291 target_height,
9292 ConfirmationsPolicy::MIN,
9293 &[],
9294 )
9295 .unwrap();
9296 assert_eq!(spendable_notes.len(), 2);
9297 for note in spendable_notes {
9298 assert_eq!(T::note_value(note.note()), value);
9299 }
9300}
9301
9302#[cfg(feature = "pczt")]
9303fn build_transparent_coinbase_tx(
9304 network: &LocalNetwork,
9305 target_height: TargetHeight,
9306 value: Zatoshis,
9307 recipient: TransparentAddress,
9308 miner_data: Option<PushValue>,
9309) -> zcash_primitives::transaction::builder::BuildResult {
9310 let build_config = BuildConfig::Coinbase { miner_data };
9311 let mut builder = Builder::new(*network, BlockHeight::from(target_height), build_config);
9312
9313 builder.add_transparent_output(&recipient, value).unwrap();
9315
9316 builder
9318 .build(
9319 &TransparentSigningSet::new(),
9321 &[],
9323 &[],
9325 UnwrapErr(SysRng),
9326 &LocalTxProver::bundled(),
9327 &LocalTxProver::bundled(),
9328 &StandardFeeRule::Zip317,
9330 )
9331 .unwrap()
9332}
9333
9334#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
9335pub fn immature_coinbase_outputs_are_excluded_from_note_selection<T: ShieldedPoolTester>(
9337 dsf: impl DataStoreFactory,
9338 cache: impl TestCache,
9339) {
9340 let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
9341
9342 let (t_addr, _) = st.get_account().usk().default_transparent_address();
9344
9345 let coinbase_value = Zatoshis::const_from_u64(50000);
9346
9347 let coinbase_height = st.sapling_activation_height();
9349
9350 let coinbase_build_result = build_transparent_coinbase_tx(
9352 st.network(),
9353 TargetHeight::from(coinbase_height),
9354 coinbase_value,
9355 t_addr,
9356 None,
9357 );
9358 let coinbase_tx = coinbase_build_result.transaction();
9359 let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
9360 st.scan_cached_blocks(h, 1);
9361
9362 let params = *st.network();
9363 decrypt_and_store_transaction(¶ms, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
9364
9365 for i in 1..=99 {
9366 let latest_block_height = st.add_empty_blocks(1);
9367
9368 let spendable_utxos = st
9370 .wallet()
9371 .get_spendable_transparent_outputs(
9372 &t_addr,
9373 TargetHeight::from(h + i),
9374 ConfirmationsPolicy::default(),
9375 CoinbaseFilter::AllTransparentOutputs,
9376 LockFilter::Policy(&LockedInputPolicy::Exclude),
9377 )
9378 .unwrap();
9379 let confirmations = latest_block_height - h;
9380 assert!(
9381 spendable_utxos.is_empty(),
9382 "{i}: Immature coinbase output is spendable at blockheight {latest_block_height} \
9383 with {confirmations} confirmations \
9384 (should only be spendable at 100):\n \
9385 {spendable_utxos:#?}"
9386 );
9387 }
9388
9389 let latest_height = st.add_empty_blocks(1);
9391 let confirmations = latest_height - h;
9392 let target_height = TargetHeight::from(latest_height + 1);
9393 let spendable_utxos = st
9394 .wallet()
9395 .get_spendable_transparent_outputs(
9396 &t_addr,
9397 target_height,
9398 ConfirmationsPolicy::default(),
9399 CoinbaseFilter::AllTransparentOutputs,
9400 LockFilter::Policy(&LockedInputPolicy::Exclude),
9401 )
9402 .unwrap();
9403 assert!(
9404 !spendable_utxos.is_empty(),
9405 "Coinbase output should be spendable at blockheight {latest_height} \
9406 with {confirmations} confirmations since the coinbase tx was mined (at {h})\n \
9407 target_height {target_height:?} - coinbase_tx.mined_height {h} = {}",
9408 u32::from(target_height) - u32::from(h)
9409 );
9410
9411 let account = st.get_account().id();
9413 let _proposal = st
9414 .propose_shielding(
9415 &GreedyInputSelector::new(),
9416 &single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL),
9417 Zatoshis::from_u64(10000).unwrap(),
9418 &[t_addr],
9419 account,
9420 ConfirmationsPolicy::default(),
9421 CoinbaseFilter::AllTransparentOutputs,
9422 )
9423 .unwrap();
9424}
9425
9426#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
9427pub fn coinbase_only_filtering<T: ShieldedPoolTester, Dsf>(ds_factory: Dsf, cache: impl TestCache)
9432where
9433 Dsf: DataStoreFactory,
9434 <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
9435{
9436 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
9437 let (t_addr, _) = st.get_account().usk().default_transparent_address();
9438 let account = st.get_account().id();
9439
9440 let coinbase_value = Zatoshis::const_from_u64(50000);
9442 let coinbase_height = st.sapling_activation_height();
9443 let coinbase_build_result = build_transparent_coinbase_tx(
9444 st.network(),
9445 TargetHeight::from(coinbase_height),
9446 coinbase_value,
9447 t_addr,
9448 None,
9449 );
9450 let coinbase_tx = coinbase_build_result.transaction();
9451 let coinbase_outpoint = OutPoint::new(coinbase_tx.txid().into(), 0);
9453 let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
9454 st.scan_cached_blocks(h, 1);
9455 let params = *st.network();
9456 decrypt_and_store_transaction(¶ms, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
9457
9458 let non_coinbase_value = Zatoshis::const_from_u64(60000);
9462 let non_coinbase_outpoint = OutPoint::fake();
9463 let utxo = WalletTransparentOutput::from_parts(
9464 non_coinbase_outpoint.clone(),
9465 TxOut::new(non_coinbase_value, t_addr.script().into()),
9466 Some(h),
9467 Some(account),
9468 Some(TransparentKeyScope::EXTERNAL),
9469 None,
9470 )
9471 .unwrap();
9472 st.wallet_mut()
9473 .put_received_transparent_utxo(&utxo)
9474 .unwrap();
9475
9476 st.add_empty_blocks(100);
9478 let target_height = TargetHeight::from(h + 101);
9479
9480 let all_utxos = st
9482 .wallet()
9483 .get_spendable_transparent_outputs(
9484 &t_addr,
9485 target_height,
9486 ConfirmationsPolicy::default(),
9487 CoinbaseFilter::AllTransparentOutputs,
9488 LockFilter::Policy(&LockedInputPolicy::Exclude),
9489 )
9490 .unwrap();
9491 assert_eq!(
9492 all_utxos.len(),
9493 2,
9494 "Expected both coinbase and non-coinbase UTXOs with CoinbaseFilter::AllTransparentOutputs"
9495 );
9496 let all_utxos_value = all_utxos
9497 .iter()
9498 .map(|utxo| utxo.value().into_u64())
9499 .sum::<u64>();
9500 assert_eq!(
9501 all_utxos_value,
9502 coinbase_value.into_u64() + non_coinbase_value.into_u64(),
9503 "Unexpected total UTXO value when querying for all transparent transactions"
9504 );
9505
9506 let coinbase_utxos = st
9508 .wallet()
9509 .get_spendable_transparent_outputs(
9510 &t_addr,
9511 target_height,
9512 ConfirmationsPolicy::default(),
9513 CoinbaseFilter::CoinbaseOnly,
9514 LockFilter::Policy(&LockedInputPolicy::Exclude),
9515 )
9516 .unwrap();
9517 assert_eq!(
9518 coinbase_utxos.len(),
9519 1,
9520 "Expected only the coinbase UTXO with CoinbaseFilter::CoinbaseOnly"
9521 );
9522 assert_eq!(coinbase_utxos[0].value(), coinbase_value);
9523 assert_eq!(coinbase_utxos[0].outpoint(), &coinbase_outpoint);
9524
9525 let non_coinbase_utxos = st
9529 .wallet()
9530 .get_spendable_transparent_outputs(
9531 &t_addr,
9532 target_height,
9533 ConfirmationsPolicy::default(),
9534 CoinbaseFilter::NonCoinbaseOnly,
9535 LockFilter::Policy(&LockedInputPolicy::Exclude),
9536 )
9537 .unwrap();
9538 assert_eq!(
9539 non_coinbase_utxos.len(),
9540 1,
9541 "Expected only the non-coinbase UTXO with CoinbaseFilter::NonCoinbaseOnly"
9542 );
9543 assert_eq!(non_coinbase_utxos[0].value(), non_coinbase_value);
9544 assert_eq!(non_coinbase_utxos[0].outpoint(), &non_coinbase_outpoint);
9545
9546 let proposal = st
9548 .propose_shielding(
9549 &GreedyInputSelector::new(),
9550 &single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL),
9551 Zatoshis::from_u64(10000).unwrap(),
9552 &[t_addr],
9553 account,
9554 ConfirmationsPolicy::default(),
9555 CoinbaseFilter::CoinbaseOnly,
9556 )
9557 .unwrap();
9558 let coinbase_inputs = proposal.steps().first().transparent_inputs();
9559 assert_eq!(
9560 coinbase_inputs.len(),
9561 1,
9562 "CoinbaseOnly proposal should contain exactly one transparent input"
9563 );
9564 assert_eq!(coinbase_inputs[0].value(), coinbase_value);
9565 assert_eq!(coinbase_inputs[0].outpoint(), &coinbase_outpoint);
9566
9567 let proposal_non_coinbase = st
9569 .propose_shielding(
9570 &GreedyInputSelector::new(),
9571 &single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL),
9572 Zatoshis::from_u64(10000).unwrap(),
9573 &[t_addr],
9574 account,
9575 ConfirmationsPolicy::default(),
9576 CoinbaseFilter::NonCoinbaseOnly,
9577 )
9578 .unwrap();
9579 let non_coinbase_inputs = proposal_non_coinbase.steps().first().transparent_inputs();
9580 assert_eq!(
9581 non_coinbase_inputs.len(),
9582 1,
9583 "NonCoinbaseOnly proposal should contain exactly one transparent input"
9584 );
9585 assert_eq!(non_coinbase_inputs[0].value(), non_coinbase_value);
9586 assert_eq!(non_coinbase_inputs[0].outpoint(), &non_coinbase_outpoint);
9587
9588 let proposal_all = st
9590 .propose_shielding(
9591 &GreedyInputSelector::new(),
9592 &single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL),
9593 Zatoshis::from_u64(10000).unwrap(),
9594 &[t_addr],
9595 account,
9596 ConfirmationsPolicy::default(),
9597 CoinbaseFilter::AllTransparentOutputs,
9598 )
9599 .unwrap();
9600 let all_inputs = proposal_all.steps().first().transparent_inputs();
9601 assert_eq!(
9602 all_inputs.len(),
9603 2,
9604 "All proposal should contain both transparent inputs"
9605 );
9606 let all_outpoints = all_inputs
9608 .iter()
9609 .map(|input| input.outpoint().clone())
9610 .collect::<BTreeSet<_>>();
9611 assert_eq!(
9612 all_outpoints,
9613 BTreeSet::from([coinbase_outpoint, non_coinbase_outpoint]),
9614 "All proposal should contain both the coinbase and non-coinbase outpoints"
9615 );
9616}
9617
9618#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
9622pub fn propose_shielding_coinbase_succeeds<T: ShieldedPoolTester, Dsf>(
9623 ds_factory: Dsf,
9624 cache: impl TestCache,
9625) where
9626 Dsf: DataStoreFactory,
9627 <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
9628{
9629 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
9630 let (t_addr, _) = st.get_account().usk().default_transparent_address();
9631 let coinbase_value = Zatoshis::const_from_u64(50000);
9632 let coinbase_build_result = build_transparent_coinbase_tx(
9633 st.network(),
9634 TargetHeight::from(st.sapling_activation_height()),
9635 coinbase_value,
9636 t_addr,
9637 None,
9638 );
9639 let coinbase_tx = coinbase_build_result.transaction();
9640 let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
9641 st.scan_cached_blocks(h, 1);
9642 let params = *st.network();
9643 decrypt_and_store_transaction(¶ms, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
9644 st.add_empty_blocks(100);
9646
9647 let to_extsk = T::sk(&[0xab; 32]);
9650 let to_address = T::sk_default_address(&to_extsk).to_zcash_address(st.network());
9651
9652 let proposal = st
9653 .propose_shielding_coinbase(
9654 &GreedyInputSelector::new(),
9655 &StandardFeeRule::Zip317,
9656 Zatoshis::ZERO,
9657 &[t_addr],
9658 to_address.clone(),
9659 None,
9660 None,
9661 )
9662 .expect("propose_shielding_coinbase with a shielded destination should succeed");
9663
9664 let step = proposal.steps().first();
9665 assert_eq!(
9666 step.transparent_inputs().len(),
9667 1,
9668 "Expected exactly one coinbase transparent input"
9669 );
9670 let payments = step.transaction_request().payments();
9671 assert_eq!(
9672 payments.len(),
9673 1,
9674 "Expected exactly one payment in proposal"
9675 );
9676 let (idx, payment) = payments.iter().next().unwrap();
9677 assert_eq!(*idx, 0);
9678 assert_eq!(payment.recipient_address(), &to_address);
9679 assert_eq!(
9680 step.balance().proposed_change().len(),
9681 0,
9682 "Coinbase shielding must produce no change"
9683 );
9684
9685 let fee = step.balance().fee_required();
9686 let payment_amount = payment.amount().expect("payment must have an amount");
9687 assert_eq!(
9688 (payment_amount + fee).unwrap(),
9689 coinbase_value,
9690 "payment_amount + fee must equal coinbase input value"
9691 );
9692}
9693
9694#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
9701pub fn proposal_without_confirmations_policy_builds<T: ShieldedPoolTester, Dsf>(
9702 ds_factory: Dsf,
9703 cache: impl TestCache,
9704) where
9705 Dsf: DataStoreFactory,
9706 <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
9707{
9708 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
9709 let (t_addr, _) = st.get_account().usk().default_transparent_address();
9710 let coinbase_value = Zatoshis::const_from_u64(50000);
9711 let coinbase_build_result = build_transparent_coinbase_tx(
9712 st.network(),
9713 TargetHeight::from(st.sapling_activation_height()),
9714 coinbase_value,
9715 t_addr,
9716 None,
9717 );
9718 let coinbase_tx = coinbase_build_result.transaction();
9719 let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
9720 st.scan_cached_blocks(h, 1);
9721 let params = *st.network();
9722 decrypt_and_store_transaction(¶ms, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
9723 st.add_empty_blocks(100);
9725
9726 let to_extsk = T::sk(&[0xab; 32]);
9727 let to_address = T::sk_default_address(&to_extsk).to_zcash_address(st.network());
9728
9729 let proposal = st
9730 .propose_shielding_coinbase(
9731 &GreedyInputSelector::new(),
9732 &StandardFeeRule::Zip317,
9733 Zatoshis::ZERO,
9734 &[t_addr],
9735 to_address,
9736 None,
9737 None,
9738 )
9739 .expect("coinbase shielding proposal should succeed");
9740
9741 let selected_anchor = proposal
9743 .steps()
9744 .first()
9745 .anchor_height()
9746 .expect("a shielding step must preserve its selected checkpoint");
9747
9748 let proto = crate::proto::proposal::Proposal::from_standard_proposal(&proposal);
9749 assert_eq!(
9750 proto.steps[0].anchor_height,
9751 u32::from(selected_anchor),
9752 "a shielding step must serialize its selected checkpoint",
9753 );
9754
9755 let mut zero_anchor = proto.clone();
9760 zero_anchor.steps[0].anchor_height = 0;
9761 assert_matches!(
9762 zero_anchor.try_into_standard_proposal(¶ms, st.wallet()),
9763 Err(crate::proto::ProposalDecodingError::MissingShieldedAnchor)
9764 );
9765
9766 let mut without_policy = proto;
9769 without_policy.confirmations_policy = None;
9770 let decoded = without_policy
9771 .try_into_standard_proposal(¶ms, st.wallet())
9772 .expect("a proposal without a confirmations policy must decode");
9773 assert_eq!(
9774 decoded.confirmations_policy(),
9775 ConfirmationsPolicy::default(),
9776 "a missing confirmations policy must decode as the default",
9777 );
9778 assert_eq!(
9779 decoded.steps().first().anchor_height(),
9780 Some(selected_anchor),
9781 "decoding must preserve the serialized anchor",
9782 );
9783 assert_eq!(
9784 decoded.min_target_height(),
9785 proposal.min_target_height(),
9786 "decoding must preserve the target height the proposal's fee was computed at",
9787 );
9788
9789 let usk = st.get_account().usk().clone();
9790 st.create_proposed_transactions::<Infallible, _, Infallible, _>(
9791 &usk,
9792 OvkPolicy::Sender,
9793 &decoded,
9794 )
9795 .expect("a proposal that carries its selected anchor must build");
9796}
9797
9798#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
9801pub fn propose_shielding_coinbase_transparent_recipient_rejected<T: ShieldedPoolTester, Dsf>(
9802 ds_factory: Dsf,
9803 cache: impl TestCache,
9804) where
9805 Dsf: DataStoreFactory,
9806 <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
9807{
9808 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
9809 let (t_addr, _) = st.get_account().usk().default_transparent_address();
9810 let coinbase_value = Zatoshis::const_from_u64(50000);
9811 let coinbase_build_result = build_transparent_coinbase_tx(
9812 st.network(),
9813 TargetHeight::from(st.sapling_activation_height()),
9814 coinbase_value,
9815 t_addr,
9816 None,
9817 );
9818 let coinbase_tx = coinbase_build_result.transaction();
9819 let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
9820 st.scan_cached_blocks(h, 1);
9821 let params = *st.network();
9822 decrypt_and_store_transaction(¶ms, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
9823 st.add_empty_blocks(100);
9824
9825 let bad_to_address = Address::Transparent(TransparentAddress::PublicKeyHash([7; 20]))
9826 .to_zcash_address(st.network());
9827
9828 let result = st.propose_shielding_coinbase(
9829 &GreedyInputSelector::new(),
9830 &StandardFeeRule::Zip317,
9831 Zatoshis::ZERO,
9832 &[t_addr],
9833 bad_to_address,
9834 None,
9835 None,
9836 );
9837
9838 assert_matches!(
9839 result,
9840 Err(Error::Proposal(
9841 ProposalError::ShieldingRequiresShieldedRecipient
9842 ))
9843 );
9844}
9845
9846#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
9849pub fn propose_shielding_coinbase_with_memo_succeeds<T: ShieldedPoolTester, Dsf>(
9850 ds_factory: Dsf,
9851 cache: impl TestCache,
9852) where
9853 Dsf: DataStoreFactory,
9854 <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
9855{
9856 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
9857 let (t_addr, _) = st.get_account().usk().default_transparent_address();
9858 let coinbase_value = Zatoshis::const_from_u64(50000);
9859 let coinbase_build_result = build_transparent_coinbase_tx(
9860 st.network(),
9861 TargetHeight::from(st.sapling_activation_height()),
9862 coinbase_value,
9863 t_addr,
9864 None,
9865 );
9866 let coinbase_tx = coinbase_build_result.transaction();
9867 let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
9868 st.scan_cached_blocks(h, 1);
9869 let params = *st.network();
9870 decrypt_and_store_transaction(¶ms, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
9871 st.add_empty_blocks(100);
9872
9873 let to_extsk = T::sk(&[0xcd; 32]);
9874 let to_address = T::sk_default_address(&to_extsk).to_zcash_address(st.network());
9875
9876 let memo_text = "shielding to external wallet";
9877 let memo_bytes = MemoBytes::from(memo_text.parse::<Memo>().unwrap());
9878
9879 let proposal = st
9880 .propose_shielding_coinbase(
9881 &GreedyInputSelector::new(),
9882 &StandardFeeRule::Zip317,
9883 Zatoshis::ZERO,
9884 &[t_addr],
9885 to_address,
9886 Some(memo_bytes.clone()),
9887 None,
9888 )
9889 .expect("propose_shielding_coinbase with memo should succeed");
9890
9891 let payments = proposal.steps().first().transaction_request().payments();
9892 let (_, payment) = payments.iter().next().unwrap();
9893 assert_eq!(payment.memo(), Some(&memo_bytes));
9894}
9895
9896#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
9899pub fn propose_shielding_coinbase_with_limit_truncates_inputs<T: ShieldedPoolTester, Dsf>(
9900 ds_factory: Dsf,
9901 cache: impl TestCache,
9902) where
9903 Dsf: DataStoreFactory,
9904 <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
9905{
9906 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
9907 let (t_addr, _) = st.get_account().usk().default_transparent_address();
9908
9909 let values = [
9912 Zatoshis::const_from_u64(30000),
9913 Zatoshis::const_from_u64(70000),
9914 Zatoshis::const_from_u64(50000),
9915 ];
9916 let mut first_h = None;
9917 for v in values {
9918 let coinbase_height = if let Some(h) = first_h {
9919 h + values.len() as u32 } else {
9921 st.sapling_activation_height()
9922 };
9923 let build = build_transparent_coinbase_tx(
9924 st.network(),
9925 TargetHeight::from(coinbase_height),
9926 v,
9927 t_addr,
9928 None,
9929 );
9930 let tx = build.transaction();
9931 let (h, _) = st.generate_next_block_from_tx(0, tx);
9932 st.scan_cached_blocks(h, 1);
9933 let params = *st.network();
9934 decrypt_and_store_transaction(¶ms, st.wallet_mut(), tx, Some(h)).unwrap();
9935 if first_h.is_none() {
9936 first_h = Some(h);
9937 }
9938 }
9939 st.add_empty_blocks(100);
9941
9942 let to_extsk = T::sk(&[0x55; 32]);
9943 let to_address = T::sk_default_address(&to_extsk).to_zcash_address(st.network());
9944
9945 let proposal = st
9946 .propose_shielding_coinbase(
9947 &GreedyInputSelector::new(),
9948 &StandardFeeRule::Zip317,
9949 Zatoshis::ZERO,
9950 &[t_addr],
9951 to_address,
9952 None,
9953 Some(2),
9954 )
9955 .expect("propose_shielding_coinbase with limit=Some(2) should succeed");
9956
9957 let inputs = proposal.steps().first().transparent_inputs();
9958 assert_eq!(
9959 inputs.len(),
9960 2,
9961 "limit=Some(2) should select exactly 2 inputs"
9962 );
9963
9964 let mut selected_values: Vec<u64> = inputs.iter().map(|i| i.value().into_u64()).collect();
9966 selected_values.sort_unstable_by(|a, b| b.cmp(a));
9967 assert_eq!(selected_values, vec![70000, 50000]);
9968}
9969
9970#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
9975pub fn propose_shielding_coinbase_with_zero_limit_insufficient_funds<T: ShieldedPoolTester, Dsf>(
9976 ds_factory: Dsf,
9977 cache: impl TestCache,
9978) where
9979 Dsf: DataStoreFactory,
9980 <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
9981{
9982 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
9983 let (t_addr, _) = st.get_account().usk().default_transparent_address();
9984 let coinbase_value = Zatoshis::const_from_u64(50000);
9985 let coinbase_build_result = build_transparent_coinbase_tx(
9986 st.network(),
9987 TargetHeight::from(st.sapling_activation_height()),
9988 coinbase_value,
9989 t_addr,
9990 None,
9991 );
9992 let coinbase_tx = coinbase_build_result.transaction();
9993 let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
9994 st.scan_cached_blocks(h, 1);
9995 let params = *st.network();
9996 decrypt_and_store_transaction(¶ms, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
9997 st.add_empty_blocks(100);
9998
9999 let to_extsk = T::sk(&[0x66; 32]);
10000 let to_address = T::sk_default_address(&to_extsk).to_zcash_address(st.network());
10001
10002 let shielding_threshold = Zatoshis::const_from_u64(10000);
10003 let result = st.propose_shielding_coinbase(
10004 &GreedyInputSelector::new(),
10005 &StandardFeeRule::Zip317,
10006 shielding_threshold,
10007 &[t_addr],
10008 to_address,
10009 None,
10010 Some(0),
10011 );
10012
10013 assert_matches!(result, Err(Error::InsufficientFunds { .. }));
10017}
10018
10019#[cfg(all(feature = "pczt", feature = "transparent-inputs"))]
10033pub fn propose_and_build_shielding_coinbase_succeeds<T: ShieldedPoolTester, Dsf>(
10034 ds_factory: Dsf,
10035 cache: impl TestCache,
10036) where
10037 Dsf: DataStoreFactory,
10038 <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
10039{
10040 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
10041 let account = st.get_account();
10042 let (t_addr, _) = account.usk().default_transparent_address();
10043 let coinbase_value = Zatoshis::const_from_u64(50000);
10044 let coinbase_build_result = build_transparent_coinbase_tx(
10045 st.network(),
10046 TargetHeight::from(st.sapling_activation_height()),
10047 coinbase_value,
10048 t_addr,
10049 None,
10050 );
10051 let coinbase_tx = coinbase_build_result.transaction();
10052 let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
10053 st.scan_cached_blocks(h, 1);
10054 let params = *st.network();
10055 decrypt_and_store_transaction(¶ms, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
10056 st.add_empty_blocks(COINBASE_MATURITY_BLOCKS as usize);
10058
10059 let to_extsk = T::sk(&[0xcd; 32]);
10061 let to_address = T::sk_default_address(&to_extsk).to_zcash_address(st.network());
10062
10063 let proposal = st
10064 .propose_shielding_coinbase(
10065 &GreedyInputSelector::new(),
10066 &StandardFeeRule::Zip317,
10067 Zatoshis::ZERO,
10068 &[t_addr],
10069 to_address,
10070 None,
10071 None,
10072 )
10073 .expect("propose_shielding_coinbase should succeed");
10074
10075 let build_result = st.create_proposed_transactions::<Infallible, _, Infallible, _>(
10080 account.usk(),
10081 OvkPolicy::Sender,
10082 &proposal,
10083 );
10084 assert_matches!(
10085 &build_result,
10086 Ok(txids) if txids.len() == 1,
10087 "create_proposed_transactions must succeed for proposal {:?}",
10088 proposal,
10089 );
10090}
10091
10092#[cfg(all(feature = "orchard", feature = "pczt", feature = "transparent-inputs"))]
10096pub fn shielding_coinbase_to_orchard_receiver_delivers_via_ironwood<Dsf>(
10097 ds_factory: Dsf,
10098 cache: impl TestCache,
10099) where
10100 Dsf: DataStoreFactory,
10101 <<Dsf as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
10102{
10103 let ironwood_active_network = {
10105 let activation = BlockHeight::from_u32(100_000);
10106 LocalNetwork {
10107 nu6: Some(activation),
10108 nu6_1: Some(activation),
10109 nu6_2: Some(activation),
10110 nu6_3: Some(activation),
10111 ..TestBuilder::<(), ()>::DEFAULT_NETWORK
10112 }
10113 };
10114
10115 let mut st = TestDsl::from(
10116 TestBuilder::new()
10117 .with_network(ironwood_active_network)
10118 .with_data_store_factory(ds_factory)
10119 .with_block_cache(cache)
10120 .with_account_from_sapling_activation(BlockHash([0; 32])),
10121 )
10122 .build::<OrchardPoolTester>();
10123 let account = st.get_account();
10124 let (t_addr, _) = account.usk().default_transparent_address();
10125 let coinbase_value = Zatoshis::const_from_u64(100000);
10126 let coinbase_build_result = build_transparent_coinbase_tx(
10127 st.network(),
10128 TargetHeight::from(st.sapling_activation_height()),
10129 coinbase_value,
10130 t_addr,
10131 None,
10132 );
10133 let coinbase_tx = coinbase_build_result.transaction();
10134 let (h, _) = st.generate_next_block_from_tx(0, coinbase_tx);
10135 st.scan_cached_blocks(h, 1);
10136 let params = *st.network();
10137 decrypt_and_store_transaction(¶ms, st.wallet_mut(), coinbase_tx, Some(h)).unwrap();
10138 st.add_empty_blocks(COINBASE_MATURITY_BLOCKS as usize);
10140
10141 let to_extsk = OrchardPoolTester::sk(&[0xcd; 32]);
10143 let to_address =
10144 OrchardPoolTester::sk_default_address(&to_extsk).to_zcash_address(st.network());
10145
10146 let proposal = st
10147 .propose_shielding_coinbase(
10148 &GreedyInputSelector::new(),
10149 &StandardFeeRule::Zip317,
10150 Zatoshis::ZERO,
10151 &[t_addr],
10152 to_address,
10153 None,
10154 None,
10155 )
10156 .expect("propose_shielding_coinbase to an Orchard receiver should succeed post-NU6.3");
10157
10158 assert_eq!(
10162 proposal.steps().head.payment_pools().get(&0),
10163 Some(&PoolType::IRONWOOD),
10164 );
10165
10166 let build_result = st.create_proposed_transactions::<Infallible, _, Infallible, _>(
10167 account.usk(),
10168 OvkPolicy::Sender,
10169 &proposal,
10170 );
10171 assert_matches!(
10172 &build_result,
10173 Ok(txids) if txids.len() == 1,
10174 "create_proposed_transactions must succeed for proposal {:?}",
10175 proposal,
10176 );
10177 let sent_txid = build_result.unwrap().head;
10178
10179 assert!(
10184 st.wallet()
10185 .transaction_data_requests()
10186 .unwrap()
10187 .contains(&TransactionDataRequest::GetStatus(sent_txid))
10188 );
10189
10190 let (mined_height, _) = st.generate_next_block_including(sent_txid);
10191 st.scan_cached_blocks(mined_height, 1);
10192 assert_eq!(
10193 st.get_tx_from_history(sent_txid)
10194 .unwrap()
10195 .expect("sent transaction is in history")
10196 .mined_height(),
10197 None,
10198 "compact scanning cannot detect an external shielding transaction",
10199 );
10200
10201 st.wallet_mut()
10202 .set_transaction_status(sent_txid, TransactionStatus::Mined(mined_height))
10203 .unwrap();
10204 assert_eq!(
10205 st.get_tx_from_history(sent_txid)
10206 .unwrap()
10207 .expect("sent transaction is in history")
10208 .mined_height(),
10209 Some(mined_height),
10210 );
10211 assert!(
10212 !st.wallet()
10213 .transaction_data_requests()
10214 .unwrap()
10215 .contains(&TransactionDataRequest::GetStatus(sent_txid)),
10216 "status intent is dormant while the transaction is mined",
10217 );
10218
10219 st.truncate_to_height(mined_height - 1);
10220 assert_eq!(
10221 st.get_tx_from_history(sent_txid)
10222 .unwrap()
10223 .expect("sent transaction is retained across the rewind")
10224 .mined_height(),
10225 None,
10226 );
10227 assert!(
10228 st.wallet()
10229 .transaction_data_requests()
10230 .unwrap()
10231 .contains(&TransactionDataRequest::GetStatus(sent_txid)),
10232 "rewinding the mined block reactivates the durable status intent",
10233 );
10234}
10235
10236#[cfg(feature = "orchard")]
10242pub fn propose_v5_payment_to_orchard_receiver_is_rejected<Dsf>(
10243 ds_factory: Dsf,
10244 cache: impl TestCache,
10245) where
10246 Dsf: DataStoreFactory,
10247{
10248 let ironwood_active_network = {
10250 let activation = BlockHeight::from_u32(100_000);
10251 LocalNetwork {
10252 nu6: Some(activation),
10253 nu6_1: Some(activation),
10254 nu6_2: Some(activation),
10255 nu6_3: Some(activation),
10256 ..TestBuilder::<(), ()>::DEFAULT_NETWORK
10257 }
10258 };
10259
10260 let mut st = TestDsl::from(
10261 TestBuilder::new()
10262 .with_network(ironwood_active_network)
10263 .with_data_store_factory(ds_factory)
10264 .with_block_cache(cache)
10265 .with_account_from_sapling_activation(BlockHash([0; 32])),
10266 )
10267 .build::<OrchardPoolTester>();
10268
10269 st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60_000));
10271
10272 let to_extsk = OrchardPoolTester::sk(&[0xf5; 32]);
10274 let to = OrchardPoolTester::sk_default_address(&to_extsk);
10275 let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
10276 to.to_zcash_address(st.network()),
10277 Zatoshis::const_from_u64(10_000),
10278 )])
10279 .unwrap();
10280
10281 let change_strategy =
10282 single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
10283 let input_selector = GreedyInputSelector::new();
10284
10285 let account = st.get_account();
10286 let network = *st.network();
10287 let result = propose_transfer::<_, _, _, _, Infallible>(
10288 st.wallet_mut(),
10289 &network,
10290 account.id(),
10291 &input_selector,
10292 &change_strategy,
10293 request,
10294 ConfirmationsPolicy::MIN,
10295 &SpendPolicy::default(),
10296 None,
10297 Some(TxVersion::V5),
10298 );
10299
10300 assert_matches!(
10301 result,
10302 Err(Error::Proposal(
10303 ProposalError::OrchardReceiverRequiresIronwood(TxVersion::V5)
10304 ))
10305 );
10306}
10307
10308#[cfg(all(feature = "orchard", feature = "pczt"))]
10313pub fn create_pczt_supports_ironwood_output<Dsf>(ds_factory: Dsf, cache: impl TestCache)
10314where
10315 Dsf: DataStoreFactory,
10316 <Dsf as DataStoreFactory>::AccountId: serde::Serialize + serde::de::DeserializeOwned,
10317{
10318 let ironwood_active_network = {
10320 let activation = BlockHeight::from_u32(100_000);
10321 LocalNetwork {
10322 nu6: Some(activation),
10323 nu6_1: Some(activation),
10324 nu6_2: Some(activation),
10325 nu6_3: Some(activation),
10326 ..TestBuilder::<(), ()>::DEFAULT_NETWORK
10327 }
10328 };
10329
10330 let mut st = TestDsl::from(
10331 TestBuilder::new()
10332 .with_network(ironwood_active_network)
10333 .with_data_store_factory(ds_factory)
10334 .with_block_cache(cache)
10335 .with_account_from_sapling_activation(BlockHash([0; 32])),
10336 )
10337 .build::<OrchardPoolTester>();
10338
10339 st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60_000));
10341
10342 let to_extsk = OrchardPoolTester::sk(&[0xf5; 32]);
10345 let to = OrchardPoolTester::sk_default_address(&to_extsk);
10346 let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
10347 to.to_zcash_address(st.network()),
10348 Zatoshis::const_from_u64(10_000),
10349 )])
10350 .unwrap();
10351
10352 let change_strategy =
10353 single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
10354 let input_selector = GreedyInputSelector::new();
10355
10356 let account_id = st.get_account().id();
10357 let proposal = st
10358 .propose_transfer(
10359 account_id,
10360 &input_selector,
10361 &change_strategy,
10362 request,
10363 ConfirmationsPolicy::MIN,
10364 )
10365 .expect("proposal construction succeeds; the Orchard-receiver payment routes to Ironwood");
10366
10367 assert_eq!(
10369 proposal.steps().head.payment_pools().get(&0),
10370 Some(&PoolType::IRONWOOD),
10371 );
10372
10373 let pczt = st
10374 .create_pczt_from_proposal::<Infallible, _, Infallible>(
10375 account_id,
10376 OvkPolicy::Sender,
10377 &proposal,
10378 None,
10379 )
10380 .expect("an Ironwood-routed payment builds as a version 6 PCZT");
10381
10382 assert_eq!(
10384 *pczt.global().tx_version(),
10385 zcash_protocol::constants::V6_TX_VERSION,
10386 );
10387 assert!(
10388 !pczt.ironwood().actions().is_empty(),
10389 "the PCZT carries an Ironwood bundle for the Ironwood-routed payment",
10390 );
10391
10392 assert!(
10396 pczt.ironwood()
10397 .actions()
10398 .iter()
10399 .any(|action| !action.output().proprietary().is_empty()),
10400 "the Ironwood output carries recipient metadata",
10401 );
10402
10403 #[derive(Clone, Debug, PartialEq, Eq)]
10404 struct SpendState {
10405 has_fvk: bool,
10406 has_signature: bool,
10407 has_alpha: bool,
10408 has_derivation: bool,
10409 value: Option<u64>,
10410 }
10411
10412 fn spend_states(pczt: pczt::Pczt) -> (Vec<SpendState>, Vec<SpendState>) {
10413 fn for_bundle(bundle: &orchard::pczt::Bundle) -> Vec<SpendState> {
10414 bundle
10415 .actions()
10416 .iter()
10417 .map(|action| SpendState {
10418 has_fvk: action.spend().fvk().is_some(),
10419 has_signature: action.spend().spend_auth_sig().is_some(),
10420 has_alpha: action.spend().alpha().is_some(),
10421 has_derivation: action.spend().zip32_derivation().is_some(),
10422 value: action.spend().value().as_ref().map(|value| value.inner()),
10423 })
10424 .collect()
10425 }
10426
10427 let mut orchard = vec![];
10428 let mut ironwood = vec![];
10429 pczt::roles::verifier::Verifier::new(pczt)
10430 .with_orchard::<Infallible, _>(|bundle| {
10431 orchard = for_bundle(bundle);
10432 Ok(())
10433 })
10434 .unwrap()
10435 .with_ironwood::<Infallible, _>(|bundle| {
10436 ironwood = for_bundle(bundle);
10437 Ok(())
10438 })
10439 .unwrap();
10440 (orchard, ironwood)
10441 }
10442
10443 let original_sighash = Signer::new(pczt.clone()).unwrap().shielded_sighash();
10444 let original_spend_states = spend_states(pczt.clone());
10445
10446 for state in original_spend_states
10453 .0
10454 .iter()
10455 .chain(original_spend_states.1.iter())
10456 {
10457 assert!(
10458 state.has_signature || state.has_derivation,
10459 "every action must be either pre-signed or identifiable by an external signer \
10460 via ZIP 32 derivation: {state:?}",
10461 );
10462 }
10463 assert!(
10467 original_spend_states
10468 .0
10469 .iter()
10470 .any(|state| state.value == Some(0) && !state.has_signature),
10471 "expected at least one unsigned zero-value Orchard spend (the wallet-controlled \
10472 change-pairing dummy)",
10473 );
10474
10475 let original_len = pczt.clone().serialize().unwrap().len();
10476 let signer_view = redact_pczt_for_signer(&pczt, SignerView::Compact);
10477 let signer_view_bytes = signer_view.serialize().unwrap();
10478 assert!(signer_view_bytes.len() < original_len);
10479 let signer_view = pczt::Pczt::parse(&signer_view_bytes).unwrap();
10480 assert_eq!(spend_states(signer_view.clone()), original_spend_states);
10481
10482 assert!(
10485 signer_view
10486 .global()
10487 .proprietary()
10488 .get("zcash_client_backend:proposal_info")
10489 .is_none()
10490 );
10491 assert!(
10492 pczt.global()
10493 .proprietary()
10494 .contains_key("zcash_client_backend:proposal_info")
10495 );
10496
10497 assert!(signer_view.sapling().anchor().is_none());
10500 assert!(signer_view.orchard().anchor().is_none());
10501 assert!(signer_view.ironwood().anchor().is_none());
10502
10503 let assert_redacted_bundle =
10504 |original: &pczt::orchard::Bundle, redacted: &pczt::orchard::Bundle| {
10505 assert_eq!(redacted.actions().len(), original.actions().len());
10506 let mut memo_plaintexts = 0;
10507 for (redacted, original) in redacted.actions().iter().zip(original.actions()) {
10508 assert!(redacted.cv_net().is_none());
10509 assert!(redacted.output().cmx().is_none());
10510 assert_eq!(redacted.spend().nullifier(), original.spend().nullifier());
10511 assert_eq!(redacted.spend().rk(), original.spend().rk());
10512 assert_eq!(
10513 redacted.spend().spend_auth_sig(),
10514 original.spend().spend_auth_sig()
10515 );
10516 assert_eq!(
10517 redacted.output().ephemeral_key(),
10518 original.output().ephemeral_key()
10519 );
10520 assert_eq!(
10521 redacted.output().out_ciphertext(),
10522 original.output().out_ciphertext()
10523 );
10524 assert_eq!(
10525 redacted.output().user_address(),
10526 original.output().user_address()
10527 );
10528 assert!(
10529 redacted
10530 .output()
10531 .proprietary()
10532 .get("zcash_client_backend:output_info")
10533 .is_none()
10534 );
10535 if matches!(
10536 redacted.output().enc_ciphertext(),
10537 pczt::orchard::EncCiphertext::MemoPlaintext(_)
10538 ) {
10539 memo_plaintexts += 1;
10540 }
10541 }
10542 memo_plaintexts
10543 };
10544
10545 let memo_plaintexts = assert_redacted_bundle(pczt.orchard(), signer_view.orchard())
10546 + assert_redacted_bundle(pczt.ironwood(), signer_view.ironwood());
10547 assert!(memo_plaintexts > 0);
10548
10549 let full_view = redact_pczt_for_signer(&pczt, SignerView::Full);
10552 assert_eq!(
10553 Signer::new(full_view.clone()).unwrap().shielded_sighash(),
10554 original_sighash,
10555 );
10556 assert!(full_view.ironwood().actions().iter().all(|action| {
10557 action.spend().witness().is_none() && action.spend().dummy_sk().is_none()
10558 }));
10559 assert_eq!(full_view.ironwood().anchor(), pczt.ironwood().anchor());
10560 assert!(
10561 !full_view
10562 .global()
10563 .proprietary()
10564 .contains_key("zcash_client_backend:proposal_info")
10565 );
10566 for bundle in [full_view.orchard(), full_view.ironwood()] {
10567 assert!(bundle.actions().iter().all(|action| {
10568 !action
10569 .output()
10570 .proprietary()
10571 .contains_key("zcash_client_backend:output_info")
10572 }));
10573 }
10574 assert!(full_view.sapling().outputs().iter().all(|output| {
10575 !output
10576 .proprietary()
10577 .contains_key("zcash_client_backend:output_info")
10578 }));
10579 assert!(full_view.transparent().outputs().iter().all(|output| {
10580 !output
10581 .proprietary()
10582 .contains_key("zcash_client_backend:output_info")
10583 }));
10584
10585 let batch_view = redact_pczt_for_batch_signer(&pczt);
10586 let batch_view_bytes = batch_view.serialize().unwrap();
10587 assert!(batch_view_bytes.len() < signer_view_bytes.len());
10588 let batch_view = pczt::Pczt::parse(&batch_view_bytes).unwrap();
10589 let batch_spend_states = spend_states(batch_view.clone());
10590
10591 let mut preauthorized_actions = 0;
10592 let mut unsigned_zero_value_actions = 0;
10593 for (original_bundle, batch_bundle) in [
10594 (&original_spend_states.0, &batch_spend_states.0),
10595 (&original_spend_states.1, &batch_spend_states.1),
10596 ] {
10597 assert_eq!(batch_bundle.len(), original_bundle.len());
10598 for (original, batch) in original_bundle.iter().zip(batch_bundle) {
10599 assert!(!batch.has_fvk);
10600 assert!(!batch.has_signature);
10601 assert_eq!(
10602 batch.has_alpha,
10603 original.has_alpha && !original.has_signature
10604 );
10605
10606 if original.has_signature {
10607 preauthorized_actions += 1;
10608 } else if original.value == Some(0) && original.has_alpha {
10609 unsigned_zero_value_actions += 1;
10610 }
10611 }
10612 }
10613 assert!(preauthorized_actions > 0);
10614 assert!(unsigned_zero_value_actions > 0);
10615
10616 for compact_view in [&signer_view, &batch_view] {
10619 let mut resolved = (*compact_view).clone();
10620 resolved.resolve_fields().unwrap();
10621 for (resolved_bundle, original_bundle) in [
10622 (resolved.orchard(), pczt.orchard()),
10623 (resolved.ironwood(), pczt.ironwood()),
10624 ] {
10625 for (resolved, original) in resolved_bundle
10626 .actions()
10627 .iter()
10628 .zip(original_bundle.actions())
10629 {
10630 assert_eq!(resolved.cv_net(), original.cv_net());
10631 assert_eq!(resolved.output().cmx(), original.output().cmx());
10632 assert_eq!(
10633 resolved.output().enc_ciphertext(),
10634 original.output().enc_ciphertext()
10635 );
10636 }
10637 }
10638 assert_eq!(
10639 Signer::new((*compact_view).clone())
10640 .unwrap()
10641 .shielded_sighash(),
10642 original_sighash,
10643 );
10644 }
10645
10646 let signable_indices = |states: &[SpendState]| {
10647 states
10648 .iter()
10649 .enumerate()
10650 .filter_map(|(index, state)| (!state.has_signature && state.has_alpha).then_some(index))
10651 .collect::<Vec<_>>()
10652 };
10653 let orchard_signable = signable_indices(&original_spend_states.0);
10654 let ironwood_signable = signable_indices(&original_spend_states.1);
10655 assert!(
10656 orchard_signable
10657 .iter()
10658 .any(|&index| original_spend_states.0[index].value == Some(0))
10659 );
10660
10661 let request = pczt::roles::signer::batch::BatchSignRequest::new(vec![batch_view]);
10665 let request =
10666 pczt::roles::signer::batch::BatchSignRequest::parse(&request.serialize().unwrap()).unwrap();
10667 assert_eq!(request.pczts().len(), 1);
10668 let transported_view = request.pczts()[0].clone();
10669 assert_eq!(spend_states(transported_view.clone()), batch_spend_states);
10670
10671 let usk = st.get_account().usk().clone();
10672 let ask = orchard::keys::SpendAuthorizingKey::from(OrchardPoolTester::usk_to_sk(&usk));
10673 let signed_view = pczt::roles::low_level_signer::Signer::new(transported_view)
10674 .sign_orchard_with::<pczt::roles::low_level_signer::OrchardParseError, _>(|_, bundle, _| {
10675 for &index in &orchard_signable {
10676 bundle.actions_mut()[index]
10677 .sign(original_sighash, &ask, UnwrapErr(SysRng))
10678 .unwrap();
10679 }
10680 Ok(())
10681 })
10682 .unwrap()
10683 .sign_ironwood_with::<pczt::roles::low_level_signer::OrchardParseError, _>(
10684 |_, bundle, _| {
10685 for &index in &ironwood_signable {
10686 bundle.actions_mut()[index]
10687 .sign(original_sighash, &ask, UnwrapErr(SysRng))
10688 .unwrap();
10689 }
10690 Ok(())
10691 },
10692 )
10693 .unwrap()
10694 .finish();
10695
10696 let signatures = pczt::roles::signer::extract_orchard_spend_auth_signatures(&signed_view);
10697 let expected_signature_positions = orchard_signable
10698 .iter()
10699 .copied()
10700 .map(|index| (orchard::ValuePool::Orchard, index))
10701 .chain(
10702 ironwood_signable
10703 .iter()
10704 .copied()
10705 .map(|index| (orchard::ValuePool::Ironwood, index)),
10706 )
10707 .collect::<Vec<_>>();
10708 let signature_positions = signatures
10709 .iter()
10710 .map(|signature| (signature.value_pool(), signature.action_index()))
10711 .collect::<Vec<_>>();
10712 assert_eq!(signature_positions, expected_signature_positions);
10713
10714 let response = pczt::roles::signer::batch::BatchSignResponse::new(vec![signatures]);
10715 let response =
10716 pczt::roles::signer::batch::BatchSignResponse::parse(&response.serialize().unwrap())
10717 .unwrap();
10718 assert_eq!(response.signatures().len(), 1);
10719
10720 let mut signer = Signer::new(pczt.clone()).unwrap();
10721 for signature in &response.signatures()[0] {
10722 signer
10723 .apply_orchard_spend_auth_signature(signature)
10724 .unwrap();
10725 }
10726 let authorized = signer.finish();
10727 assert_eq!(
10728 authorized.global().proprietary(),
10729 pczt.global().proprietary()
10730 );
10731
10732 let authorized_spend_states = spend_states(authorized.clone());
10733 for (original_bundle, authorized_bundle) in [
10734 (&original_spend_states.0, &authorized_spend_states.0),
10735 (&original_spend_states.1, &authorized_spend_states.1),
10736 ] {
10737 for (original, authorized) in original_bundle.iter().zip(authorized_bundle) {
10738 assert_eq!(authorized.has_fvk, original.has_fvk);
10739 assert_eq!(authorized.has_alpha, original.has_alpha);
10740 assert!(authorized.has_signature);
10741 }
10742 }
10743 for (authorized, original) in authorized
10744 .orchard()
10745 .actions()
10746 .iter()
10747 .zip(pczt.orchard().actions())
10748 .chain(
10749 authorized
10750 .ironwood()
10751 .actions()
10752 .iter()
10753 .zip(pczt.ironwood().actions()),
10754 )
10755 {
10756 if original.spend().spend_auth_sig().is_some() {
10757 assert_eq!(
10758 authorized.spend().spend_auth_sig(),
10759 original.spend().spend_auth_sig()
10760 );
10761 }
10762 assert_eq!(
10763 authorized.output().proprietary(),
10764 original.output().proprietary()
10765 );
10766 }
10767
10768 let pczt_branch_id = consensus::BranchId::try_from(*authorized.global().consensus_branch_id())
10775 .expect("the PCZT carries a valid consensus branch ID");
10776 let orchard_pk = zcash_primitives::transaction::builder::cached_orchard_proving_key(
10777 zcash_primitives::transaction::components::orchard::bundle_version_for_branch(
10778 pczt_branch_id,
10779 ::orchard::ValuePool::Orchard,
10780 )
10781 .expect("the PCZT's consensus branch supports the Orchard pool")
10782 .circuit_version(),
10783 );
10784 let proven = Prover::new(authorized)
10785 .create_orchard_proof(UnwrapErr(SysRng), orchard_pk)
10786 .unwrap()
10787 .create_ironwood_proof(UnwrapErr(SysRng), orchard_pk)
10788 .unwrap()
10789 .finish();
10790
10791 let txid = st
10792 .extract_and_store_transaction_from_pczt(proven)
10793 .expect("extracts, verifies, and stores the finalized transaction");
10794
10795 let sent_outputs = st.wallet().get_sent_outputs(&txid).unwrap();
10798 assert!(
10799 sent_outputs.iter().any(|output| {
10800 output.value() == Zatoshis::const_from_u64(10_000)
10801 && output.external_recipient().is_some()
10802 }),
10803 "the Ironwood payment output is recorded among the sent outputs: {sent_outputs:?}",
10804 );
10805 assert!(
10806 !st.wallet()
10807 .get_sent_note_ids(&txid, ShieldedPool::Ironwood)
10808 .unwrap()
10809 .is_empty(),
10810 "the payment's sent-note record belongs to the Ironwood pool",
10811 );
10812}
10813
10814#[cfg(feature = "orchard")]
10819pub fn orchard_to_ironwood_payment_reports_net_value_delta<Dsf>(
10820 ds_factory: Dsf,
10821 cache: impl TestCache,
10822) where
10823 Dsf: DataStoreFactory,
10824{
10825 let ironwood_active_network = {
10827 let activation = BlockHeight::from_u32(100_000);
10828 LocalNetwork {
10829 nu6: Some(activation),
10830 nu6_1: Some(activation),
10831 nu6_2: Some(activation),
10832 nu6_3: Some(activation),
10833 ..TestBuilder::<(), ()>::DEFAULT_NETWORK
10834 }
10835 };
10836
10837 let mut st = TestDsl::from(
10838 TestBuilder::new()
10839 .with_network(ironwood_active_network)
10840 .with_data_store_factory(ds_factory)
10841 .with_block_cache(cache)
10842 .with_account_from_sapling_activation(BlockHash([0; 32])),
10843 )
10844 .build::<OrchardPoolTester>();
10845
10846 let note_value = Zatoshis::const_from_u64(60_000);
10848 st.add_a_single_note_checking_balance(note_value);
10849
10850 let to_extsk = OrchardPoolTester::sk(&[0xf5; 32]);
10853 let to = OrchardPoolTester::sk_default_address(&to_extsk);
10854 let transfer_amount = Zatoshis::const_from_u64(10_000);
10855 let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
10856 to.to_zcash_address(st.network()),
10857 transfer_amount,
10858 )])
10859 .unwrap();
10860
10861 let change_strategy =
10862 single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
10863 let input_selector = GreedyInputSelector::new();
10864
10865 let account = st.get_account();
10866 let account_id = account.id();
10867 let usk = account.usk().clone();
10868 let proposal = st
10869 .propose_transfer(
10870 account_id,
10871 &input_selector,
10872 &change_strategy,
10873 request,
10874 ConfirmationsPolicy::MIN,
10875 )
10876 .expect("proposal construction succeeds; the Orchard-receiver payment routes to Ironwood");
10877
10878 assert_eq!(
10880 proposal.steps().head.payment_pools().get(&0),
10881 Some(&PoolType::IRONWOOD),
10882 );
10883 let fee = proposal.steps().head.balance().fee_required();
10884 let expected_change = (note_value - transfer_amount - fee).unwrap();
10885
10886 let txids = st
10887 .create_proposed_transactions::<Infallible, _, Infallible, _>(
10888 &usk,
10889 OvkPolicy::Sender,
10890 &proposal,
10891 )
10892 .expect("an Ironwood-routed payment builds successfully");
10893 let txid = *txids.first();
10894
10895 let expected_delta = -zcash_protocol::value::ZatBalance::from((transfer_amount + fee).unwrap());
10898 macro_rules! check_history {
10899 ($phase:literal) => {{
10900 let tx_history = st.wallet().get_tx_history().unwrap();
10901 let tx = tx_history
10902 .iter()
10903 .find(|tx| tx.txid() == txid)
10904 .expect("the created transaction appears in the transaction history");
10905 assert_eq!(
10906 tx.account_value_delta(),
10907 expected_delta,
10908 "account_value_delta ({}) reflects the payment plus fee",
10909 $phase,
10910 );
10911 assert_eq!(
10912 tx.total_spent(),
10913 note_value,
10914 "total_spent ({}) is the total value of the notes spent",
10915 $phase,
10916 );
10917 assert_eq!(
10918 tx.total_received(),
10919 expected_change,
10920 "total_received ({}) is the change returned to the wallet",
10921 $phase,
10922 );
10923 assert!(tx.has_change(), "the transaction has change ({})", $phase);
10924 assert_eq!(
10927 tx.pool_crossing_value(),
10928 None,
10929 "a payment to an external recipient is not a pool crossing ({})",
10930 $phase,
10931 );
10932 }};
10933 }
10934
10935 check_history!("before mining");
10937
10938 let (h, _) = st.generate_next_block_including(txid);
10940 st.scan_cached_blocks(h, 1);
10941 check_history!("after mining");
10942
10943 let tx = st
10947 .wallet()
10948 .get_transaction(txid)
10949 .unwrap()
10950 .expect("the created transaction can be retrieved");
10951 let network = *st.network();
10952 decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, Some(h)).unwrap();
10953 check_history!("after enhancement");
10954}
10955
10956#[cfg(feature = "orchard")]
10963pub fn orchard_to_ironwood_self_migration_reports_fee_only_delta<Dsf>(
10964 ds_factory: Dsf,
10965 cache: impl TestCache,
10966) where
10967 Dsf: DataStoreFactory,
10968{
10969 let ironwood_active_network = {
10971 let activation = BlockHeight::from_u32(100_000);
10972 LocalNetwork {
10973 nu6: Some(activation),
10974 nu6_1: Some(activation),
10975 nu6_2: Some(activation),
10976 nu6_3: Some(activation),
10977 ..TestBuilder::<(), ()>::DEFAULT_NETWORK
10978 }
10979 };
10980
10981 let mut st = TestDsl::from(
10982 TestBuilder::new()
10983 .with_network(ironwood_active_network)
10984 .with_data_store_factory(ds_factory)
10985 .with_block_cache(cache)
10986 .with_account_from_sapling_activation(BlockHash([0; 32])),
10987 )
10988 .build::<OrchardPoolTester>();
10989
10990 let note_value = Zatoshis::const_from_u64(60_000);
10992 st.add_a_single_note_checking_balance(note_value);
10993
10994 let own_fvk = OrchardPoolTester::test_account_fvk(&st);
10997 let own_address = OrchardPoolTester::fvk_default_address(&own_fvk);
10998 let transfer_amount = Zatoshis::const_from_u64(40_000);
10999 let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
11000 own_address.to_zcash_address(st.network()),
11001 transfer_amount,
11002 )])
11003 .unwrap();
11004
11005 let change_strategy =
11006 single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
11007 let input_selector = GreedyInputSelector::new();
11008
11009 let account = st.get_account();
11010 let account_id = account.id();
11011 let usk = account.usk().clone();
11012 let proposal = st
11013 .propose_transfer(
11014 account_id,
11015 &input_selector,
11016 &change_strategy,
11017 request,
11018 ConfirmationsPolicy::MIN,
11019 )
11020 .expect("proposal construction succeeds; the Orchard-receiver payment routes to Ironwood");
11021
11022 assert_eq!(
11024 proposal.steps().head.payment_pools().get(&0),
11025 Some(&PoolType::IRONWOOD),
11026 );
11027 let fee = proposal.steps().head.balance().fee_required();
11028
11029 let txids = st
11030 .create_proposed_transactions::<Infallible, _, Infallible, _>(
11031 &usk,
11032 OvkPolicy::Sender,
11033 &proposal,
11034 )
11035 .expect("an Ironwood-routed payment builds successfully");
11036 let txid = *txids.first();
11037
11038 let (h, _) = st.generate_next_block_including(txid);
11042 st.scan_cached_blocks(h, 1);
11043
11044 macro_rules! check_history {
11045 ($phase:literal) => {{
11046 let tx_history = st.wallet().get_tx_history().unwrap();
11047 let tx = tx_history
11048 .iter()
11049 .find(|tx| tx.txid() == txid)
11050 .expect("the created transaction appears in the transaction history");
11051 assert_eq!(
11052 tx.total_spent(),
11053 note_value,
11054 "total_spent ({}) is the total value of the notes spent",
11055 $phase,
11056 );
11057 assert_eq!(
11058 tx.total_received(),
11059 (note_value - fee).unwrap(),
11060 "total_received ({}) covers both the migrated value and the change",
11061 $phase,
11062 );
11063 assert_eq!(
11064 tx.account_value_delta(),
11065 -zcash_protocol::value::ZatBalance::from(fee),
11066 "the migration ({}) reduces the account balance only by the fee",
11067 $phase,
11068 );
11069 assert!(
11075 tx.is_pool_crossing(),
11076 "a mined payment to the wallet's own address is a pool crossing ({})",
11077 $phase,
11078 );
11079 assert_eq!(
11080 tx.pool_crossing_value(),
11081 Some(transfer_amount),
11082 "pool_crossing_value ({}) is the migrated payment amount",
11083 $phase,
11084 );
11085 }};
11086 }
11087
11088 check_history!("after mining");
11089 assert_eq!(
11090 st.get_total_balance(account_id),
11091 (note_value - fee).unwrap(),
11092 "the account retains all funds except the fee",
11093 );
11094
11095 let tx = st
11099 .wallet()
11100 .get_transaction(txid)
11101 .unwrap()
11102 .expect("the created transaction can be retrieved");
11103 let network = *st.network();
11104 decrypt_and_store_transaction(&network, st.wallet_mut(), &tx, Some(h)).unwrap();
11105 check_history!("after enhancement");
11106}
11107
11108#[cfg(feature = "orchard")]
11113pub fn proposal_records_and_serializes_proposed_version<Dsf>(ds_factory: Dsf, cache: impl TestCache)
11114where
11115 Dsf: DataStoreFactory,
11116{
11117 let mut st = TestDsl::from(
11118 TestBuilder::new()
11119 .with_data_store_factory(ds_factory)
11120 .with_block_cache(cache)
11121 .with_account_from_sapling_activation(BlockHash([0; 32])),
11122 )
11123 .build::<OrchardPoolTester>();
11124
11125 st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(60_000));
11127
11128 let to_extsk = OrchardPoolTester::sk(&[0xf5; 32]);
11129 let to = OrchardPoolTester::sk_default_address(&to_extsk);
11130 let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
11131 to.to_zcash_address(st.network()),
11132 Zatoshis::const_from_u64(10_000),
11133 )])
11134 .unwrap();
11135
11136 let change_strategy =
11137 single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
11138 let input_selector = GreedyInputSelector::new();
11139
11140 let account_id = st.get_account().id();
11141 let network = *st.network();
11142 let proposal = propose_transfer::<_, _, _, _, Infallible>(
11144 st.wallet_mut(),
11145 &network,
11146 account_id,
11147 &input_selector,
11148 &change_strategy,
11149 request,
11150 ConfirmationsPolicy::MIN,
11151 &SpendPolicy::default(),
11152 None,
11153 Some(TxVersion::V5),
11154 )
11155 .expect("proposal construction succeeds");
11156
11157 assert_eq!(proposal.proposed_version(), Some(TxVersion::V5));
11159
11160 let proto = crate::proto::proposal::Proposal::from_standard_proposal(&proposal);
11162 let decoded = proto
11163 .try_into_standard_proposal(&network, st.wallet())
11164 .expect("the serialized proposal decodes");
11165 assert_eq!(decoded.proposed_version(), Some(TxVersion::V5));
11166
11167 let mut legacy_proto = crate::proto::proposal::Proposal::from_standard_proposal(&proposal);
11170 legacy_proto.proposed_version = None;
11171 let decoded_legacy = legacy_proto
11172 .try_into_standard_proposal(&network, st.wallet())
11173 .expect("a legacy proposal without a requested version must decode");
11174 assert_eq!(decoded_legacy.proposed_version(), None);
11175}
11176
11177#[cfg(feature = "orchard")]
11182pub fn canonical_crossing_is_bucketed_and_unpadded<Dsf: DataStoreFactory>(
11183 ds_factory: Dsf,
11184 cache: impl TestCache,
11185) {
11186 let interval = AnchorBucketInterval::custom(NonZeroU32::new(12).expect("nonzero"));
11188 let activation = BlockHeight::from_u32(100_000);
11189 let ironwood_active_network = LocalNetwork {
11190 nu6: Some(activation),
11191 nu6_1: Some(activation),
11192 nu6_2: Some(activation),
11193 nu6_3: Some(activation),
11194 ..TestBuilder::<(), ()>::DEFAULT_NETWORK
11195 };
11196
11197 let mut st = TestDsl::from(
11198 TestBuilder::new()
11199 .with_network(ironwood_active_network)
11200 .with_data_store_factory(ds_factory)
11201 .with_block_cache(cache)
11202 .with_anchor_retention_interval(interval)
11203 .with_account_from_sapling_activation(BlockHash([0; 32])),
11204 )
11205 .build::<OrchardPoolTester>();
11206
11207 let account = st.test_account().cloned().unwrap();
11208 let fvk = OrchardPoolTester::test_account_fvk(&st);
11209 let recipient = OrchardPoolTester::fvk_default_address(&fvk).to_zcash_address(st.network());
11210
11211 let note_value = Zatoshis::const_from_u64(10_000_000);
11213 let (received_height, _, _) = st.add_a_single_note_checking_balance(note_value);
11214
11215 let received = u32::from(received_height);
11221 let interval_blocks = interval.block_count().get();
11222 let tip = u32::from(anchor_grid(st.network(), interval).boundary_at_or_above(received_height))
11225 + 3 * interval_blocks
11226 + 5;
11227 let filler_count = tip - received;
11228
11229 let not_our_fvk = OrchardPoolTester::sk_to_fvk(&OrchardPoolTester::sk(&[0xf5; 32]));
11232 for _ in 0..filler_count {
11233 st.generate_next_block(
11234 ¬_our_fvk,
11235 AddressType::DefaultExternal,
11236 Zatoshis::const_from_u64(10_000),
11237 );
11238 }
11239 st.scan_cached_blocks(received_height + 1, filler_count as usize);
11240
11241 let input_selector = GreedyInputSelector::new();
11242 let change_strategy =
11243 single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
11244
11245 let propose = |st: &mut TestState<_, _, _>, amount: Zatoshis| {
11246 let request =
11247 TransactionRequest::new(vec![Payment::without_memo(recipient.clone(), amount)])
11248 .unwrap();
11249 st.propose_transfer(
11250 account.id(),
11251 &input_selector,
11252 &change_strategy,
11253 request,
11254 ConfirmationsPolicy::MIN,
11255 )
11256 };
11257
11258 let canonical = propose(&mut st, MAX_RESIDUAL_VALUE).expect("the wallet can fund this");
11260 assert_eq!(canonical.steps().len(), 1);
11261 let canonical_fee = crate::fees::canonical_crossing_fee(
11262 st.network(),
11263 BlockHeight::from(canonical.min_target_height()),
11264 )
11265 .expect("the canonical shape is a valid input to the ZIP 317 rule");
11266
11267 let step = canonical.steps().first();
11268 let anchor = step
11269 .anchor_height()
11270 .expect("a shielded step binds an anchor");
11271 assert!(
11272 anchor_grid(st.network(), interval).is_boundary(anchor),
11273 "a canonical crossing must anchor to a grid boundary, got {anchor:?}"
11274 );
11275 assert_eq!(step.input_count_in_pool(PoolType::ORCHARD), 1);
11276 assert_eq!(step.input_count_in_pool(PoolType::IRONWOOD), 0);
11277 assert!(step.is_canonical_crossing(
11278 &st.wallet().pool_migration_params(st.network()),
11279 canonical_fee
11280 ));
11281 assert_eq!(
11282 step.ironwood_action_count(
11283 step.ironwood_bundle_padding(),
11284 ::orchard::bundle::BundleVersion::ironwood_v3()
11285 ),
11286 Ok(1),
11287 "the Ironwood bundle must be a single unpadded action"
11288 );
11289
11290 let off_by_one = propose(
11292 &mut st,
11293 (MAX_RESIDUAL_VALUE + Zatoshis::const_from_u64(1)).unwrap(),
11294 )
11295 .unwrap();
11296 let step = off_by_one.steps().first();
11297 assert!(!step.is_canonical_crossing(
11298 &st.wallet().pool_migration_params(st.network()),
11299 canonical_fee
11300 ));
11301 assert_eq!(
11302 step.ironwood_action_count(
11303 step.ironwood_bundle_padding(),
11304 ::orchard::bundle::BundleVersion::ironwood_v3()
11305 ),
11306 Ok(2)
11307 );
11308 assert!(
11309 !anchor_grid(st.network(), interval).is_boundary(step.anchor_height().unwrap()),
11310 "a non-canonical payment must not pay for a bucketed anchor"
11311 );
11312
11313 assert_eq!(
11320 canonical
11321 .steps()
11322 .first()
11323 .balance()
11324 .dummy_outputs()
11325 .expect("the fee model records dummy outputs")
11326 .ironwood(),
11327 0,
11328 "a canonical crossing has no Ironwood dummy output"
11329 );
11330 assert_eq!(
11331 canonical.steps().first().ironwood_bundle_padding(),
11332 BundlePadding::UNPADDED,
11333 "and the step must report the recorded value to the builder"
11334 );
11335
11336 let proto = crate::proto::proposal::Proposal::from_standard_proposal(&canonical);
11339 let serialized_dummy_outputs = proto.steps[0]
11340 .balance
11341 .as_ref()
11342 .expect("a proposal step carries a balance")
11343 .dummy_outputs
11344 .as_ref()
11345 .expect("new proposals serialize their dummy outputs");
11346 assert_eq!(
11347 (
11348 serialized_dummy_outputs.sapling,
11349 serialized_dummy_outputs.orchard,
11350 serialized_dummy_outputs.ironwood,
11351 ),
11352 (0, 1, 0)
11353 );
11354 let canonical = proto
11355 .try_into_standard_proposal(st.network(), st.wallet())
11356 .expect("the canonical proposal must deserialize");
11357 assert_eq!(
11358 canonical
11359 .steps()
11360 .first()
11361 .balance()
11362 .dummy_outputs()
11363 .expect("dummy outputs survive proposal decoding")
11364 .ironwood(),
11365 0,
11366 "the PCZT proposal round-trip must preserve the Ironwood dummy-output count"
11367 );
11368
11369 let txids = st.create_proposed_expecting(&canonical, 1);
11370 let built = st
11371 .wallet()
11372 .get_transaction(txids[0])
11373 .unwrap()
11374 .expect("the transaction was stored");
11375 assert_eq!(
11376 built
11377 .ironwood_bundle()
11378 .expect("a crossing carries an Ironwood bundle")
11379 .actions()
11380 .len(),
11381 1,
11382 "the BUILT Ironwood bundle must have the single action the fee was charged for"
11383 );
11384
11385 let tx = st.get_tx_from_history(txids[0]).unwrap().unwrap();
11386 assert_eq!(
11387 tx.expiry_height(),
11388 Some(zcash_protocol::zip318::expiry_height(
11389 &zcash_protocol::zip318::BlockSpacing::for_network(st.network()),
11390 BlockHeight::from(canonical.min_target_height())
11391 )),
11392 "a canonical crossing must carry the ZIP 318 rolling expiry"
11393 );
11394 assert_eq!(
11395 tx.fee_paid(),
11396 Some(canonical_fee),
11397 "and the canonical ZIP 317 fee that shape costs"
11398 );
11399}
11400
11401#[cfg(feature = "orchard")]
11407pub fn canonical_crossing_builds_at_empty_boundary_block<Dsf: DataStoreFactory>(
11408 ds_factory: Dsf,
11409 cache: impl TestCache,
11410) {
11411 let interval = AnchorRetentionInterval::custom(NonZeroU32::new(12).expect("nonzero"));
11413 let activation = BlockHeight::from_u32(100_000);
11414 let ironwood_active_network = LocalNetwork {
11415 nu6: Some(activation),
11416 nu6_1: Some(activation),
11417 nu6_2: Some(activation),
11418 nu6_3: Some(activation),
11419 ..TestBuilder::<(), ()>::DEFAULT_NETWORK
11420 };
11421
11422 let mut st = TestDsl::from(
11423 TestBuilder::new()
11424 .with_network(ironwood_active_network)
11425 .with_data_store_factory(ds_factory)
11426 .with_block_cache(cache)
11427 .with_anchor_retention_interval(interval)
11428 .with_account_from_sapling_activation(BlockHash([0; 32])),
11429 )
11430 .build::<OrchardPoolTester>();
11431
11432 let account = st.test_account().cloned().unwrap();
11433 let fvk = OrchardPoolTester::test_account_fvk(&st);
11434 let recipient = OrchardPoolTester::fvk_default_address(&fvk).to_zcash_address(st.network());
11435
11436 let note_value = Zatoshis::const_from_u64(10_000_000);
11438 let (received_height, _, _) = st.add_a_single_note_checking_balance(note_value);
11439 let received = u32::from(received_height);
11440 let interval_blocks = interval.block_count().get();
11441
11442 let tip = u32::from(anchor_grid(st.network(), interval).boundary_at_or_above(received_height))
11448 + 3 * interval_blocks
11449 + 5;
11450 let not_our_fvk = OrchardPoolTester::sk_to_fvk(&OrchardPoolTester::sk(&[0xf5; 32]));
11451 let mut empty_heights = Vec::new();
11452 for height in (received + 1)..=tip {
11453 if anchor_grid(st.network(), interval).is_boundary(BlockHeight::from_u32(height)) {
11454 let (h, _) = st.generate_empty_block();
11455 empty_heights.push(h);
11456 } else {
11457 st.generate_next_block(
11458 ¬_our_fvk,
11459 AddressType::DefaultExternal,
11460 Zatoshis::const_from_u64(10_000),
11461 );
11462 }
11463 }
11464 st.scan_cached_blocks(received_height + 1, (tip - received) as usize);
11467
11468 let input_selector = GreedyInputSelector::new();
11469 let change_strategy =
11470 single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
11471 let request = TransactionRequest::new(vec![Payment::without_memo(
11472 recipient.clone(),
11473 MAX_RESIDUAL_VALUE,
11474 )])
11475 .unwrap();
11476 let canonical = st
11477 .propose_transfer(
11478 account.id(),
11479 &input_selector,
11480 &change_strategy,
11481 request,
11482 ConfirmationsPolicy::MIN,
11483 )
11484 .expect("the wallet can fund this");
11485
11486 let canonical_fee = crate::fees::canonical_crossing_fee(
11487 st.network(),
11488 BlockHeight::from(canonical.min_target_height()),
11489 )
11490 .expect("the canonical shape is a valid input to the ZIP 317 rule");
11491 let step = canonical.steps().first();
11492 let anchor = step
11493 .anchor_height()
11494 .expect("a shielded step binds an anchor");
11495 assert!(
11496 step.is_canonical_crossing(
11497 &st.wallet().pool_migration_params(st.network()),
11498 canonical_fee
11499 ),
11500 "the payment must be recognized as a canonical crossing"
11501 );
11502 assert!(
11503 empty_heights.contains(&anchor),
11504 "the bucketed anchor {anchor:?} must be one of the empty boundary blocks {empty_heights:?}"
11505 );
11506
11507 let txids = st.create_proposed_expecting(&canonical, 1);
11510 let built = st
11511 .wallet()
11512 .get_transaction(txids[0])
11513 .unwrap()
11514 .expect("the transaction was stored");
11515 assert_eq!(
11516 built
11517 .ironwood_bundle()
11518 .expect("a crossing carries an Ironwood bundle")
11519 .actions()
11520 .len(),
11521 1,
11522 "the BUILT Ironwood bundle must have the single action of the canonical shape"
11523 );
11524}
11525
11526#[cfg(feature = "orchard")]
11534pub fn multi_note_crossing_is_not_bucketed<Dsf: DataStoreFactory>(
11535 ds_factory: Dsf,
11536 cache: impl TestCache,
11537) {
11538 let interval = AnchorBucketInterval::custom(NonZeroU32::new(12).expect("nonzero"));
11539 let activation = BlockHeight::from_u32(100_000);
11540 let network = LocalNetwork {
11541 nu6: Some(activation),
11542 nu6_1: Some(activation),
11543 nu6_2: Some(activation),
11544 nu6_3: Some(activation),
11545 ..TestBuilder::<(), ()>::DEFAULT_NETWORK
11546 };
11547
11548 let mut st = TestDsl::from(
11549 TestBuilder::new()
11550 .with_network(network)
11551 .with_data_store_factory(ds_factory)
11552 .with_block_cache(cache)
11553 .with_anchor_retention_interval(interval)
11554 .with_account_from_sapling_activation(BlockHash([0; 32])),
11555 )
11556 .build::<OrchardPoolTester>();
11557
11558 let account = st.test_account().cloned().unwrap();
11559 let fvk = OrchardPoolTester::test_account_fvk(&st);
11560 let recipient = OrchardPoolTester::fvk_default_address(&fvk).to_zcash_address(st.network());
11561
11562 let note_value = Zatoshis::const_from_u64(400_000);
11564 let (first_height, _, _) = st.add_a_single_note_checking_balance(note_value);
11565 for _ in 0..2 {
11566 st.generate_next_block(&fvk, AddressType::DefaultExternal, note_value);
11567 }
11568 st.scan_cached_blocks(first_height + 1, 2);
11569
11570 let interval_blocks = interval.block_count().get();
11571 let tip = u32::from(anchor_grid(st.network(), interval).boundary_at_or_above(first_height))
11572 + 3 * interval_blocks
11573 + 5;
11574 let not_our_fvk = OrchardPoolTester::sk_to_fvk(&OrchardPoolTester::sk(&[0xf5; 32]));
11575 let filler_count = tip - u32::from(first_height) - 2;
11576 for _ in 0..filler_count {
11577 st.generate_next_block(
11578 ¬_our_fvk,
11579 AddressType::DefaultExternal,
11580 Zatoshis::const_from_u64(10_000),
11581 );
11582 }
11583 st.scan_cached_blocks(first_height + 3, filler_count as usize);
11584
11585 let input_selector = GreedyInputSelector::new();
11586 let change_strategy =
11587 single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
11588 let request =
11589 TransactionRequest::new(vec![Payment::without_memo(recipient, MAX_RESIDUAL_VALUE)])
11590 .unwrap();
11591
11592 let proposal = st
11593 .propose_transfer(
11594 account.id(),
11595 &input_selector,
11596 &change_strategy,
11597 request,
11598 ConfirmationsPolicy::MIN,
11599 )
11600 .expect("three notes together can fund the payment");
11601
11602 let step = proposal.steps().first();
11603 let zip318 = st.wallet().pool_migration_params(st.network());
11604 let canonical_fee = crate::fees::canonical_crossing_fee(
11605 st.network(),
11606 BlockHeight::from(proposal.min_target_height()),
11607 )
11608 .expect("the canonical shape is a valid input to the ZIP 317 rule");
11609 assert!(
11610 step.input_count_in_pool(PoolType::ORCHARD) > 1,
11611 "this scenario is only meaningful if funding needs several notes"
11612 );
11613 assert!(!step.is_canonical_crossing(&zip318, canonical_fee));
11614 assert!(
11615 !anchor_grid(st.network(), interval).is_boundary(step.anchor_height().unwrap()),
11616 "a multi-input transaction must not pay for a bucketed anchor"
11617 );
11618 assert_eq!(
11619 step.ironwood_action_count(
11620 step.ironwood_bundle_padding(),
11621 ::orchard::bundle::BundleVersion::ironwood_v3()
11622 ),
11623 Ok(2)
11624 );
11625}
11626
11627#[cfg(feature = "orchard")]
11639pub fn canonical_crossing_prefers_single_note<Dsf: DataStoreFactory>(
11640 ds_factory: Dsf,
11641 cache: impl TestCache,
11642) {
11643 let interval = AnchorRetentionInterval::custom(NonZeroU32::new(12).expect("nonzero"));
11644 let activation = BlockHeight::from_u32(100_000);
11645 let network = LocalNetwork {
11646 nu6: Some(activation),
11647 nu6_1: Some(activation),
11648 nu6_2: Some(activation),
11649 nu6_3: Some(activation),
11650 ..TestBuilder::<(), ()>::DEFAULT_NETWORK
11651 };
11652
11653 let mut st = TestDsl::from(
11654 TestBuilder::new()
11655 .with_network(network)
11656 .with_data_store_factory(ds_factory)
11657 .with_block_cache(cache)
11658 .with_anchor_retention_interval(interval)
11659 .with_account_from_sapling_activation(BlockHash([0; 32])),
11660 )
11661 .build::<OrchardPoolTester>();
11662
11663 let account = st.test_account().cloned().unwrap();
11664 let fvk = OrchardPoolTester::test_account_fvk(&st);
11665 let recipient = OrchardPoolTester::fvk_default_address(&fvk).to_zcash_address(st.network());
11666
11667 let small_value = Zatoshis::const_from_u64(600_000);
11671 let large_value = Zatoshis::const_from_u64(1_200_000);
11672 let (first_height, _, _) = st.add_a_single_note_checking_balance(small_value);
11673 st.generate_next_block(&fvk, AddressType::DefaultExternal, small_value);
11674 st.generate_next_block(&fvk, AddressType::DefaultExternal, large_value);
11675 st.scan_cached_blocks(first_height + 1, 2);
11676
11677 let interval_blocks = interval.block_count().get();
11678 let tip = u32::from(anchor_grid(st.network(), interval).boundary_at_or_above(first_height))
11679 + 3 * interval_blocks
11680 + 5;
11681 let not_our_fvk = OrchardPoolTester::sk_to_fvk(&OrchardPoolTester::sk(&[0xf5; 32]));
11682 let filler_count = tip - u32::from(first_height) - 2;
11683 for _ in 0..filler_count {
11684 st.generate_next_block(
11685 ¬_our_fvk,
11686 AddressType::DefaultExternal,
11687 Zatoshis::const_from_u64(10_000),
11688 );
11689 }
11690 st.scan_cached_blocks(first_height + 3, filler_count as usize);
11691
11692 let input_selector = GreedyInputSelector::new();
11693 let change_strategy =
11694 single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
11695 let propose = |st: &mut TestState<_, _, _>, amount: Zatoshis| {
11696 let request =
11697 TransactionRequest::new(vec![Payment::without_memo(recipient.clone(), amount)])
11698 .unwrap();
11699 st.propose_transfer(
11700 account.id(),
11701 &input_selector,
11702 &change_strategy,
11703 request,
11704 ConfirmationsPolicy::MIN,
11705 )
11706 };
11707
11708 let canonical = propose(&mut st, MAX_RESIDUAL_VALUE).expect("the wallet can fund this");
11710 let step = canonical.steps().first();
11711 let zip318 = st.wallet().pool_migration_params(st.network());
11712 let canonical_fee = crate::fees::canonical_crossing_fee(
11713 st.network(),
11714 BlockHeight::from(canonical.min_target_height()),
11715 )
11716 .expect("the canonical shape is a valid input to the ZIP 317 rule");
11717 assert_eq!(
11718 step.input_count_in_pool(PoolType::ORCHARD),
11719 1,
11720 "the canonical payment must be funded from a single note"
11721 );
11722 assert!(step.is_canonical_crossing(&zip318, canonical_fee));
11723 let spent = step
11724 .shielded_inputs()
11725 .expect("a shielded step spends notes")
11726 .notes()
11727 .first()
11728 .note()
11729 .value();
11730 assert_eq!(
11731 spent, large_value,
11732 "the single covering note funds the payment, not the older small notes"
11733 );
11734
11735 let ordinary = propose(
11737 &mut st,
11738 (MAX_RESIDUAL_VALUE + Zatoshis::const_from_u64(1)).unwrap(),
11739 )
11740 .expect("the wallet can fund this too");
11741 let step = ordinary.steps().first();
11742 assert!(
11743 step.input_count_in_pool(PoolType::ORCHARD) > 1,
11744 "single-note preference must not leak into ordinary selection"
11745 );
11746}
11747
11748#[cfg(feature = "orchard")]
11764pub fn canonical_crossing_abandoned_without_anchor_checkpoint<Dsf, TC>(
11765 ds_factory: Dsf,
11766 cache: TC,
11767 remove_checkpoint: impl FnOnce(&mut TestState<TC, Dsf::DataStore, LocalNetwork>, BlockHeight),
11768) where
11769 Dsf: DataStoreFactory,
11770 TC: TestCache,
11771{
11772 let interval = AnchorRetentionInterval::custom(NonZeroU32::new(12).expect("nonzero"));
11773 let activation = BlockHeight::from_u32(100_000);
11774 let network = LocalNetwork {
11775 nu6: Some(activation),
11776 nu6_1: Some(activation),
11777 nu6_2: Some(activation),
11778 nu6_3: Some(activation),
11779 ..TestBuilder::<(), ()>::DEFAULT_NETWORK
11780 };
11781
11782 let mut st = TestDsl::from(
11783 TestBuilder::new()
11784 .with_network(network)
11785 .with_data_store_factory(ds_factory)
11786 .with_block_cache(cache)
11787 .with_anchor_retention_interval(interval)
11788 .with_account_from_sapling_activation(BlockHash([0; 32])),
11789 )
11790 .build::<OrchardPoolTester>();
11791
11792 let account = st.test_account().cloned().unwrap();
11793 let fvk = OrchardPoolTester::test_account_fvk(&st);
11794 let recipient = OrchardPoolTester::fvk_default_address(&fvk).to_zcash_address(st.network());
11795
11796 let (received_height, _, _) =
11799 st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(10_000_000));
11800 let received = u32::from(received_height);
11801 let interval_blocks = interval.block_count().get();
11802 let tip = u32::from(anchor_grid(st.network(), interval).boundary_at_or_above(received_height))
11803 + 3 * interval_blocks
11804 + 5;
11805 let not_our_fvk = OrchardPoolTester::sk_to_fvk(&OrchardPoolTester::sk(&[0xf5; 32]));
11806 let filler_count = tip - received;
11807 for _ in 0..filler_count {
11808 st.generate_next_block(
11809 ¬_our_fvk,
11810 AddressType::DefaultExternal,
11811 Zatoshis::const_from_u64(10_000),
11812 );
11813 }
11814 st.scan_cached_blocks(received_height + 1, filler_count as usize);
11815
11816 let input_selector = GreedyInputSelector::new();
11817 let change_strategy =
11818 single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
11819 let propose = |st: &mut TestState<_, _, _>| {
11820 let request = TransactionRequest::new(vec![Payment::without_memo(
11821 recipient.clone(),
11822 MAX_RESIDUAL_VALUE,
11823 )])
11824 .unwrap();
11825 st.propose_transfer(
11826 account.id(),
11827 &input_selector,
11828 &change_strategy,
11829 request,
11830 ConfirmationsPolicy::MIN,
11831 )
11832 .expect("the wallet can fund this")
11833 };
11834
11835 let canonical = propose(&mut st);
11840 let step = canonical.steps().first();
11841 let zip318 = st.wallet().pool_migration_params(st.network());
11842 let canonical_fee = crate::fees::canonical_crossing_fee(
11843 st.network(),
11844 BlockHeight::from(canonical.min_target_height()),
11845 )
11846 .expect("the canonical shape is a valid input to the ZIP 317 rule");
11847 assert!(step.is_canonical_crossing(&zip318, canonical_fee));
11848 let boundary = step
11849 .anchor_height()
11850 .expect("a shielded step binds an anchor");
11851 assert!(
11852 st.wallet()
11853 .anchor_computable(ShieldedPool::Orchard, boundary)
11854 .unwrap(),
11855 "an anchor is computable at the boundary before removal"
11856 );
11857
11858 remove_checkpoint(&mut st, boundary);
11860 assert!(
11861 !st.wallet()
11862 .anchor_computable(ShieldedPool::Orchard, boundary)
11863 .unwrap(),
11864 "no anchor is computable at the boundary after removal"
11865 );
11866
11867 let fallback = propose(&mut st);
11871 let step = fallback.steps().first();
11872 assert!(
11873 !step.is_canonical_crossing(&zip318, canonical_fee),
11874 "the attempt must be abandoned when its anchor cannot be proved"
11875 );
11876 assert_ne!(
11877 step.anchor_height()
11878 .expect("a shielded step binds an anchor"),
11879 boundary,
11880 "the fallback anchors at the ordinary height, not the unprovable boundary"
11881 );
11882 st.create_proposed_expecting(&fallback, 1);
11883}
11884
11885#[cfg(feature = "orchard")]
11893pub fn self_migration_keeps_spending_orchard<Dsf: DataStoreFactory>(
11894 ds_factory: Dsf,
11895 cache: impl TestCache,
11896) {
11897 let interval = AnchorBucketInterval::custom(NonZeroU32::new(12).expect("nonzero"));
11898 let activation = BlockHeight::from_u32(100_000);
11899 let network = LocalNetwork {
11900 nu6: Some(activation),
11901 nu6_1: Some(activation),
11902 nu6_2: Some(activation),
11903 nu6_3: Some(activation),
11904 ..TestBuilder::<(), ()>::DEFAULT_NETWORK
11905 };
11906
11907 let mut st = TestDsl::from(
11908 TestBuilder::new()
11909 .with_network(network)
11910 .with_data_store_factory(ds_factory)
11911 .with_block_cache(cache)
11912 .with_anchor_retention_interval(interval)
11913 .with_account_from_sapling_activation(BlockHash([0; 32])),
11914 )
11915 .build::<OrchardPoolTester>();
11916
11917 let account = st.test_account().cloned().unwrap();
11918 let fvk = OrchardPoolTester::test_account_fvk(&st);
11919 let recipient = OrchardPoolTester::fvk_default_address(&fvk).to_zcash_address(st.network());
11920
11921 let (received_height, _, _) =
11922 st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(10_000_000));
11923
11924 let interval_blocks = interval.block_count().get();
11925 let not_our_fvk = OrchardPoolTester::sk_to_fvk(&OrchardPoolTester::sk(&[0xf5; 32]));
11926 let advance = |st: &mut TestState<_, _, _>, from: BlockHeight, count: u32| {
11927 for _ in 0..count {
11928 st.generate_next_block(
11929 ¬_our_fvk,
11930 AddressType::DefaultExternal,
11931 Zatoshis::const_from_u64(10_000),
11932 );
11933 }
11934 st.scan_cached_blocks(from, count as usize);
11935 };
11936
11937 let tip = u32::from(anchor_grid(st.network(), interval).boundary_at_or_above(received_height))
11938 + 3 * interval_blocks
11939 + 5;
11940 advance(
11941 &mut st,
11942 received_height + 1,
11943 tip - u32::from(received_height),
11944 );
11945
11946 let input_selector = GreedyInputSelector::new();
11947 let change_strategy =
11948 single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
11949 let zip318 = st.wallet().pool_migration_params(st.network());
11950
11951 let request = TransactionRequest::new(vec![Payment::without_memo(
11953 recipient.clone(),
11954 MAX_RESIDUAL_VALUE,
11955 )])
11956 .unwrap();
11957 let first = st
11958 .propose_transfer(
11959 account.id(),
11960 &input_selector,
11961 &change_strategy,
11962 request,
11963 ConfirmationsPolicy::MIN,
11964 )
11965 .expect("the wallet can fund the first crossing");
11966 let canonical_fee = crate::fees::canonical_crossing_fee(
11967 st.network(),
11968 BlockHeight::from(first.min_target_height()),
11969 )
11970 .expect("the canonical shape is a valid input to the ZIP 317 rule");
11971 assert!(
11972 first
11973 .steps()
11974 .first()
11975 .is_canonical_crossing(&zip318, canonical_fee)
11976 );
11977
11978 let txids = st.create_proposed_expecting(&first, 1);
11980 let (mined_height, _) = st.generate_next_block_including(txids[0]);
11981 st.scan_cached_blocks(mined_height, 1);
11982
11983 advance(&mut st, mined_height + 1, 2 * interval_blocks + 1);
11985
11986 let summary = st
11989 .get_wallet_summary(ConfirmationsPolicy::MIN)
11990 .expect("the wallet is synced");
11991 let balances = summary
11992 .account_balances()
11993 .get(&account.id())
11994 .expect("the account is known");
11995 assert!(
11996 balances.ironwood_balance().total().is_positive(),
11997 "the first crossing must have left an Ironwood note for the selector to prefer"
11998 );
11999 assert!(
12000 balances.orchard_balance().total().is_positive(),
12001 "and Orchard change to fund the second crossing from"
12002 );
12003
12004 let request =
12006 TransactionRequest::new(vec![Payment::without_memo(recipient, MAX_RESIDUAL_VALUE)])
12007 .unwrap();
12008 let second = st
12009 .propose_transfer(
12010 account.id(),
12011 &input_selector,
12012 &change_strategy,
12013 request,
12014 ConfirmationsPolicy::MIN,
12015 )
12016 .expect("the wallet can fund the second crossing");
12017
12018 let step = second.steps().first();
12019 assert_eq!(
12020 step.input_count_in_pool(PoolType::IRONWOOD),
12021 0,
12022 "the Ironwood note must be left alone, or self-migration stalls here"
12023 );
12024 assert_eq!(step.input_count_in_pool(PoolType::ORCHARD), 1);
12025 assert!(
12026 step.is_canonical_crossing(&zip318, canonical_fee),
12027 "the second crossing must still be canonical"
12028 );
12029}
12030
12031pub fn create_to_address_respects_recipient_expiry<T: ShieldedPoolTester>(
12037 dsf: impl DataStoreFactory,
12038 cache: impl TestCache,
12039) {
12040 let mut st = TestDsl::with_sapling_birthday_account(dsf, cache).build::<T>();
12041
12042 st.add_notes_checking_balance([
12045 [Zatoshis::const_from_u64(100_000)],
12046 [Zatoshis::const_from_u64(100_000)],
12047 [Zatoshis::const_from_u64(100_000)],
12048 ]);
12049
12050 let account = st.test_account().cloned().unwrap();
12051 let birthday = account.birthday().height();
12052 let chain_tip = st.wallet().chain_height().unwrap().unwrap();
12053
12054 let (default_addr, _) = account
12057 .usk()
12058 .to_unified_full_viewing_key()
12059 .default_address(UnifiedAddressRequest::AllAvailableKeys)
12060 .unwrap();
12061 let with_expiry = |expiry_height: Option<BlockHeight>, expiry_time: Option<u64>| {
12062 UnifiedAddress::from_receivers(
12063 #[cfg(feature = "orchard")]
12064 default_addr.orchard().copied(),
12065 default_addr.sapling().copied(),
12066 default_addr.transparent().copied(),
12067 expiry_height,
12068 expiry_time,
12069 )
12070 .expect("the default address has at least one receiver")
12071 };
12072
12073 let payment_value = Zatoshis::const_from_u64(20_000);
12074 let change_strategy =
12075 single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
12076 let input_selector = GreedyInputSelector::new();
12077
12078 let expired_by_height = with_expiry(Some(chain_tip), None);
12082 let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
12083 Address::from(expired_by_height.clone()).to_zcash_address(st.network()),
12084 payment_value,
12085 )])
12086 .unwrap();
12087 let proposal = st
12088 .propose_transfer(
12089 account.id(),
12090 &input_selector,
12091 &change_strategy,
12092 request,
12093 ConfirmationsPolicy::MIN,
12094 )
12095 .unwrap();
12096 assert_matches!(
12097 st.create_proposed_transactions::<Infallible, _, Infallible, _>(
12098 account.usk(),
12099 OvkPolicy::Sender,
12100 &proposal
12101 ),
12102 Err(Error::RecipientAddressExpiry {
12103 payment_index: 0,
12104 error: AddressExpiryError::ExpiryHeightConflict { .. },
12105 })
12106 );
12107
12108 const EXPIRY_TIME_IN_PAST: u64 = 1;
12112 let valid_far_future = with_expiry(
12113 Some(birthday + 10_000),
12114 Some(super::TEST_CLOCK_EPOCH_OFFSET.as_secs() + 10_000),
12115 );
12116 let expired_by_time = with_expiry(None, Some(EXPIRY_TIME_IN_PAST));
12117 let request = zip321::TransactionRequest::new(vec![
12118 Payment::without_memo(
12119 Address::from(valid_far_future.clone()).to_zcash_address(st.network()),
12120 payment_value,
12121 ),
12122 Payment::without_memo(
12123 Address::from(expired_by_time.clone()).to_zcash_address(st.network()),
12124 payment_value,
12125 ),
12126 ])
12127 .unwrap();
12128 let proposal = st
12129 .propose_transfer(
12130 account.id(),
12131 &input_selector,
12132 &change_strategy,
12133 request,
12134 ConfirmationsPolicy::MIN,
12135 )
12136 .unwrap();
12137 assert_matches!(
12138 st.create_proposed_transactions::<Infallible, _, Infallible, _>(
12139 account.usk(),
12140 OvkPolicy::Sender,
12141 &proposal
12142 ),
12143 Err(Error::RecipientAddressExpiry {
12144 payment_index: 1,
12145 error: AddressExpiryError::TimeExpired { .. },
12146 })
12147 );
12148
12149 let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
12151 Address::from(valid_far_future.clone()).to_zcash_address(st.network()),
12152 payment_value,
12153 )])
12154 .unwrap();
12155 let proposal = st
12156 .propose_transfer(
12157 account.id(),
12158 &input_selector,
12159 &change_strategy,
12160 request,
12161 ConfirmationsPolicy::MIN,
12162 )
12163 .unwrap();
12164 assert_matches!(
12165 st.create_proposed_transactions::<Infallible, _, Infallible, _>(
12166 account.usk(),
12167 OvkPolicy::Sender,
12168 &proposal
12169 ),
12170 Ok(_)
12171 );
12172
12173 let recipient = with_expiry(Some(chain_tip - 1), None);
12177 let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
12178 Address::from(recipient).to_zcash_address(st.network()),
12179 payment_value,
12180 )])
12181 .unwrap();
12182 let proposal = st
12183 .propose_transfer(
12184 account.id(),
12185 &input_selector,
12186 &change_strategy,
12187 request,
12188 ConfirmationsPolicy::MIN,
12189 )
12190 .unwrap();
12191 assert_matches!(
12192 st.create_proposed_transactions::<Infallible, _, Infallible, _>(
12193 account.usk(),
12194 OvkPolicy::Sender,
12195 &proposal
12196 ),
12197 Err(Error::RecipientAddressExpiry {
12198 payment_index: 0,
12199 error: AddressExpiryError::HeightExpired { .. },
12200 })
12201 );
12202
12203 let target_height = chain_tip + 1;
12208 let default_expiry_height =
12209 target_height + default_tx_expiry_delta(BranchId::for_height(st.network(), target_height));
12210 let recipient = with_expiry(Some(default_expiry_height), None);
12211 let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
12212 Address::from(recipient).to_zcash_address(st.network()),
12213 payment_value,
12214 )])
12215 .unwrap();
12216 let proposal = st
12217 .propose_transfer(
12218 account.id(),
12219 &input_selector,
12220 &change_strategy,
12221 request,
12222 ConfirmationsPolicy::MIN,
12223 )
12224 .unwrap();
12225 assert_matches!(
12226 st.create_proposed_transactions::<Infallible, _, Infallible, _>(
12227 account.usk(),
12228 OvkPolicy::Sender,
12229 &proposal
12230 ),
12231 Ok(_)
12232 );
12233
12234 let recipient = with_expiry(None, Some(super::TEST_CLOCK_EPOCH_OFFSET.as_secs()));
12237 let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
12238 Address::from(recipient).to_zcash_address(st.network()),
12239 payment_value,
12240 )])
12241 .unwrap();
12242 let proposal = st
12243 .propose_transfer(
12244 account.id(),
12245 &input_selector,
12246 &change_strategy,
12247 request,
12248 ConfirmationsPolicy::MIN,
12249 )
12250 .unwrap();
12251 assert_matches!(
12252 st.create_proposed_transactions::<Infallible, _, Infallible, _>(
12253 account.usk(),
12254 OvkPolicy::Sender,
12255 &proposal
12256 ),
12257 Ok(_)
12258 );
12259}
12260
12261const NU7_ACTIVATION_OFFSET: u32 = 10;
12264
12265pub(crate) fn nu7_activating_network() -> LocalNetwork {
12271 let activation = TestBuilder::<(), ()>::DEFAULT_NETWORK
12272 .sapling
12273 .expect("the default test network activates Sapling");
12274 LocalNetwork {
12275 nu6: Some(activation),
12276 nu6_1: Some(activation),
12277 nu6_2: Some(activation),
12278 nu6_3: Some(activation),
12279 nu7: Some(activation + NU7_ACTIVATION_OFFSET),
12280 ..TestBuilder::<(), ()>::DEFAULT_NETWORK
12281 }
12282}
12283
12284fn nu7_default_expiry_scenario<T: ShieldedPoolTester, Cache: TestCache, Dsf: DataStoreFactory>(
12288 dsf: Dsf,
12289 cache: Cache,
12290) -> (TestDsl<TestScenario<T, Cache, Dsf>>, BlockHeight) {
12291 let network = nu7_activating_network();
12292 let nu7_activation = network
12293 .activation_height(NetworkUpgrade::Nu7)
12294 .expect("the test network activates NU7");
12295 let mut st = TestDsl::from(
12296 TestBuilder::new()
12297 .with_network(network)
12298 .with_data_store_factory(dsf)
12299 .with_block_cache(cache)
12300 .with_account_from_sapling_activation(BlockHash([0; 32])),
12301 )
12302 .build::<T>();
12303
12304 st.add_notes_checking_balance([
12305 [Zatoshis::const_from_u64(100_000)],
12306 [Zatoshis::const_from_u64(100_000)],
12307 ]);
12308 let tip = st.wallet().chain_height().unwrap().unwrap();
12309 let blocks_to_add = u32::from(nu7_activation) - 2 - u32::from(tip);
12310 st.add_empty_blocks(usize::try_from(blocks_to_add).expect("block count fits in a usize"));
12311 (st, nu7_activation)
12312}
12313
12314pub fn create_proposed_transactions_uses_nu7_default_expiry<T: ShieldedPoolTester>(
12318 dsf: impl DataStoreFactory,
12319 cache: impl TestCache,
12320) {
12321 let (mut st, nu7_activation) = nu7_default_expiry_scenario::<T, _, _>(dsf, cache);
12322 let recipient = T::fvk_default_address(&T::sk_to_fvk(&T::sk(&[0xf5; 32])));
12323 let payment_value = Zatoshis::const_from_u64(20_000);
12324
12325 for (expected_target_height, expected_delta) in [
12326 (nu7_activation - 1, BLOSSOM_DEFAULT_TX_EXPIRY_DELTA),
12327 (nu7_activation, NU7_DEFAULT_TX_EXPIRY_DELTA),
12328 ] {
12329 let proposal = st.propose_transfer_to(&recipient, payment_value);
12330 let target_height = BlockHeight::from(proposal.min_target_height());
12331 assert_eq!(target_height, expected_target_height);
12332
12333 let txids = st.create_proposed_expecting(&proposal, 1);
12334 let tx = st
12335 .wallet()
12336 .get_transaction(txids[0])
12337 .unwrap()
12338 .expect("the created transaction is stored");
12339 assert_eq!(
12340 tx.expiry_height(),
12341 target_height + expected_delta,
12342 "default expiry height for target height {target_height}",
12343 );
12344
12345 st.add_empty_blocks(1);
12346 }
12347}
12348
12349#[cfg(feature = "pczt")]
12356pub fn create_pczt_uses_nu7_default_expiry<T: ShieldedPoolTester, Dsf>(
12357 dsf: Dsf,
12358 cache: impl TestCache,
12359) where
12360 Dsf: DataStoreFactory,
12361 <Dsf as DataStoreFactory>::AccountId: serde::Serialize + serde::de::DeserializeOwned,
12362{
12363 let (mut st, nu7_activation) = nu7_default_expiry_scenario::<T, _, _>(dsf, cache);
12364 let account_id = st.get_account().id();
12365 let recipient = T::fvk_default_address(&T::sk_to_fvk(&T::sk(&[0xf5; 32])));
12366 let payment_value = Zatoshis::const_from_u64(20_000);
12367
12368 for (expected_target_height, expected_delta) in [
12369 (nu7_activation - 1, BLOSSOM_DEFAULT_TX_EXPIRY_DELTA),
12370 (nu7_activation, NU7_DEFAULT_TX_EXPIRY_DELTA),
12371 ] {
12372 let proposal = st.propose_transfer_to(&recipient, payment_value);
12373 let target_height = BlockHeight::from(proposal.min_target_height());
12374 assert_eq!(target_height, expected_target_height);
12375
12376 let pczt = st
12377 .create_pczt_from_proposal::<Infallible, _, Infallible>(
12378 account_id,
12379 OvkPolicy::Sender,
12380 &proposal,
12381 None,
12382 )
12383 .unwrap();
12384 assert_eq!(
12385 *pczt.global().expiry_height(),
12386 u32::from(target_height + expected_delta),
12387 "default expiry height for target height {target_height}",
12388 );
12389
12390 st.add_empty_blocks(1);
12391 }
12392}
12393
12394pub fn proposal_fee_is_fixed_at_its_target_height_across_fee_reduction<T: ShieldedPoolTester>(
12400 dsf: impl DataStoreFactory,
12401 cache: impl TestCache,
12402) {
12403 let (mut st, nu7_activation) = nu7_default_expiry_scenario::<T, _, _>(dsf, cache);
12404 let reduction_height = nu7_activation;
12406 let recipient = T::fvk_default_address(&T::sk_to_fvk(&T::sk(&[0xf5; 32])));
12407 let payment_value = Zatoshis::const_from_u64(20_000);
12408
12409 let proposal = st.propose_transfer_to(&recipient, payment_value);
12414 let target_height = BlockHeight::from(proposal.min_target_height());
12415 assert_eq!(target_height, reduction_height - 1);
12416 let pre_reduction_fee = proposal.steps().first().balance().fee_required();
12417 let logical_actions =
12418 u64::from(pre_reduction_fee) / u64::from(marginal_fee(st.network(), target_height));
12419 assert_eq!(
12420 (marginal_fee(st.network(), target_height) * logical_actions).unwrap(),
12421 pre_reduction_fee
12422 );
12423
12424 let tip = st.add_empty_blocks(2);
12427 assert!(tip >= reduction_height);
12428 let txids = st.create_proposed_expecting(&proposal, 1);
12429 let tx = st
12430 .get_tx_from_history(txids[0])
12431 .unwrap()
12432 .expect("the built transaction is in the history");
12433 assert_eq!(tx.fee_paid(), Some(pre_reduction_fee));
12434
12435 let proposal = st.propose_transfer_to(&recipient, payment_value);
12438 let target_height = BlockHeight::from(proposal.min_target_height());
12439 assert!(target_height >= reduction_height);
12440 let reduced_fee = proposal.steps().first().balance().fee_required();
12441 assert_eq!(
12442 reduced_fee,
12443 (marginal_fee(st.network(), target_height) * logical_actions).unwrap()
12444 );
12445 assert!(reduced_fee < pre_reduction_fee);
12446}
12447
12448pub fn dust_threshold_follows_marginal_fee_at_target_height<T, Dsf>(dsf: Dsf, cache: impl TestCache)
12455where
12456 T: ShieldedPoolTester,
12457 Dsf: DataStoreFactory,
12458{
12459 let network = nu7_activating_network();
12460 let reduction_height = network
12462 .activation_height(NetworkUpgrade::Nu7)
12463 .expect("the test network activates NU7");
12464 let mut st = TestDsl::from(
12465 TestBuilder::new()
12466 .with_network(network)
12467 .with_data_store_factory(dsf)
12468 .with_block_cache(cache)
12469 .with_account_from_sapling_activation(BlockHash([0; 32])),
12470 )
12471 .build::<T>();
12472 let account_id = st.get_account().id();
12473 let recipient = T::fvk_default_address(&T::sk_to_fvk(&T::sk(&[0xf5; 32])));
12474 let policy = ConfirmationsPolicy::MIN;
12475
12476 let large_value = Zatoshis::const_from_u64(COIN);
12480 let small_value = marginal_fee(st.network(), reduction_height - 1);
12481 assert!(small_value > marginal_fee(st.network(), reduction_height));
12482 st.add_notes_checking_balance([[large_value], [small_value]]);
12483
12484 macro_rules! assert_classified {
12487 ($uneconomic:expr, $spendable:expr) => {{
12488 let tip = st
12489 .wallet()
12490 .chain_height()
12491 .unwrap()
12492 .expect("the chain tip is known");
12493 let target_height = TargetHeight::from(tip + 1);
12494 let balance = st
12495 .get_account_balance(policy)
12496 .expect("the wallet has scanned blocks");
12497 assert_eq!(balance.uneconomic_value(), $uneconomic);
12498 assert_eq!(balance.spendable_value(), $spendable);
12499 for target_value in [
12500 TargetValue::AllFunds(MaxSpendMode::MaxSpendable),
12501 TargetValue::AtLeast(Zatoshis::const_from_u64(MAX_MONEY)),
12502 ] {
12503 let selected = T::select_spendable_notes(
12504 &st,
12505 account_id,
12506 target_value,
12507 target_height,
12508 policy,
12509 &[],
12510 )
12511 .unwrap()
12512 .iter()
12513 .map(|note| T::note_value(note.note()))
12514 .try_fold(Zatoshis::ZERO, |sum, value| sum + value)
12515 .expect("the selected value is in range");
12516 assert_eq!(
12517 selected, $spendable,
12518 "{target_value:?} at {target_height:?}"
12519 );
12520 }
12521 }};
12522 }
12523
12524 let tip = st
12527 .wallet()
12528 .chain_height()
12529 .unwrap()
12530 .expect("the chain tip is known");
12531 let blocks_to_add = u32::from(reduction_height) - 2 - u32::from(tip);
12532 let tip =
12533 st.add_empty_blocks(usize::try_from(blocks_to_add).expect("block count fits in a usize"));
12534 assert_eq!(tip, reduction_height - 2);
12535
12536 assert_classified!(small_value, large_value);
12539 assert_matches!(
12540 st.propose_standard_transfer::<Infallible>(
12541 account_id,
12542 StandardFeeRule::Zip317,
12543 policy,
12544 &recipient,
12545 large_value,
12546 None,
12547 None,
12548 T::SHIELDED_PROTOCOL,
12549 ),
12550 Err(Error::InsufficientFunds { available, .. }) if available == large_value
12551 );
12552
12553 st.add_empty_blocks(1);
12555 assert_classified!(Zatoshis::ZERO, (large_value + small_value).unwrap());
12556 let proposal = st.propose_transfer_to(&recipient, large_value);
12557 assert_eq!(
12558 BlockHeight::from(proposal.min_target_height()),
12559 reduction_height
12560 );
12561 let mut input_values = proposal
12562 .steps()
12563 .first()
12564 .shielded_inputs()
12565 .expect("the payment is funded from shielded notes")
12566 .notes()
12567 .iter()
12568 .map(|note| note.note().value())
12569 .collect::<Vec<_>>();
12570 input_values.sort();
12571 assert_eq!(input_values, vec![small_value, large_value]);
12572}
12573
12574#[cfg(feature = "orchard")]
12581pub fn canonical_crossing_fee_follows_marginal_fee_at_target_height<Dsf: DataStoreFactory>(
12582 ds_factory: Dsf,
12583 cache: impl TestCache,
12584) {
12585 let interval = AnchorBucketInterval::custom(NonZeroU32::new(12).expect("nonzero"));
12587 const FUNDING_BLOCKS: u32 = 2;
12589 let nu5_activation = TestBuilder::<(), ()>::DEFAULT_NETWORK
12590 .nu5
12591 .expect("the default test network activates NU5");
12592 let ironwood_activation = nu5_activation + FUNDING_BLOCKS;
12593 let ironwood_active_network = LocalNetwork {
12594 nu6: Some(nu5_activation),
12595 nu6_1: Some(nu5_activation),
12596 nu6_2: Some(nu5_activation),
12597 nu6_3: Some(ironwood_activation),
12598 ..TestBuilder::<(), ()>::DEFAULT_NETWORK
12599 };
12600
12601 let interval_blocks = interval.block_count().get();
12608 let pre_reduction_tip = anchor_grid(&ironwood_active_network, interval)
12609 .boundary_at_or_above(ironwood_activation)
12610 + (3 * interval_blocks + 5);
12611 let reduction_height = pre_reduction_tip + 2;
12612 let network = LocalNetwork {
12613 nu7: Some(reduction_height),
12614 ..ironwood_active_network
12615 };
12616
12617 let mut st = TestDsl::from(
12618 TestBuilder::new()
12619 .with_network(network)
12620 .with_data_store_factory(ds_factory)
12621 .with_block_cache(cache)
12622 .with_anchor_retention_interval(interval)
12623 .with_account_from_sapling_activation(BlockHash([0; 32])),
12624 )
12625 .build::<OrchardPoolTester>();
12626
12627 let account = st.test_account().cloned().unwrap();
12628 let fvk = OrchardPoolTester::test_account_fvk(&st);
12629 let recipient = OrchardPoolTester::fvk_default_address(&fvk).to_zcash_address(st.network());
12630 let zip318 = st.wallet().pool_migration_params(st.network());
12631
12632 let pre_reduction_fee = fees::canonical_crossing_fee(st.network(), reduction_height - 1)
12633 .expect("the canonical shape is a valid input to the ZIP 317 rule");
12634 let reduced_fee = fees::canonical_crossing_fee(st.network(), reduction_height)
12635 .expect("the canonical shape is a valid input to the ZIP 317 rule");
12636 assert!(reduced_fee < pre_reduction_fee);
12637
12638 let note_value = Zatoshis::const_from_u64(10_000_000);
12640 let funded = st.add_notes_checking_balance([[note_value], [note_value]]);
12641 assert_eq!(funded.first_block_height(), Some(nu5_activation));
12642 let funded_height = funded.block_height().expect("blocks were added");
12643 assert!(funded_height < ironwood_activation);
12644
12645 let not_our_fvk = OrchardPoolTester::sk_to_fvk(&OrchardPoolTester::sk(&[0xf5; 32]));
12648 let filler_count = u32::from(pre_reduction_tip) - u32::from(funded_height);
12649 for _ in 0..filler_count {
12650 st.generate_next_block(
12651 ¬_our_fvk,
12652 AddressType::DefaultExternal,
12653 Zatoshis::const_from_u64(10_000),
12654 );
12655 }
12656 st.scan_cached_blocks(funded_height + 1, filler_count as usize);
12657 assert_eq!(st.wallet().chain_height().unwrap(), Some(pre_reduction_tip));
12658
12659 let input_selector = GreedyInputSelector::new();
12660 let change_strategy =
12661 single_output_change_strategy(StandardFeeRule::Zip317, None, ShieldedPool::Orchard);
12662 let propose = |st: &mut TestState<_, _, _>| {
12663 let request = TransactionRequest::new(vec![Payment::without_memo(
12664 recipient.clone(),
12665 MAX_RESIDUAL_VALUE,
12666 )])
12667 .unwrap();
12668 st.propose_transfer(
12669 account.id(),
12670 &input_selector,
12671 &change_strategy,
12672 request,
12673 ConfirmationsPolicy::MIN,
12674 )
12675 .expect("the wallet can fund this")
12676 };
12677 macro_rules! assert_canonical_built {
12680 ($proposal:expr, $fee:expr) => {{
12681 assert_eq!($proposal.steps().len(), 1);
12682 let step = $proposal.steps().first();
12683 assert_eq!(step.balance().fee_required(), $fee);
12684 assert!(
12685 step.is_canonical_crossing(&zip318, $fee),
12686 "the payment must be recognized as a canonical crossing"
12687 );
12688 let txids = st.create_proposed_expecting(&$proposal, 1);
12689 let built = st
12690 .wallet()
12691 .get_transaction(txids[0])
12692 .unwrap()
12693 .expect("the transaction was stored");
12694 assert_eq!(
12695 built
12696 .ironwood_bundle()
12697 .expect("a crossing carries an Ironwood bundle")
12698 .actions()
12699 .len(),
12700 1,
12701 "the BUILT Ironwood bundle must have the single action of the canonical shape"
12702 );
12703 let tx = st.get_tx_from_history(txids[0]).unwrap().unwrap();
12704 assert_eq!(tx.fee_paid(), Some($fee));
12705 }};
12706 }
12707
12708 let pre_reduction_proposal = propose(&mut st);
12711 assert_eq!(
12712 BlockHeight::from(pre_reduction_proposal.min_target_height()),
12713 reduction_height - 1
12714 );
12715 let tip = st.add_empty_blocks(2);
12716 assert_eq!(tip, reduction_height);
12717 assert_canonical_built!(pre_reduction_proposal, pre_reduction_fee);
12718
12719 let reduced_proposal = propose(&mut st);
12721 assert!(BlockHeight::from(reduced_proposal.min_target_height()) >= reduction_height);
12722 assert_canonical_built!(reduced_proposal, reduced_fee);
12723}
12724
12725pub fn reorg_below_scanned_height_is_a_continuity_error<T, Dsf>(
12730 ds_factory: Dsf,
12731 cache: impl TestCache,
12732) where
12733 T: ShieldedPoolTester,
12734 Dsf: DataStoreFactory,
12735 <Dsf as DataStoreFactory>::AccountId: std::fmt::Debug,
12736{
12737 use crate::data_api::chain::error::Error as ChainError;
12738
12739 let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
12740 let (note_height, _, _) =
12741 st.add_a_single_note_checking_balance(Zatoshis::const_from_u64(500_000));
12742 let not_our_key = T::sk_to_fvk(&T::sk(&[0xf5; 32]));
12743 let filler_value = Zatoshis::const_from_u64(1000);
12744
12745 const SCANNED_BLOCKS: u32 = 10;
12746 for _ in 0..SCANNED_BLOCKS {
12747 st.generate_next_block(¬_our_key, AddressType::DefaultExternal, filler_value);
12748 }
12749 st.scan_cached_blocks(note_height + 1, SCANNED_BLOCKS as usize);
12750 let scanned_tip = st
12751 .wallet()
12752 .chain_height()
12753 .unwrap()
12754 .expect("chain tip is known");
12755
12756 const REORG_DEPTH: u32 = 3;
12759 let fork_height = scanned_tip - REORG_DEPTH;
12760 st.truncate_cache_to_height(fork_height);
12761 for _ in 0..REORG_DEPTH {
12762 st.generate_next_block(¬_our_key, AddressType::DefaultExternal, filler_value);
12763 }
12764 let stored_hash = st
12765 .wallet()
12766 .block_metadata(fork_height + 1)
12767 .unwrap()
12768 .expect("the block above the fork was scanned")
12769 .block_hash();
12770
12771 let result = st.try_scan_cached_blocks(fork_height + 1, REORG_DEPTH as usize);
12772 assert_matches!(
12773 result,
12774 Err(ChainError::Scan(ref err)) if err.is_continuity_error() && err.at_height() == fork_height + 1
12775 );
12776
12777 assert_eq!(st.wallet().chain_height().unwrap(), Some(scanned_tip));
12779 assert_eq!(
12780 st.wallet()
12781 .block_metadata(fork_height + 1)
12782 .unwrap()
12783 .map(|meta| meta.block_hash()),
12784 Some(stored_hash),
12785 );
12786}