1use std::collections::{HashMap, HashSet};
2use std::convert::TryFrom;
3use std::fmt;
4use std::hash::Hash;
5
6use incrementalmerkletree::Retention;
7use sapling::note_encryption::SaplingDomain;
8use subtle::ConditionallySelectable;
9use tracing::{debug, trace, warn};
10
11use zcash_note_encryption::{Domain, batch};
12use zcash_primitives::{
13 block::{Block, BlockHeader},
14 transaction::{Transaction, components::sapling::zip212_enforcement},
15};
16use zcash_protocol::{
17 ShieldedPool,
18 consensus::{self, BlockHeight, NetworkUpgrade, TxIndex},
19};
20
21use super::{
22 PositionTracker, ScanError, ScanningKeys, SpendIdentifiers, find_received, find_spent,
23};
24
25#[cfg(feature = "transparent-inputs")]
26use super::find_transparent_spends;
27
28#[doc(inline)]
29pub use super::ScanBlockError;
30use crate::{
31 data_api::{
32 BlockMetadata, ScannedBlock, ScannedBundles, ll::wallet::detect_wallet_transparent_outputs,
33 },
34 scan::{Batch, BatchReceiver, BatchRunner, DecryptedOutput, FullDecryptor, Tasks},
35 wallet::{WalletSpend, WalletTx},
36};
37
38#[cfg(feature = "orchard")]
39use orchard::{note_encryption::OrchardDomain, primitives::redpallas, tree::MerkleHashOrchard};
40
41#[cfg(feature = "orchard")]
42use super::IronwoodDomain;
43
44#[cfg(not(feature = "orchard"))]
45use std::marker::PhantomData;
46
47#[cfg(feature = "transparent-inputs")]
48use {
49 crate::wallet::transparent_address_observations, transparent::address::TransparentAddress,
50 zcash_keys::keys::transparent::TransparentKeyScope,
51 zcash_primitives::transaction::coinbase::is_coinbase,
52};
53
54pub(crate) const DEFAULT_BATCH_SIZE_THRESHOLD: usize = 200;
56
57type TaggedSaplingBatch<IvkTag> = Batch<
58 IvkTag,
59 SaplingDomain,
60 sapling::bundle::OutputDescription<sapling::bundle::GrothProofBytes>,
61 FullDecryptor,
62>;
63type TaggedSaplingBatchRunner<IvkTag, Tasks> = BatchRunner<
64 IvkTag,
65 SaplingDomain,
66 sapling::bundle::OutputDescription<sapling::bundle::GrothProofBytes>,
67 FullDecryptor,
68 Tasks,
69>;
70
71#[cfg(feature = "orchard")]
72type TaggedOrchardBatch<IvkTag> = Batch<
73 IvkTag,
74 OrchardDomain,
75 orchard::Action<redpallas::Signature<redpallas::SpendAuth>>,
76 FullDecryptor,
77>;
78#[cfg(feature = "orchard")]
79type TaggedOrchardBatchRunner<IvkTag, Tasks> = BatchRunner<
80 IvkTag,
81 OrchardDomain,
82 orchard::Action<redpallas::Signature<redpallas::SpendAuth>>,
83 FullDecryptor,
84 Tasks,
85>;
86
87#[cfg(feature = "orchard")]
91type TaggedIronwoodBatch<IvkTag> = Batch<
92 IvkTag,
93 IronwoodDomain,
94 orchard::Action<redpallas::Signature<redpallas::SpendAuth>>,
95 FullDecryptor,
96>;
97#[cfg(feature = "orchard")]
98type TaggedIronwoodBatchRunner<IvkTag, Tasks> = BatchRunner<
99 IvkTag,
100 IronwoodDomain,
101 orchard::Action<redpallas::Signature<redpallas::SpendAuth>>,
102 FullDecryptor,
103 Tasks,
104>;
105
106pub(crate) trait SaplingTasks<IvkTag>: Tasks<TaggedSaplingBatch<IvkTag>> {}
107impl<IvkTag, T: Tasks<TaggedSaplingBatch<IvkTag>>> SaplingTasks<IvkTag> for T {}
108
109#[cfg(not(feature = "orchard"))]
110pub(crate) trait OrchardTasks<IvkTag> {}
111#[cfg(not(feature = "orchard"))]
112impl<IvkTag, T> OrchardTasks<IvkTag> for T {}
113
114#[cfg(feature = "orchard")]
115pub(crate) trait OrchardTasks<IvkTag>: Tasks<TaggedOrchardBatch<IvkTag>> {}
116#[cfg(feature = "orchard")]
117impl<IvkTag, T: Tasks<TaggedOrchardBatch<IvkTag>>> OrchardTasks<IvkTag> for T {}
118
119#[cfg(not(feature = "orchard"))]
120pub(crate) trait IronwoodTasks<IvkTag> {}
121#[cfg(not(feature = "orchard"))]
122impl<IvkTag, T> IronwoodTasks<IvkTag> for T {}
123
124#[cfg(feature = "orchard")]
125pub(crate) trait IronwoodTasks<IvkTag>: Tasks<TaggedIronwoodBatch<IvkTag>> {}
126#[cfg(feature = "orchard")]
127impl<IvkTag, T: Tasks<TaggedIronwoodBatch<IvkTag>>> IronwoodTasks<IvkTag> for T {}
128
129pub(crate) struct BatchRunners<
130 IvkTag,
131 TS: SaplingTasks<IvkTag>,
132 TO: OrchardTasks<IvkTag>,
133 TI: IronwoodTasks<IvkTag>,
134> {
135 sapling: TaggedSaplingBatchRunner<IvkTag, TS>,
136 #[cfg(feature = "orchard")]
137 orchard: TaggedOrchardBatchRunner<IvkTag, TO>,
138 #[cfg(feature = "orchard")]
139 ironwood: TaggedIronwoodBatchRunner<IvkTag, TI>,
140 #[cfg(not(feature = "orchard"))]
141 orchard: PhantomData<(TO, TI)>,
142}
143
144impl<IvkTag, TS, TO, TI> BatchRunners<IvkTag, TS, TO, TI>
145where
146 IvkTag: Clone + Send + 'static,
147 TS: SaplingTasks<IvkTag>,
148 TO: OrchardTasks<IvkTag>,
149 TI: IronwoodTasks<IvkTag>,
150{
151 pub(crate) fn for_keys<AccountId>(
157 sapling_batch_size_threshold: usize,
158 #[cfg(feature = "orchard")] orchard_batch_size_threshold: usize,
159 #[cfg(feature = "orchard")] ironwood_batch_size_threshold: usize,
160 scanning_keys: &ScanningKeys<AccountId, IvkTag>,
161 ) -> Self {
162 BatchRunners {
163 sapling: BatchRunner::new(
164 sapling_batch_size_threshold,
165 scanning_keys
166 .sapling()
167 .iter()
168 .map(|(id, key)| (id.clone(), key.prepare())),
169 ),
170 #[cfg(feature = "orchard")]
171 orchard: BatchRunner::new(
172 orchard_batch_size_threshold,
173 scanning_keys
174 .orchard()
175 .iter()
176 .map(|(id, key)| (id.clone(), key.prepare())),
177 ),
178 #[cfg(feature = "orchard")]
179 ironwood: BatchRunner::new(
180 ironwood_batch_size_threshold,
181 scanning_keys
182 .ironwood()
183 .iter()
184 .map(|(id, key)| (id.clone(), key.prepare())),
185 ),
186 #[cfg(not(feature = "orchard"))]
187 orchard: PhantomData,
188 }
189 }
190
191 #[tracing::instrument(skip_all, fields(height = u32::from(height)))]
201 pub(crate) fn process_transaction<P>(
202 &mut self,
203 params: &P,
204 height: BlockHeight,
205 tx: Transaction,
206 ) -> PendingBatch<IvkTag>
207 where
208 P: consensus::Parameters + Send + 'static,
209 IvkTag: Copy + Send + 'static,
210 {
211 let zip212_enforcement = zip212_enforcement(params, height);
212
213 let sapling_batch = tx.sapling_bundle().map(|bundle| {
214 self.sapling.process_outputs(
215 |_| SaplingDomain::new(zip212_enforcement),
216 bundle.shielded_outputs().iter().cloned(),
217 )
218 });
219
220 #[cfg(feature = "orchard")]
221 let orchard_batch = tx.orchard_bundle().map(|bundle| {
222 self.orchard
223 .process_outputs(OrchardDomain::for_action, bundle.actions().iter().cloned())
224 });
225
226 #[cfg(feature = "orchard")]
227 let ironwood_batch = tx.ironwood_bundle().map(|bundle| {
228 self.ironwood
229 .process_outputs(IronwoodDomain::for_action, bundle.actions().iter().cloned())
230 });
231
232 PendingBatch {
233 tx,
234 sapling_batch,
235 #[cfg(feature = "orchard")]
236 orchard_batch,
237 #[cfg(feature = "orchard")]
238 ironwood_batch,
239 }
240 }
241
242 pub(crate) fn flush(&mut self) {
246 self.sapling.flush();
247 #[cfg(feature = "orchard")]
248 self.orchard.flush();
249 #[cfg(feature = "orchard")]
250 self.ironwood.flush();
251 }
252}
253
254pub(crate) struct PendingBatch<IvkTag> {
256 tx: Transaction,
257 sapling_batch: Option<BatchReceiver<IvkTag, SaplingDomain, <SaplingDomain as Domain>::Memo>>,
258 #[cfg(feature = "orchard")]
259 orchard_batch: Option<BatchReceiver<IvkTag, OrchardDomain, <OrchardDomain as Domain>::Memo>>,
260 #[cfg(feature = "orchard")]
261 ironwood_batch: Option<BatchReceiver<IvkTag, IronwoodDomain, <IronwoodDomain as Domain>::Memo>>,
262}
263
264impl<IvkTag> PendingBatch<IvkTag> {
265 pub(crate) fn wait(self) -> BatchResult<IvkTag> {
267 BatchResult {
268 tx: self.tx,
269 sapling: self
270 .sapling_batch
271 .map(|b| b.into_results())
272 .unwrap_or_default(),
273 #[cfg(feature = "orchard")]
274 orchard: self
275 .orchard_batch
276 .map(|b| b.into_results())
277 .unwrap_or_default(),
278 #[cfg(feature = "orchard")]
279 ironwood: self
280 .ironwood_batch
281 .map(|b| b.into_results())
282 .unwrap_or_default(),
283 }
284 }
285
286 #[cfg(feature = "sync-decryptor")]
291 pub(crate) async fn wait_async(self) -> BatchResult<IvkTag> {
292 let sapling = match self.sapling_batch {
293 Some(b) => b.into_results_async().await,
294 None => HashMap::new(),
295 };
296 #[cfg(feature = "orchard")]
297 let orchard = match self.orchard_batch {
298 Some(b) => b.into_results_async().await,
299 None => HashMap::new(),
300 };
301 #[cfg(feature = "orchard")]
302 let ironwood = match self.ironwood_batch {
303 Some(b) => b.into_results_async().await,
304 None => HashMap::new(),
305 };
306 BatchResult {
307 tx: self.tx,
308 sapling,
309 #[cfg(feature = "orchard")]
310 orchard,
311 #[cfg(feature = "orchard")]
312 ironwood,
313 }
314 }
315}
316
317pub struct BatchResult<IvkTag> {
322 tx: Transaction,
323 sapling:
324 HashMap<usize, DecryptedOutput<IvkTag, SaplingDomain, <SaplingDomain as Domain>::Memo>>,
325 #[cfg(feature = "orchard")]
326 orchard:
327 HashMap<usize, DecryptedOutput<IvkTag, OrchardDomain, <OrchardDomain as Domain>::Memo>>,
328 #[cfg(feature = "orchard")]
329 ironwood:
330 HashMap<usize, DecryptedOutput<IvkTag, IronwoodDomain, <IronwoodDomain as Domain>::Memo>>,
331}
332
333pub fn decrypt_block<P, AccountId, IvkTag>(
342 params: &P,
343 block: Block,
344 scanning_keys: &ScanningKeys<AccountId, IvkTag>,
345) -> (BlockHeader, Vec<BatchResult<IvkTag>>)
346where
347 P: consensus::Parameters + Send + 'static,
348 IvkTag: Copy + Send + 'static,
349{
350 let mut runners = BatchRunners::<_, (), (), ()>::for_keys(
351 DEFAULT_BATCH_SIZE_THRESHOLD,
352 #[cfg(feature = "orchard")]
353 DEFAULT_BATCH_SIZE_THRESHOLD,
354 #[cfg(feature = "orchard")]
355 DEFAULT_BATCH_SIZE_THRESHOLD,
356 scanning_keys,
357 );
358
359 let mined_height = block.claimed_height();
360 let (header, vtx) = block.into_parts();
361 let batches = vtx
362 .into_iter()
363 .map(|tx| runners.process_transaction(params, mined_height, tx))
364 .collect::<Vec<_>>();
365
366 runners.flush();
370
371 let vtx = batches
372 .into_iter()
373 .map(|batch| batch.wait())
374 .collect::<Vec<_>>();
375
376 (header, vtx)
377}
378
379#[tracing::instrument(skip_all, fields(height = u32::from(height)))]
398#[allow(clippy::too_many_arguments)]
399pub fn scan_block<P, AccountId, IvkTag, E>(
400 params: &P,
401 height: BlockHeight,
402 header: &BlockHeader,
403 vtx: Vec<BatchResult<IvkTag>>,
404 scanning_keys: &ScanningKeys<AccountId, IvkTag>,
405 spend_ids: &SpendIdentifiers<AccountId>,
406 prior_block_metadata: Option<&BlockMetadata>,
407 #[cfg(feature = "transparent-inputs")] find_account_for_address: impl Fn(
408 &TransparentAddress,
409 ) -> Result<
410 Option<(AccountId, Option<TransparentKeyScope>)>,
411 E,
412 >,
413) -> Result<ScannedBlock<AccountId>, ScanBlockError<E>>
414where
415 P: consensus::Parameters + Send + 'static,
416 AccountId: Default + fmt::Debug + Ord + Hash + ConditionallySelectable + Send + Sync + 'static,
417 IvkTag: Copy + std::hash::Hash + Eq + Send + 'static,
418{
419 fn check_hash_continuity(
420 height: BlockHeight,
421 header: &BlockHeader,
422 prior_block_metadata: Option<&BlockMetadata>,
423 ) -> Option<ScanError> {
424 if let Some(prev) = prior_block_metadata {
425 if height != prev.block_height() + 1 {
426 debug!(
427 "Block height discontinuity at {:?}, previous was {:?} ",
428 height,
429 prev.block_height()
430 );
431 return Some(ScanError::BlockHeightDiscontinuity {
432 prev_height: prev.block_height(),
433 new_height: height,
434 });
435 }
436
437 if header.prev_block != prev.block_hash() {
438 debug!("Block hash discontinuity at {:?}", height);
439 return Some(ScanError::PrevHashMismatch { at_height: height });
440 }
441 }
442
443 None
444 }
445
446 if let Some(scan_error) = check_hash_continuity(height, header, prior_block_metadata) {
447 return Err(scan_error.into());
448 }
449
450 trace!("Block continuity okay at {:?}", height);
451
452 let cur_hash = header.hash();
453 let zip212_enforcement = zip212_enforcement(params, height);
454
455 let mut pos_tracker = PositionTracker::for_block(params, height, &vtx, prior_block_metadata)?;
456
457 let mut wtxs: Vec<WalletTx<AccountId>> = vec![];
458
459 let mut sapling_nullifier_map = Vec::with_capacity(vtx.len());
460 let mut sapling_note_commitments: Vec<(sapling::Node, Retention<BlockHeight>)> = vec![];
461
462 #[cfg(feature = "orchard")]
463 let mut orchard_nullifier_map = Vec::with_capacity(vtx.len());
464 #[cfg(feature = "orchard")]
465 let mut orchard_note_commitments: Vec<(MerkleHashOrchard, Retention<BlockHeight>)> = vec![];
466
467 #[cfg(feature = "orchard")]
468 let mut ironwood_nullifier_map = Vec::with_capacity(vtx.len());
469 #[cfg(feature = "orchard")]
470 let mut ironwood_note_commitments: Vec<(MerkleHashOrchard, Retention<BlockHeight>)> = vec![];
471
472 #[cfg(feature = "transparent-inputs")]
473 let mut transparent_spend_map = Vec::with_capacity(vtx.len());
474
475 for (tx_index, batch) in vtx.into_iter().enumerate() {
476 let BatchResult {
477 tx,
478 sapling: sapling_decrypted,
479 #[cfg(feature = "orchard")]
480 orchard: orchard_decrypted,
481 #[cfg(feature = "orchard")]
482 ironwood: ironwood_decrypted,
483 } = batch;
484 let txid = tx.txid();
485 let tx_index =
486 TxIndex::try_from(tx_index).expect("Cannot fit more than 2^16 transactions in a block");
487
488 let (sapling_spends, sapling_unlinked_nullifiers) = tx
489 .sapling_bundle()
490 .map(|bundle| {
491 find_spent(
492 bundle.shielded_spends(),
493 spend_ids.shielded().sapling(),
494 |spend| *spend.nullifier(),
495 WalletSpend::from_parts,
496 )
497 })
498 .unwrap_or_default();
499
500 sapling_nullifier_map.push((tx_index, txid, sapling_unlinked_nullifiers));
501
502 #[cfg(feature = "orchard")]
503 let orchard_spends = {
504 let (orchard_spends, orchard_unlinked_nullifiers) = tx
505 .orchard_bundle()
506 .map(|bundle| {
507 find_spent(
508 bundle.actions().iter(),
509 spend_ids.shielded().orchard(),
510 |action| *action.nullifier(),
511 WalletSpend::from_parts,
512 )
513 })
514 .unwrap_or_default();
515 orchard_nullifier_map.push((tx_index, txid, orchard_unlinked_nullifiers));
516 orchard_spends
517 };
518
519 #[cfg(feature = "orchard")]
520 let ironwood_spends = {
521 let (ironwood_spends, ironwood_unlinked_nullifiers) = tx
522 .ironwood_bundle()
523 .map(|bundle| {
524 find_spent(
525 bundle.actions().iter(),
526 spend_ids.shielded().ironwood(),
527 |action| *action.nullifier(),
528 WalletSpend::from_parts,
529 )
530 })
531 .unwrap_or_default();
532 ironwood_nullifier_map.push((tx_index, txid, ironwood_unlinked_nullifiers));
533 ironwood_spends
534 };
535
536 #[cfg(feature = "transparent-inputs")]
541 let (transparent_spends, unlinked_prevouts) = tx
542 .transparent_bundle()
543 .filter(|_| !is_coinbase(&tx))
544 .map(|bundle| {
545 find_transparent_spends(
546 bundle.vin.iter().map(|txin| txin.prevout().clone()),
547 spend_ids.transparent(),
548 )
549 })
550 .unwrap_or_default();
551
552 #[cfg(feature = "transparent-inputs")]
553 transparent_spend_map.push((tx_index, txid, unlinked_prevouts));
554
555 let spent_from_accounts = sapling_spends.iter().map(|spend| spend.account_id());
557 #[cfg(feature = "transparent-inputs")]
558 let spent_from_accounts =
559 spent_from_accounts.chain(transparent_spends.iter().map(|spend| spend.account_id()));
560 #[cfg(feature = "orchard")]
561 let spent_from_accounts =
562 spent_from_accounts.chain(orchard_spends.iter().map(|spend| spend.account_id()));
563 #[cfg(feature = "orchard")]
564 let spent_from_accounts =
565 spent_from_accounts.chain(ironwood_spends.iter().map(|spend| spend.account_id()));
566 let spent_from_accounts = spent_from_accounts.copied().collect::<HashSet<_>>();
567
568 let funding_account = spent_from_accounts.iter().min().copied();
572 if spent_from_accounts.len() > 1 {
573 warn!(
574 "More than one wallet account detected as funding transaction {:?}, selecting {:?}",
575 txid,
576 funding_account
577 .expect("funding_account is Some when spent_from_accounts is nonempty")
578 )
579 }
580
581 let transparent_outputs = detect_wallet_transparent_outputs(
582 params,
583 &tx,
584 Some(height),
585 funding_account,
586 #[cfg(feature = "transparent-inputs")]
587 &find_account_for_address,
588 )
589 .map_err(ScanBlockError::AddressLookup)?;
590
591 #[cfg(feature = "transparent-inputs")]
592 let has_transparent = !(transparent_spends.is_empty() && transparent_outputs.is_empty());
593 #[cfg(not(feature = "transparent-inputs"))]
594 let has_transparent = !transparent_outputs.is_empty();
595
596 let (sapling_outputs, mut sapling_nc) = tx
597 .sapling_bundle()
598 .map(|bundle| {
599 find_received(
600 height,
601 pos_tracker.tx_contains_last_sapling_outputs_in_block(&tx),
602 txid,
603 |output_idx| pos_tracker.sapling_note_position(output_idx),
604 &scanning_keys.sapling,
605 &spent_from_accounts,
606 &bundle
607 .shielded_outputs()
608 .iter()
609 .map(|output| (SaplingDomain::new(zip212_enforcement), output.clone()))
610 .collect::<Vec<_>>(),
611 Some(move |_| sapling_decrypted),
612 batch::try_note_decryption,
613 |output| sapling::Node::from_cmu(output.cmu()),
614 |note| note,
615 )
616 })
617 .unwrap_or_default();
618 sapling_note_commitments.append(&mut sapling_nc);
619 let has_sapling = !(sapling_spends.is_empty() && sapling_outputs.is_empty());
620
621 #[cfg(feature = "orchard")]
622 let (orchard_outputs, mut orchard_nc) = tx
623 .orchard_bundle()
624 .map(|bundle| {
625 find_received(
626 height,
627 pos_tracker.tx_contains_last_orchard_actions_in_block(&tx),
628 txid,
629 |output_idx| pos_tracker.orchard_note_position(output_idx),
630 &scanning_keys.orchard,
631 &spent_from_accounts,
632 &bundle
633 .actions()
634 .iter()
635 .map(|action| (OrchardDomain::for_action(action), action.clone()))
636 .collect::<Vec<_>>(),
637 Some(move |_| orchard_decrypted),
638 batch::try_note_decryption,
639 |action| MerkleHashOrchard::from_cmx(action.cmx()),
640 |note| (note, orchard::ValuePool::Orchard),
641 )
642 })
643 .unwrap_or_default();
644 #[cfg(feature = "orchard")]
645 orchard_note_commitments.append(&mut orchard_nc);
646
647 #[cfg(feature = "orchard")]
648 let (ironwood_outputs, mut ironwood_nc) = tx
649 .ironwood_bundle()
650 .map(|bundle| {
651 find_received(
652 height,
653 pos_tracker.tx_contains_last_ironwood_actions_in_block(&tx),
654 txid,
655 |output_idx| pos_tracker.ironwood_note_position(output_idx),
656 &scanning_keys.ironwood,
657 &spent_from_accounts,
658 &bundle
659 .actions()
660 .iter()
661 .map(|action| (IronwoodDomain::for_action(action), action.clone()))
662 .collect::<Vec<_>>(),
663 Some(move |_| ironwood_decrypted),
664 batch::try_note_decryption,
665 |action| MerkleHashOrchard::from_cmx(action.cmx()),
666 |note| (note, orchard::ValuePool::Ironwood),
667 )
668 })
669 .unwrap_or_default();
670 #[cfg(feature = "orchard")]
671 ironwood_note_commitments.append(&mut ironwood_nc);
672
673 #[cfg(feature = "orchard")]
674 let has_orchard = !(orchard_spends.is_empty() && orchard_outputs.is_empty());
675 #[cfg(not(feature = "orchard"))]
676 let has_orchard = false;
677
678 #[cfg(feature = "orchard")]
679 let has_ironwood = !(ironwood_spends.is_empty() && ironwood_outputs.is_empty());
680 #[cfg(not(feature = "orchard"))]
681 let has_ironwood = false;
682
683 if has_transparent || has_sapling || has_orchard || has_ironwood {
684 wtxs.push(WalletTx::new(
685 txid,
686 tx_index,
687 #[cfg(feature = "transparent-inputs")]
688 transparent_spends,
689 #[cfg(not(feature = "transparent-inputs"))]
690 vec![],
691 transparent_outputs,
692 #[cfg(feature = "transparent-inputs")]
701 transparent_address_observations(&tx),
702 sapling_spends,
703 sapling_outputs,
704 #[cfg(feature = "orchard")]
705 orchard_spends,
706 #[cfg(feature = "orchard")]
707 orchard_outputs,
708 #[cfg(feature = "orchard")]
709 ironwood_spends,
710 #[cfg(feature = "orchard")]
711 ironwood_outputs,
712 ));
713 }
714
715 pos_tracker.increment_over_tx(&tx);
716 }
717
718 pos_tracker.check_end_of_block_consistency()?;
719
720 Ok(ScannedBlock::from_parts(
721 height,
722 cur_hash,
723 header.time,
724 wtxs,
725 ScannedBundles::new(
726 pos_tracker.sapling_final_tree_size,
727 sapling_note_commitments,
728 sapling_nullifier_map,
729 ),
730 #[cfg(feature = "orchard")]
731 ScannedBundles::new(
732 pos_tracker.orchard_final_tree_size,
733 orchard_note_commitments,
734 orchard_nullifier_map,
735 ),
736 #[cfg(feature = "orchard")]
737 ScannedBundles::new(
738 pos_tracker.ironwood_final_tree_size,
739 ironwood_note_commitments,
740 ironwood_nullifier_map,
741 ),
742 #[cfg(feature = "transparent-inputs")]
743 transparent_spend_map,
744 ))
745}
746
747fn tree_sizes_around(
760 at_height: BlockHeight,
761 activation_height: Option<BlockHeight>,
762 prior_tree_size: Option<u32>,
763 mut output_counts: impl Iterator<Item = usize>,
764 protocol: ShieldedPool,
765) -> Result<(u32, u32), ScanError> {
766 let start_tree_size = match prior_tree_size {
767 Some(size) => size,
768 None => match activation_height {
771 Some(activation_height) if at_height >= activation_height => {
772 return Err(ScanError::TreeSizeUnknown {
773 protocol,
774 at_height,
775 });
776 }
777 _ => 0,
778 },
779 };
780
781 let overflow = || ScanError::TreeSizeOverflow {
787 protocol,
788 at_height,
789 };
790 let end_tree_size = output_counts.try_fold(start_tree_size, |acc, tx_outputs| {
791 let tx_outputs = u32::try_from(tx_outputs).map_err(|_| overflow())?;
792 acc.checked_add(tx_outputs).ok_or_else(overflow)
793 })?;
794
795 Ok((start_tree_size, end_tree_size))
796}
797
798fn sapling_output_count(tx: &Transaction) -> u32 {
803 tx.sapling_bundle().map_or(0, |b| {
804 u32::try_from(b.shielded_outputs().len()).expect("Sapling output count cannot exceed a u32")
805 })
806}
807
808#[cfg(feature = "orchard")]
813fn orchard_action_count(tx: &Transaction) -> u32 {
814 tx.orchard_bundle().map_or(0, |b| {
815 u32::try_from(b.actions().len()).expect("Orchard action count cannot exceed a u32")
816 })
817}
818
819#[cfg(feature = "orchard")]
824fn ironwood_action_count(tx: &Transaction) -> u32 {
825 tx.ironwood_bundle().map_or(0, |b| {
826 u32::try_from(b.actions().len()).expect("Ironwood action count cannot exceed a u32")
827 })
828}
829
830impl PositionTracker {
831 fn for_block<P, IvkTag>(
832 params: &P,
833 at_height: BlockHeight,
834 vtx: &[BatchResult<IvkTag>],
835 prior_block_metadata: Option<&BlockMetadata>,
836 ) -> Result<Self, ScanError>
837 where
838 P: consensus::Parameters,
839 {
840 let (sapling_prior_tree_size, sapling_final_tree_size) = tree_sizes_around(
841 at_height,
842 params.activation_height(NetworkUpgrade::Sapling),
843 prior_block_metadata.and_then(|m| m.sapling_tree_size()),
844 vtx.iter().map(|b| {
845 b.tx.sapling_bundle()
846 .map_or(0, |bd| bd.shielded_outputs().len())
847 }),
848 ShieldedPool::Sapling,
849 )?;
850
851 #[cfg(feature = "orchard")]
852 let (orchard_prior_tree_size, orchard_final_tree_size) = tree_sizes_around(
853 at_height,
854 params.activation_height(NetworkUpgrade::Nu5),
855 prior_block_metadata.and_then(|m| m.orchard_tree_size()),
856 vtx.iter()
857 .map(|b| b.tx.orchard_bundle().map_or(0, |bd| bd.actions().len())),
858 ShieldedPool::Orchard,
859 )?;
860
861 #[cfg(feature = "orchard")]
862 let (ironwood_prior_tree_size, ironwood_final_tree_size) = tree_sizes_around(
863 at_height,
864 params.activation_height(NetworkUpgrade::Nu6_3),
865 prior_block_metadata.and_then(|m| m.ironwood_tree_size()),
866 vtx.iter()
867 .map(|b| b.tx.ironwood_bundle().map_or(0, |bd| bd.actions().len())),
868 ShieldedPool::Ironwood,
869 )?;
870
871 Ok(Self {
872 sapling_tree_position: sapling_prior_tree_size,
873 sapling_final_tree_size,
874 #[cfg(feature = "orchard")]
875 orchard_tree_position: orchard_prior_tree_size,
876 #[cfg(feature = "orchard")]
877 orchard_final_tree_size,
878 #[cfg(feature = "orchard")]
879 ironwood_tree_position: ironwood_prior_tree_size,
880 #[cfg(feature = "orchard")]
881 ironwood_final_tree_size,
882 })
883 }
884
885 fn contains_last_sapling_outputs(&self, sapling_output_count: u32) -> bool {
889 self.sapling_tree_position + sapling_output_count == self.sapling_final_tree_size
890 }
891
892 fn tx_contains_last_sapling_outputs_in_block(&self, tx: &Transaction) -> bool {
893 self.contains_last_sapling_outputs(sapling_output_count(tx))
894 }
895
896 #[cfg(feature = "orchard")]
900 fn contains_last_orchard_actions(&self, orchard_action_count: u32) -> bool {
901 self.orchard_tree_position + orchard_action_count == self.orchard_final_tree_size
902 }
903
904 #[cfg(feature = "orchard")]
905 fn tx_contains_last_orchard_actions_in_block(&self, tx: &Transaction) -> bool {
906 self.contains_last_orchard_actions(orchard_action_count(tx))
907 }
908
909 #[cfg(feature = "orchard")]
913 fn contains_last_ironwood_actions(&self, ironwood_action_count: u32) -> bool {
914 self.ironwood_tree_position + ironwood_action_count == self.ironwood_final_tree_size
915 }
916
917 #[cfg(feature = "orchard")]
918 fn tx_contains_last_ironwood_actions_in_block(&self, tx: &Transaction) -> bool {
919 self.contains_last_ironwood_actions(ironwood_action_count(tx))
920 }
921
922 fn increment(
925 &mut self,
926 sapling_output_count: u32,
927 #[cfg(feature = "orchard")] orchard_action_count: u32,
928 #[cfg(feature = "orchard")] ironwood_action_count: u32,
929 ) {
930 self.sapling_tree_position += sapling_output_count;
931 #[cfg(feature = "orchard")]
932 {
933 self.orchard_tree_position += orchard_action_count;
934 self.ironwood_tree_position += ironwood_action_count;
935 }
936 }
937
938 fn increment_over_tx(&mut self, tx: &Transaction) {
939 self.increment(
940 sapling_output_count(tx),
941 #[cfg(feature = "orchard")]
942 orchard_action_count(tx),
943 #[cfg(feature = "orchard")]
944 ironwood_action_count(tx),
945 );
946 }
947
948 fn check_end_of_block_consistency(&self) -> Result<(), ScanError> {
949 assert_eq!(self.sapling_tree_position, self.sapling_final_tree_size);
953 #[cfg(feature = "orchard")]
954 assert_eq!(self.orchard_tree_position, self.orchard_final_tree_size);
955 #[cfg(feature = "orchard")]
956 assert_eq!(self.ironwood_tree_position, self.ironwood_final_tree_size);
957
958 Ok(())
959 }
960}
961
962#[cfg(test)]
963mod tests {
964 use proptest::prelude::*;
965
966 use zcash_protocol::{consensus::BlockHeight, testing::arb_protocol};
967
968 use super::{PositionTracker, tree_sizes_around};
969 use crate::scanning::ScanError;
970
971 #[cfg(feature = "transparent-inputs")]
972 use {
973 crate::{
974 data_api::BlockMetadata,
975 scanning::{
976 ScanningKeys, SpendIdentifiers,
977 full::{decrypt_block, scan_block},
978 },
979 wallet::TransparentInvolvement,
980 },
981 nonempty::NonEmpty,
982 std::convert::Infallible,
983 transparent::{
984 address::{Script, TransparentAddress},
985 bundle::{Authorized as TransparentAuthorized, Bundle, OutPoint, TxIn, TxOut},
986 },
987 zcash_keys::keys::transparent::TransparentKeyScope,
988 zcash_primitives::{
989 block::{Block, BlockHash, BlockHeaderData},
990 transaction::{Authorized, TransactionData, TxVersion},
991 },
992 zcash_protocol::{
993 consensus::{BranchId, MAIN_NETWORK},
994 value::Zatoshis,
995 },
996 zcash_script::script,
997 };
998
999 #[test]
1003 #[cfg(feature = "transparent-inputs")]
1004 fn scan_block_records_transparent_address_observations() {
1005 let mut pubkey = vec![0x02];
1007 pubkey.extend_from_slice(&[0x11; 32]);
1008 let mut script_sig = vec![71];
1009 script_sig.extend_from_slice(&[0x30; 71]);
1010 script_sig.push(u8::try_from(pubkey.len()).unwrap());
1011 script_sig.extend_from_slice(&pubkey);
1012
1013 let recipient = TransparentAddress::PublicKeyHash([0x22; 20]);
1014 let prevout = OutPoint::new([0x33; 32], 7);
1015 let tx = TransactionData::<Authorized>::from_parts(
1016 TxVersion::V5,
1017 BranchId::Nu5,
1018 0,
1019 BlockHeight::from(0),
1020 Some(Bundle::<TransparentAuthorized, Zatoshis> {
1021 vin: vec![TxIn::from_parts(
1022 prevout.clone(),
1023 Script(script::Code(script_sig)),
1024 0,
1025 )],
1026 vout: vec![TxOut::new(
1027 Zatoshis::const_from_u64(100_000),
1028 Script::from(&recipient.script()),
1029 )],
1030 authorization: TransparentAuthorized,
1031 }),
1032 None,
1033 None,
1034 None,
1035 )
1036 .freeze()
1037 .expect("transaction data is complete");
1038
1039 let height = BlockHeight::from(1_000_000);
1040 let header = BlockHeaderData {
1041 version: 4,
1042 prev_block: BlockHash([0; 32]),
1043 merkle_root: [0; 32],
1044 final_sapling_root: [0; 32],
1045 time: 0,
1046 bits: 0,
1047 nonce: [0; 32],
1048 solution: vec![],
1049 }
1050 .freeze()
1051 .unwrap();
1052 let block = Block::from_parts(header, NonEmpty::singleton(tx), height);
1053
1054 let scanning_keys = ScanningKeys::<u32, ()>::empty();
1055 let (header, vtx) = decrypt_block(&MAIN_NETWORK, block, &scanning_keys);
1056 let scanned = scan_block(
1057 &MAIN_NETWORK,
1058 height,
1059 &header,
1060 vtx,
1061 &scanning_keys,
1062 &SpendIdentifiers::empty(),
1063 Some(&BlockMetadata::from_parts(
1064 height - 1,
1065 BlockHash([0; 32]),
1066 Some(0),
1067 #[cfg(feature = "orchard")]
1068 Some(0),
1069 #[cfg(feature = "orchard")]
1070 Some(0),
1071 )),
1072 |addr| {
1075 Ok::<_, Infallible>(
1076 (*addr == recipient).then_some((0u32, Some(TransparentKeyScope::EXTERNAL))),
1077 )
1078 },
1079 )
1080 .expect("scanning the block succeeds");
1081
1082 assert_eq!(scanned.transactions().len(), 1);
1083 let observations = scanned.transactions()[0].transparent_address_observations();
1084
1085 assert_eq!(observations.len(), 2);
1087 assert_eq!(observations[0].address(), &recipient);
1088 assert_eq!(
1089 observations[0].involvement(),
1090 &TransparentInvolvement::Output(Zatoshis::const_from_u64(100_000))
1091 );
1092 assert_eq!(
1093 observations[1].involvement(),
1094 &TransparentInvolvement::Input(prevout)
1095 );
1096 }
1097
1098 proptest! {
1102 #[test]
1106 fn uses_known_prior_size(
1107 protocol in arb_protocol(),
1108 at_height in 0u32..1_000_000,
1109 prior in 0u32..100_000,
1110 counts in prop::collection::vec(0usize..1_000, 0..16),
1111 ) {
1112 let expected_end = prior + counts.iter().map(|c| *c as u32).sum::<u32>();
1113 let result = tree_sizes_around(
1114 BlockHeight::from(at_height),
1115 Some(BlockHeight::from(1u32)),
1116 Some(prior),
1117 counts.into_iter(),
1118 protocol,
1119 );
1120 prop_assert_eq!(result.unwrap(), (prior, expected_end));
1121 }
1122
1123 #[test]
1126 fn zero_below_activation_without_prior(
1127 protocol in arb_protocol(),
1128 at_height in 0u32..1_000_000,
1129 activation_offset in 1u32..1_000,
1130 counts in prop::collection::vec(0usize..1_000, 0..16),
1131 ) {
1132 let activation = at_height + activation_offset;
1134 let expected_end: u32 = counts.iter().map(|c| *c as u32).sum();
1135 let result = tree_sizes_around(
1136 BlockHeight::from(at_height),
1137 Some(BlockHeight::from(activation)),
1138 None,
1139 counts.into_iter(),
1140 protocol,
1141 );
1142 prop_assert_eq!(result.unwrap(), (0, expected_end));
1143 }
1144
1145 #[test]
1148 fn zero_when_activation_unset(
1149 protocol in arb_protocol(),
1150 at_height in 0u32..1_000_000,
1151 counts in prop::collection::vec(0usize..1_000, 0..16),
1152 ) {
1153 let expected_end: u32 = counts.iter().map(|c| *c as u32).sum();
1154 let result = tree_sizes_around(
1155 BlockHeight::from(at_height),
1156 None,
1157 None,
1158 counts.into_iter(),
1159 protocol,
1160 );
1161 prop_assert_eq!(result.unwrap(), (0, expected_end));
1162 }
1163
1164 #[test]
1166 fn prior_size_takes_precedence_below_activation(
1167 protocol in arb_protocol(),
1168 at_height in 0u32..1_000_000,
1169 activation_offset in 1u32..1_000,
1170 prior in 0u32..100_000,
1171 counts in prop::collection::vec(0usize..1_000, 0..16),
1172 ) {
1173 let activation = at_height + activation_offset;
1174 let expected_end = prior + counts.iter().map(|c| *c as u32).sum::<u32>();
1175 let result = tree_sizes_around(
1176 BlockHeight::from(at_height),
1177 Some(BlockHeight::from(activation)),
1178 Some(prior),
1179 counts.into_iter(),
1180 protocol,
1181 );
1182 prop_assert_eq!(result.unwrap(), (prior, expected_end));
1183 }
1184
1185 #[test]
1188 fn unknown_at_or_above_activation_without_prior(
1189 protocol in arb_protocol(),
1190 activation in 0u32..1_000_000,
1191 delta in 0u32..1_000,
1192 ) {
1193 let at_height = activation + delta;
1195 let result = tree_sizes_around(
1196 BlockHeight::from(at_height),
1197 Some(BlockHeight::from(activation)),
1198 None,
1199 std::iter::empty(),
1200 protocol,
1201 );
1202 let matched = matches!(
1203 result,
1204 Err(ScanError::TreeSizeUnknown { protocol: p, at_height: h })
1205 if p == protocol && h == BlockHeight::from(at_height)
1206 );
1207 prop_assert!(matched);
1208 }
1209
1210 #[test]
1213 fn overflow_is_reported(
1214 protocol in arb_protocol(),
1215 headroom in 0u32..100,
1216 extra in 1u32..100,
1217 ) {
1218 let prior = u32::MAX - headroom;
1221 let count = headroom as usize + extra as usize;
1222 let result = tree_sizes_around(
1223 BlockHeight::from(100u32),
1224 Some(BlockHeight::from(1u32)),
1225 Some(prior),
1226 std::iter::once(count),
1227 protocol,
1228 );
1229 let matched = matches!(
1230 result,
1231 Err(ScanError::TreeSizeOverflow { protocol: p, .. }) if p == protocol
1232 );
1233 prop_assert!(matched);
1234 }
1235
1236 #[test]
1238 fn exact_u32_max_boundary_is_not_overflow(
1239 protocol in arb_protocol(),
1240 count in 0u32..1_000,
1241 ) {
1242 let prior = u32::MAX - count;
1243 let result = tree_sizes_around(
1244 BlockHeight::from(100u32),
1245 Some(BlockHeight::from(1u32)),
1246 Some(prior),
1247 std::iter::once(count as usize),
1248 protocol,
1249 );
1250 prop_assert_eq!(result.unwrap(), (prior, u32::MAX));
1251 }
1252 }
1253
1254 #[test]
1255 fn contains_last_sapling_outputs_detects_boundary() {
1256 let tracker = PositionTracker {
1257 sapling_tree_position: 10,
1258 sapling_final_tree_size: 15,
1259 #[cfg(feature = "orchard")]
1260 orchard_tree_position: 0,
1261 #[cfg(feature = "orchard")]
1262 orchard_final_tree_size: 0,
1263 #[cfg(feature = "orchard")]
1264 ironwood_tree_position: 0,
1265 #[cfg(feature = "orchard")]
1266 ironwood_final_tree_size: 0,
1267 };
1268
1269 assert!(tracker.contains_last_sapling_outputs(5));
1272 assert!(!tracker.contains_last_sapling_outputs(0));
1273 assert!(!tracker.contains_last_sapling_outputs(4));
1274 assert!(!tracker.contains_last_sapling_outputs(6));
1275 }
1276
1277 #[test]
1278 fn increment_advances_sapling_position_to_final_size() {
1279 let mut tracker = PositionTracker {
1280 sapling_tree_position: 0,
1281 sapling_final_tree_size: 6,
1282 #[cfg(feature = "orchard")]
1283 orchard_tree_position: 0,
1284 #[cfg(feature = "orchard")]
1285 orchard_final_tree_size: 0,
1286 #[cfg(feature = "orchard")]
1287 ironwood_tree_position: 0,
1288 #[cfg(feature = "orchard")]
1289 ironwood_final_tree_size: 0,
1290 };
1291
1292 assert!(!tracker.contains_last_sapling_outputs(2));
1295 tracker.increment(
1296 2,
1297 #[cfg(feature = "orchard")]
1298 0,
1299 #[cfg(feature = "orchard")]
1300 0,
1301 );
1302 assert!(!tracker.contains_last_sapling_outputs(0));
1303 tracker.increment(
1304 0,
1305 #[cfg(feature = "orchard")]
1306 0,
1307 #[cfg(feature = "orchard")]
1308 0,
1309 );
1310 assert!(tracker.contains_last_sapling_outputs(4));
1311 tracker.increment(
1312 4,
1313 #[cfg(feature = "orchard")]
1314 0,
1315 #[cfg(feature = "orchard")]
1316 0,
1317 );
1318
1319 assert_eq!(tracker.sapling_tree_position, 6);
1320 tracker.check_end_of_block_consistency().unwrap();
1321 }
1322
1323 #[cfg(feature = "orchard")]
1324 #[test]
1325 fn increment_advances_orchard_position_to_final_size() {
1326 let mut tracker = PositionTracker {
1327 sapling_tree_position: 0,
1328 sapling_final_tree_size: 0,
1329 orchard_tree_position: 4,
1330 orchard_final_tree_size: 9,
1331 ironwood_tree_position: 0,
1332 ironwood_final_tree_size: 0,
1333 };
1334
1335 assert!(tracker.contains_last_orchard_actions(5));
1336 assert!(!tracker.contains_last_orchard_actions(4));
1337 tracker.increment(0, 5, 0);
1338
1339 assert_eq!(tracker.orchard_tree_position, 9);
1340 tracker.check_end_of_block_consistency().unwrap();
1341 }
1342
1343 #[test]
1344 #[should_panic]
1345 fn check_end_of_block_consistency_panics_when_incomplete() {
1346 let tracker = PositionTracker {
1349 sapling_tree_position: 3,
1350 sapling_final_tree_size: 6,
1351 #[cfg(feature = "orchard")]
1352 orchard_tree_position: 0,
1353 #[cfg(feature = "orchard")]
1354 orchard_final_tree_size: 0,
1355 #[cfg(feature = "orchard")]
1356 ironwood_tree_position: 0,
1357 #[cfg(feature = "orchard")]
1358 ironwood_final_tree_size: 0,
1359 };
1360 let _ = tracker.check_end_of_block_consistency();
1361 }
1362}