1use std::{
4 convert::Infallible,
5 marker::PhantomData,
6 ops::{Deref, DerefMut},
7};
8
9use assert_matches::assert_matches;
10use nonempty::NonEmpty;
11use zcash_keys::address::Address;
12use zcash_primitives::{block::BlockHash, transaction::fees::zip317};
13use zcash_protocol::{
14 PoolType, TxId, consensus::BlockHeight, local_consensus::LocalNetwork, value::Zatoshis,
15};
16
17use zip321::Payment;
18
19use crate::{
20 data_api::{
21 Account, AccountBalance, InputSource, WalletRead, WalletTest,
22 chain::ScanSummary,
23 testing::{
24 AddressType, DataStoreFactory, FakeCompactOutput, TestAccount, TestBuilder, TestCache,
25 TestFvk, TestState, single_output_change_strategy,
26 },
27 wallet::{
28 ConfirmationsPolicy, LockRequest,
29 input_selection::{GreedyInputSelector, SpendPolicy},
30 propose_transfer,
31 },
32 },
33 fees::StandardFeeRule,
34 proposal::Proposal,
35 wallet::{LockOwner, OutputRef, OvkPolicy},
36};
37
38use super::ShieldedPoolTester;
39
40pub struct TestDsl<T> {
42 inner: T,
45}
46
47impl<T> Deref for TestDsl<T> {
48 type Target = T;
49
50 fn deref(&self) -> &Self::Target {
51 &self.inner
52 }
53}
54
55impl<T> DerefMut for TestDsl<T> {
56 fn deref_mut(&mut self) -> &mut Self::Target {
57 &mut self.inner
58 }
59}
60
61impl<T> From<T> for TestDsl<T> {
62 fn from(inner: T) -> Self {
63 Self { inner }
64 }
65}
66
67impl<T> TestDsl<T> {
68 pub fn map<X>(self, f: impl FnOnce(T) -> X) -> TestDsl<X> {
70 f(self.inner).into()
71 }
72}
73
74impl<Cache, Dsf> TestDsl<TestBuilder<Cache, Dsf>>
76where
77 Dsf: DataStoreFactory,
78{
79 pub fn with_sapling_birthday_account(dsf: Dsf, tc: Cache) -> Self {
92 TestBuilder::new()
93 .with_data_store_factory(dsf)
94 .with_block_cache(tc)
95 .with_account_from_sapling_activation(BlockHash([0; 32]))
96 .into()
97 }
98
99 pub fn build<T: ShieldedPoolTester>(self) -> TestDsl<TestScenario<T, Cache, Dsf>> {
101 let state = self.inner.build();
102 TestScenario {
103 state,
104 _phantom: PhantomData,
105 }
106 .into()
107 }
108}
109
110pub struct TestNoteConfig<T: ShieldedPoolTester> {
113 pub value: Zatoshis,
115 pub fvk: Option<T::Fvk>,
117 pub address_type: Option<AddressType>,
119}
120
121impl<T: ShieldedPoolTester> From<Zatoshis> for TestNoteConfig<T> {
122 fn from(value: Zatoshis) -> Self {
123 TestNoteConfig {
124 value,
125 fvk: None,
126 address_type: None,
127 }
128 }
129}
130
131impl<T: ShieldedPoolTester> TestNoteConfig<T> {
132 pub fn with_address_type(mut self, address_type: AddressType) -> Self {
133 self.address_type = Some(address_type);
134 self
135 }
136
137 pub fn with_fvk(mut self, fvk: T::Fvk) -> Self {
138 self.fvk = Some(fvk);
139 self
140 }
141}
142
143pub struct AddFundsStepResult<T: ShieldedPoolTester, C: TestCache> {
144 pub block_height: BlockHeight,
145 pub insert_result: C::InsertResult,
146 pub nullifiers: Vec<<T::Fvk as TestFvk>::Nullifier>,
148}
149
150pub struct AddFundsStep<T: ShieldedPoolTester, C: TestCache> {
152 pub notes: Vec<TestNoteConfig<T>>,
153 pub results: AddFundsStepResult<T, C>,
154}
155
156pub struct AddFundsSummary<T: ShieldedPoolTester, C: TestCache> {
158 pub steps: Vec<AddFundsStep<T, C>>,
159 pub scan_summary: Option<ScanSummary>,
160}
161
162impl<T: ShieldedPoolTester, C: TestCache> Default for AddFundsSummary<T, C> {
163 fn default() -> Self {
164 Self {
165 steps: Default::default(),
166 scan_summary: None,
167 }
168 }
169}
170
171impl<T: ShieldedPoolTester, C: TestCache> AddFundsSummary<T, C> {
172 pub fn first_block_height(&self) -> Option<BlockHeight> {
174 self.steps.first().map(|step| step.results.block_height)
175 }
176
177 pub fn block_height(&self) -> Option<BlockHeight> {
180 self.steps.last().map(|step| step.results.block_height)
181 }
182}
183
184#[repr(transparent)]
185pub struct TestScenario<T: ShieldedPoolTester, Cache, Dsf: DataStoreFactory> {
186 state: TestState<Cache, Dsf::DataStore, LocalNetwork>,
188 _phantom: PhantomData<T>,
189}
190
191impl<T, C, D> Deref for TestScenario<T, C, D>
192where
193 T: ShieldedPoolTester,
194 D: DataStoreFactory,
195{
196 type Target = TestState<C, D::DataStore, LocalNetwork>;
197
198 fn deref(&self) -> &Self::Target {
199 &self.state
200 }
201}
202
203impl<T, C, D> DerefMut for TestScenario<T, C, D>
204where
205 T: ShieldedPoolTester,
206 D: DataStoreFactory,
207{
208 fn deref_mut(&mut self) -> &mut Self::Target {
209 &mut self.state
210 }
211}
212
213impl<Cache, Dsf, T> TestScenario<T, Cache, Dsf>
215where
216 T: ShieldedPoolTester,
217 Cache: TestCache,
218 Dsf: DataStoreFactory,
219{
220 pub fn get_account_balance(
225 &self,
226 confirmations_policy: ConfirmationsPolicy,
227 ) -> Option<AccountBalance> {
228 let account = self.get_account();
229 let binding = self
230 .wallet()
231 .get_wallet_summary(confirmations_policy)
232 .unwrap()?;
233 let balance = binding.account_balances().get(&account.id())?;
234 Some(*balance)
235 }
236
237 pub fn add_a_single_note_checking_balance(
255 &mut self,
256 note: impl Into<TestNoteConfig<T>>,
257 ) -> (
258 BlockHeight,
259 Cache::InsertResult,
260 <T::Fvk as TestFvk>::Nullifier,
261 ) {
262 let mut summary = self.add_notes_checking_balance([[note]]);
263 let res = summary.steps.pop().unwrap().results;
264 (res.block_height, res.insert_result, res.nullifiers[0])
265 }
266
267 fn scanned_block_height(&self) -> BlockHeight {
268 self.wallet()
269 .block_max_scanned()
270 .unwrap()
271 .map(|meta| meta.block_height())
272 .unwrap_or_else(|| BlockHeight::from_u32(0))
273 }
274
275 pub fn add_empty_blocks(&mut self, n: usize) -> BlockHeight {
279 let mut out_height = self.scanned_block_height();
280 for _ in 0..n {
281 let (h, _) = self.generate_empty_block();
282 out_height = h;
283 self.scan_cached_blocks(h, 1);
284 }
285 out_height
286 }
287
288 pub fn get_account(&self) -> TestAccount<Dsf::Account> {
290 self.test_account().expect("not configured").clone()
291 }
292
293 fn make_fake_output(&self, note_config: &TestNoteConfig<T>) -> FakeCompactOutput<T::Fvk> {
295 let TestNoteConfig {
296 value,
297 fvk,
298 address_type,
299 } = note_config;
300 FakeCompactOutput::new(
301 fvk.clone().unwrap_or_else(|| T::test_account_fvk(self)),
302 address_type.unwrap_or(AddressType::DefaultExternal),
303 *value,
304 )
305 }
306
307 pub fn add_notes_checking_balance(
327 &mut self,
328 blocks: impl IntoIterator<Item = impl IntoIterator<Item = impl Into<TestNoteConfig<T>>>>,
329 ) -> AddFundsSummary<T, Cache> {
330 let mut from_height = None;
331 let mut current_height = self.scanned_block_height();
332 let mut limit = 0;
333 let account = self.get_account();
334 let starting_balance = self
335 .get_account_balance(ConfirmationsPolicy::MIN)
336 .map(|b| b.total())
337 .unwrap_or(Zatoshis::ZERO);
338 let mut expected_total = starting_balance;
339 let mut summary = AddFundsSummary::default();
340 let mut note_values = vec![];
341 for notes in blocks.into_iter() {
342 let (fake_outputs, note_configs): (Vec<_>, Vec<_>) = notes
346 .into_iter()
347 .map(|into_note_config| {
348 let note_config = into_note_config.into();
349 note_values.push(note_config.value);
350 (self.make_fake_output(¬e_config), note_config)
351 })
352 .unzip();
353 let step_result = if fake_outputs.is_empty() {
354 let (h, r) = self.generate_empty_block();
355 AddFundsStepResult {
356 block_height: h,
357 insert_result: r,
358 nullifiers: vec![],
359 }
360 } else {
361 let (h, r, n) = self.generate_next_block_multi(&fake_outputs);
362 AddFundsStepResult {
363 block_height: h,
364 insert_result: r,
365 nullifiers: n,
366 }
367 };
368 current_height = step_result.block_height;
369 if from_height.is_none() {
370 from_height = Some(current_height);
371 }
372 summary.steps.push(AddFundsStep {
373 notes: note_configs,
374 results: step_result,
375 });
376 limit += 1;
377 }
378 if let Some(from_height) = from_height {
379 summary.scan_summary = Some(self.scan_cached_blocks(from_height, limit));
380 }
381
382 let uneconomic_threshold = zip317::marginal_fee(self.network(), current_height + 1);
386 for value in note_values {
387 if value > uneconomic_threshold {
388 expected_total = (expected_total + value).unwrap();
389 }
390 }
391
392 assert_eq!(
394 self.get_total_balance(account.id()),
395 expected_total,
396 "Unexpected total balance"
397 );
398 assert_eq!(
399 self.wallet()
400 .block_max_scanned()
401 .unwrap()
402 .unwrap()
403 .block_height(),
404 current_height
405 );
406 assert_eq!(
407 self.get_spendable_balance(account.id(), ConfirmationsPolicy::MIN),
408 expected_total
409 );
410
411 summary
412 }
413
414 pub fn propose_transfer_to(
421 &mut self,
422 to: &Address,
423 amount: Zatoshis,
424 ) -> Proposal<StandardFeeRule, <Dsf::DataStore as InputSource>::NoteRef> {
425 let account_id = self.get_account().id();
426 self.propose_standard_transfer::<Infallible>(
427 account_id,
428 StandardFeeRule::Zip317,
429 ConfirmationsPolicy::MIN,
430 to,
431 amount,
432 None,
433 None,
434 T::SHIELDED_PROTOCOL,
435 )
436 .unwrap()
437 }
438
439 pub fn spend_to(&mut self, to: &Address, amount: Zatoshis) -> TxId {
446 let account = self.get_account();
447 let proposal = self.propose_transfer_to(to, amount);
448 self.create_proposed_transactions::<Infallible, _, Infallible, _>(
449 account.usk(),
450 OvkPolicy::Sender,
451 &proposal,
452 )
453 .unwrap()[0]
454 }
455
456 pub fn create_proposed_expecting(
467 &mut self,
468 proposal: &Proposal<StandardFeeRule, <Dsf::DataStore as InputSource>::NoteRef>,
469 expected: usize,
470 ) -> NonEmpty<TxId> {
471 let account = self.get_account();
472 let result = self.create_proposed_transactions::<Infallible, _, Infallible, _>(
473 account.usk(),
474 OvkPolicy::Sender,
475 proposal,
476 );
477 assert_matches!(&result, Ok(txids) if txids.len() == expected);
478 result.unwrap()
479 }
480
481 pub fn expect_insufficient_funds(
487 &mut self,
488 to: &Address,
489 amount: Zatoshis,
490 available: Zatoshis,
491 required: Zatoshis,
492 ) {
493 self.expect_insufficient_funds_with(
494 to,
495 amount,
496 ConfirmationsPolicy::MIN,
497 available,
498 required,
499 )
500 }
501
502 pub fn expect_insufficient_funds_with(
505 &mut self,
506 to: &Address,
507 amount: Zatoshis,
508 confirmations_policy: ConfirmationsPolicy,
509 available: Zatoshis,
510 required: Zatoshis,
511 ) {
512 let account_id = self.get_account().id();
513 assert_matches!(
514 self.propose_standard_transfer::<Infallible>(
515 account_id,
516 StandardFeeRule::Zip317,
517 confirmations_policy,
518 to,
519 amount,
520 None,
521 None,
522 T::SHIELDED_PROTOCOL,
523 ),
524 Err(crate::data_api::error::Error::InsufficientFunds { available: a, required: r })
525 if a == available && r == required,
526 "expected InsufficientFunds (available={}, required={}) proposing {}",
527 u64::from(available),
528 u64::from(required),
529 u64::from(amount)
530 );
531 }
532
533 pub fn mine_decoy_block(&mut self, seed: u8, value: Zatoshis) -> BlockHeight {
537 let (h, _, _) = self.generate_next_block(
538 &T::sk_to_fvk(&T::sk(&[seed; 32])),
539 AddressType::DefaultExternal,
540 value,
541 );
542 h
543 }
544
545 pub fn mine_decoy_blocks(
548 &mut self,
549 seeds: impl IntoIterator<Item = u8>,
550 value: Zatoshis,
551 ) -> Option<BlockHeight> {
552 let mut last = None;
553 for seed in seeds {
554 last = Some(self.mine_decoy_block(seed, value));
555 }
556 last
557 }
558
559 pub fn sole_note_ref(&self) -> OutputRef {
562 let notes = self.wallet().get_notes(T::SHIELDED_PROTOCOL).unwrap();
563 assert_eq!(notes.len(), 1);
564 let note = ¬es[0];
565 OutputRef::new(
566 *note.txid(),
567 PoolType::Shielded(note.note().pool()),
568 u32::from(note.output_index()),
569 )
570 }
571
572 pub fn note_ref_by_value(&self, value: Zatoshis) -> OutputRef {
578 let notes = self.wallet().get_notes(T::SHIELDED_PROTOCOL).unwrap();
579 let note = notes
580 .iter()
581 .find(|n| n.note().value() == value)
582 .expect("a note with the requested value exists");
583 OutputRef::new(
584 *note.txid(),
585 PoolType::Shielded(note.note().pool()),
586 u32::from(note.output_index()),
587 )
588 }
589
590 pub fn propose_locking_transfer(
601 &mut self,
602 to: &Address,
603 amount: Zatoshis,
604 owner: LockOwner,
605 lock_for_blocks: u32,
606 ) -> Proposal<StandardFeeRule, <Dsf::DataStore as InputSource>::NoteRef> {
607 let account_id = self.get_account().id();
608 let input_selector = GreedyInputSelector::new();
609 let change_strategy =
610 single_output_change_strategy(StandardFeeRule::Zip317, None, T::SHIELDED_PROTOCOL);
611 let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
612 to.to_zcash_address(self.network()),
613 amount,
614 )])
615 .unwrap();
616 let network = *self.network();
617 propose_transfer::<_, _, _, _, Infallible>(
618 self.wallet_mut(),
619 &network,
620 account_id,
621 &input_selector,
622 &change_strategy,
623 request,
624 ConfirmationsPolicy::MIN,
625 &SpendPolicy::default(),
626 Some(LockRequest::new(owner, lock_for_blocks)),
627 None,
628 )
629 .unwrap()
630 }
631}