zcash_client_backend/data_api/testing/
orchard.rs1use std::hash::Hash;
2
3use ::orchard::{
4 keys::{FullViewingKey, SpendingKey},
5 note_encryption::OrchardDomain,
6 tree::MerkleHashOrchard,
7};
8use incrementalmerkletree::{Address as TreeAddress, Hashable, Level, Position};
9use shardtree::error::ShardTreeError;
10
11use zcash_keys::{
12 address::{Address, UnifiedAddress},
13 keys::UnifiedSpendingKey,
14};
15use zcash_note_encryption::try_output_recovery_with_ovk;
16use zcash_primitives::transaction::Transaction;
17use zcash_protocol::{
18 ShieldedPool,
19 consensus::{self, BlockHeight},
20 memo::MemoBytes,
21 value::Zatoshis,
22};
23
24use crate::{
25 data_api::{
26 DecryptedTransaction, InputSource, TargetValue, WalletCommitmentTrees, WalletSummary,
27 WalletTest,
28 chain::{CommitmentTreeRoot, ScanSummary},
29 testing::{TestState, pool::ShieldedPoolTester},
30 wallet::{
31 ConfirmationsPolicy, TargetHeight,
32 input_selection::{LockFilter, LockedInputPolicy},
33 },
34 },
35 wallet::{Note, ReceivedNote},
36};
37
38pub struct OrchardPoolTester;
40impl ShieldedPoolTester for OrchardPoolTester {
41 const SHIELDED_PROTOCOL: ShieldedPool = ShieldedPool::Orchard;
42 type Sk = SpendingKey;
45 type Fvk = FullViewingKey;
46 type MerkleTreeHash = MerkleHashOrchard;
47 type Note = orchard::note::Note;
48
49 fn test_account_fvk<Cache, DbT: WalletTest, P: consensus::Parameters>(
50 st: &TestState<Cache, DbT, P>,
51 ) -> Self::Fvk {
52 st.test_account_orchard().unwrap().clone()
53 }
54
55 fn usk_to_sk(usk: &UnifiedSpendingKey) -> &Self::Sk {
56 usk.orchard()
57 .expect("test accounts derive their keys from a seed")
58 }
59
60 fn sk(seed: &[u8]) -> Self::Sk {
61 let mut account = zip32::AccountId::ZERO;
62 loop {
63 if let Ok(sk) = SpendingKey::from_zip32_seed(seed, 1, account) {
64 break sk;
65 }
66 account = account.next().unwrap();
67 }
68 }
69
70 fn sk_to_fvk(sk: &Self::Sk) -> Self::Fvk {
71 sk.into()
72 }
73
74 fn sk_default_address(sk: &Self::Sk) -> Address {
75 Self::fvk_default_address(&Self::sk_to_fvk(sk))
76 }
77
78 fn fvk_default_address(fvk: &Self::Fvk) -> Address {
79 UnifiedAddress::from_receivers(
80 Some(fvk.address_at(0u32, zip32::Scope::External)),
81 None,
82 None,
83 None,
84 None,
85 )
86 .unwrap()
87 .into()
88 }
89
90 fn fvks_equal(a: &Self::Fvk, b: &Self::Fvk) -> bool {
91 a == b
92 }
93
94 fn empty_tree_leaf() -> Self::MerkleTreeHash {
95 MerkleHashOrchard::empty_leaf()
96 }
97
98 fn empty_tree_root(level: Level) -> Self::MerkleTreeHash {
99 MerkleHashOrchard::empty_root(level)
100 }
101
102 fn put_subtree_roots<Cache, DbT: WalletTest + WalletCommitmentTrees, P>(
103 st: &mut TestState<Cache, DbT, P>,
104 start_index: u64,
105 roots: &[CommitmentTreeRoot<Self::MerkleTreeHash>],
106 ) -> Result<(), ShardTreeError<<DbT as WalletCommitmentTrees>::Error>> {
107 st.wallet_mut()
108 .put_orchard_subtree_roots(start_index, roots)
109 }
110
111 fn shard_root<Cache, DbT: WalletTest + WalletCommitmentTrees, P>(
112 st: &mut TestState<Cache, DbT, P>,
113 shard_index: u64,
114 ) -> Result<Self::MerkleTreeHash, ShardTreeError<<DbT as WalletCommitmentTrees>::Error>> {
115 let shard_height = crate::data_api::ORCHARD_SHARD_HEIGHT;
116 let addr = TreeAddress::from_parts(Level::from(shard_height), shard_index);
117 let end_position = Position::from((shard_index + 1) << shard_height);
118 st.wallet_mut()
119 .with_orchard_tree_mut(|tree| tree.root(addr, end_position))
120 }
121
122 fn next_subtree_index<A: Hash + Eq>(s: &WalletSummary<A>) -> u64 {
123 s.next_orchard_subtree_index()
124 }
125
126 fn note_value(note: &Self::Note) -> Zatoshis {
127 Zatoshis::const_from_u64(note.value().inner())
128 }
129
130 fn select_spendable_notes<Cache, DbT: InputSource + WalletTest, P>(
131 st: &TestState<Cache, DbT, P>,
132 account: <DbT as InputSource>::AccountId,
133 target_value: TargetValue,
134 target_height: TargetHeight,
135 confirmations_policy: ConfirmationsPolicy,
136 exclude: &[DbT::NoteRef],
137 ) -> Result<Vec<ReceivedNote<DbT::NoteRef, Self::Note>>, <DbT as InputSource>::Error> {
138 st.wallet()
139 .select_spendable_notes(
140 account,
141 target_value,
142 &[ShieldedPool::Orchard],
143 target_height,
144 confirmations_policy,
145 exclude,
146 LockFilter::Policy(&LockedInputPolicy::Exclude),
147 )
148 .map(|n| n.take_orchard())
149 }
150
151 fn select_unspent_notes<Cache, DbT: InputSource + WalletTest, P>(
152 st: &TestState<Cache, DbT, P>,
153 account: <DbT as InputSource>::AccountId,
154 target_height: TargetHeight,
155 exclude: &[DbT::NoteRef],
156 ) -> Result<Vec<ReceivedNote<DbT::NoteRef, Self::Note>>, <DbT as InputSource>::Error> {
157 st.wallet()
158 .select_unspent_notes(
159 account,
160 &[ShieldedPool::Orchard],
161 target_height,
162 exclude,
163 LockFilter::Policy(&LockedInputPolicy::Exclude),
164 )
165 .map(|n| n.take_orchard())
166 }
167
168 fn decrypted_pool_outputs_count<A>(d_tx: &DecryptedTransaction<Transaction, A>) -> usize {
169 d_tx.orchard_outputs().len()
170 }
171
172 fn with_decrypted_pool_memos<A>(
173 d_tx: &DecryptedTransaction<Transaction, A>,
174 mut f: impl FnMut(&MemoBytes),
175 ) {
176 for output in d_tx.orchard_outputs() {
177 f(output.memo());
178 }
179 }
180
181 fn try_output_recovery<P: consensus::Parameters>(
182 _params: &P,
183 _: BlockHeight,
184 tx: &Transaction,
185 fvk: &Self::Fvk,
186 ) -> Option<(Note, Address, MemoBytes)> {
187 for action in tx.orchard_bundle().unwrap().actions() {
188 let result = try_output_recovery_with_ovk(
190 &OrchardDomain::for_action(action),
191 &fvk.to_ovk(zip32::Scope::External),
192 action,
193 action.cv_net(),
194 &action.encrypted_note().out_ciphertext,
195 );
196
197 if result.is_some() {
198 return result.map(|(note, addr, memo)| {
199 (
200 Note::Orchard {
201 note,
202 pool: orchard::ValuePool::Orchard,
203 },
204 UnifiedAddress::from_receivers(Some(addr), None, None, None, None)
205 .unwrap()
206 .into(),
207 MemoBytes::from_bytes(&memo).expect("correct length"),
208 )
209 });
210 }
211 }
212
213 None
214 }
215
216 fn received_note_count(summary: &ScanSummary) -> usize {
217 summary.received_orchard_note_count()
218 }
219
220 #[cfg(feature = "pczt")]
221 fn add_proof_generation_keys(
222 pczt: pczt::Pczt,
223 _: &UnifiedSpendingKey,
224 ) -> Result<pczt::Pczt, pczt::roles::updater::SaplingError> {
225 Ok(pczt)
227 }
228
229 #[cfg(feature = "pczt")]
230 fn apply_signatures_to_pczt(
231 signer: &mut pczt::roles::signer::Signer,
232 usk: &UnifiedSpendingKey,
233 ) -> Result<(), pczt::roles::signer::Error> {
234 let sk = Self::usk_to_sk(usk);
235 use rand::{rand_core::UnwrapErr, rngs::SysRng};
236
237 let ask = orchard::keys::SpendAuthorizingKey::from(sk);
238
239 for index in 0.. {
241 match signer.sign_orchard(UnwrapErr(SysRng), index, &ask) {
242 Err(pczt::roles::signer::Error::InvalidIndex) => break,
244 Ok(())
246 | Err(pczt::roles::signer::Error::OrchardSign(
247 orchard::pczt::SignerError::WrongSpendAuthorizingKey,
248 )) => Ok(()),
249 Err(e) => Err(e),
251 }?;
252 }
253
254 Ok(())
255 }
256}