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