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