Skip to main content

zcash_client_backend/scanning/
full.rs

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
54/// The default number of outputs at which a batch runner immediately flushes a batch.
55pub(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// Ironwood outputs are decrypted under the Ironwood note-encryption domain, which is distinct from
88// the Orchard domain (it accepts version 3 note plaintexts), so an Ironwood batch is a distinct
89// type from an Orchard batch and requires its own task type.
90#[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    /// Constructs a fresh set of batch runners that will trial-decrypt outputs using the
152    /// given scanning keys.
153    ///
154    /// Each per-pool runner immediately flushes a batch once it has accumulated the
155    /// corresponding `*_batch_size_threshold` number of outputs.
156    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    /// Adds the given transaction's shielded outputs to the various batch runners,
192    /// returning a [`PendingBatch`] from which the decryption results can be awaited.
193    ///
194    /// `height` is the height of the block containing the transaction, or the mempool
195    /// height (chain tip height + 1) for a mempool transaction.
196    ///
197    /// After adding the outputs, any accumulated batch of sufficient size is run on the
198    /// global threadpool. Subsequent calls to `Self::process_transaction` will accumulate
199    /// outputs into new batches.
200    #[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    /// Runs the currently accumulated batches on the global threadpool.
243    ///
244    /// Subsequent calls to [`Self::process_transaction`] will be accumulated into new batches.
245    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
254/// A pending batch decryption result for a single transaction.
255pub(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    /// Blocks until the results of the batch are ready.
266    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    /// Waits, without blocking the current thread, until the results of the batch are
287    /// ready.
288    ///
289    /// This is the asynchronous counterpart of [`Self::wait`].
290    #[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
317/// The result of batch-decrypting a single transaction.
318///
319/// This is an opaque value, produced by [`decrypt_block`] (or the `sync::decryptor`
320/// engine) and consumed by [`scan_block`]; it is not intended to be inspected directly.
321pub 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
333/// Decrypts a block with a set of [`ScanningKeys`].
334///
335/// This is an inline, synchronous alternative to the batch decryption engine in the
336/// `sync::decryptor` module (available behind the `sync-decryptor` feature flag): it
337/// internally spins up batch runners to process the block, and discards them afterwards.
338///
339/// This is the first half of block scanning. Pass the result to [`scan_block`] for the
340/// second half.
341pub 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    // Flush any partially-accumulated batch so that every batch is actually run;
367    // otherwise `PendingBatch::wait` would block forever waiting on a batch that
368    // never started.
369    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/// Scans a block with a set of [`ScanningKeys`].
380///
381/// Returns a [`ScannedBlock`] containing one [`WalletTx`] for each transaction in the
382/// block that is decryptable by any of the given keys. If an output is decrypted by a
383/// full viewing key, the nullifiers of that output will also be computed.
384///
385/// This is the second half of block scanning. Use [`decrypt_block`], or the
386/// `sync::decryptor` engine (available behind the `sync-decryptor` feature flag), for
387/// the first half.
388///
389/// # Panics
390///
391/// Panics if any of the [`BatchResult`]s in `vtx` references an `IvkTag` not present in
392/// `scanning_keys`. To uphold this precondition, use the same set of [`ScanningKeys`]
393/// with both this function and [`decrypt_block`] (or `sync::decryptor::new` if you are
394/// running the decryption engine yourself).
395///
396/// [`WalletTx`]: crate::wallet::WalletTx
397#[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        // Detect spends of transparent outputs the wallet is tracking. A coinbase transaction's
537        // single input spends the null outpoint rather than a real prior output, so it is
538        // excluded: it can match no wallet output, and recording it would collide with the
539        // corresponding input of every other block's coinbase.
540        #[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        // Collect the set of accounts that were spent from in this transaction
556        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        // TODO(#1305): Correctly track accounts that fund each transaction output. For now
569        // we pick a single funding account; when more than one wallet account contributed
570        // inputs we select the lowest account id, so that the choice is deterministic.
571        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                // A full block carries complete transaction data, so both involvement
693                // directions are observable: the addresses paid by the outputs, and the
694                // addresses the inputs' `scriptSig`s reveal. Addresses the wallet does not
695                // control are recorded too, since a transaction that involves the wallet may
696                // name an address it learns to control only later. Every input of every other
697                // transaction in the block would have to be hashed to derive observations that
698                // are then discarded, so this is computed only once the transaction is known to
699                // involve the wallet.
700                #[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
747/// Returns the size of the given shielded protocol's note commitment tree both before and
748/// after the application of a block at `at_height`.
749///
750/// - `activation_height` is the height at which `protocol` activated, if set.
751/// - `prior_tree_size` is the tree size as of the end of the previous block, if known.
752/// - `output_counts` yields the number of `protocol` outputs in each transaction of the
753///   block, in order.
754///
755/// Returns [`ScanError::TreeSizeUnknown`] if the starting size cannot be determined (the
756/// block is at or above the protocol's activation height but no prior size is known), or
757/// [`ScanError::TreeSizeOverflow`] if applying the block's outputs would take the tree
758/// size beyond the `u32` range.
759fn 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        // If we're below the protocol's activation height, or it is not set, the tree
769        // size is zero; otherwise the starting size is unknown.
770        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    // We pre-compute the end tree size here so we can determine when we reach the last
782    // transaction in the block that adds notes to the tree. This enables us to correctly
783    // set the tree checkpoint in `find_received`. Note commitment tree sizes are
784    // `u32`-bounded by the protocol, so overflow here indicates corrupt or adversarial
785    // input rather than a valid chain state.
786    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
798/// Returns the number of Sapling outputs in `tx`.
799///
800/// Note commitment tree sizes are `u32`-bounded by the protocol, so a valid transaction
801/// can never contain more than `u32::MAX` outputs.
802fn 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/// Returns the number of Orchard actions in `tx`.
809///
810/// Note commitment tree sizes are `u32`-bounded by the protocol, so a valid transaction
811/// can never contain more than `u32::MAX` actions.
812#[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/// Returns the number of Ironwood actions in `tx`.
820///
821/// Note commitment tree sizes are `u32`-bounded by the protocol, so a valid transaction
822/// can never contain more than `u32::MAX` actions.
823#[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    /// Returns `true` if a transaction contributing `sapling_output_count` outputs would
886    /// bring the Sapling tree position up to the block's final Sapling tree size; that is,
887    /// such a transaction contains the last Sapling output in the block.
888    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    /// Returns `true` if a transaction contributing `orchard_action_count` actions would
897    /// bring the Orchard tree position up to the block's final Orchard tree size; that is,
898    /// such a transaction contains the last Orchard output in the block.
899    #[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    /// Returns `true` if a transaction contributing `ironwood_action_count` actions would
910    /// bring the Ironwood tree position up to the block's final Ironwood tree size; that is,
911    /// such a transaction contains the last Ironwood output in the block.
912    #[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    /// Advances the tracked tree positions past a transaction with the given output
923    /// counts.
924    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        // It is a programming error to construct `PositionTracker` from a `CompactBlock`
950        // and then not call `PositionTracker::increment_over_tx` on every transaction
951        // within the block.
952        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    /// Scanning a full block records, for each transaction the wallet is involved in, the
1000    /// transparent addresses that transaction's data names — in both directions, since a full
1001    /// block carries the `scriptSig`s that an input reveals its address through.
1002    #[test]
1003    #[cfg(feature = "transparent-inputs")]
1004    fn scan_block_records_transparent_address_observations() {
1005        // A compressed public key encoding, and a P2PKH `scriptSig` revealing it.
1006        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            // The output's recipient is treated as a wallet address, which is what makes the
1073            // transaction wallet-involving and so eligible to be observed at all.
1074            |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        // Both directions are observable from complete transaction data.
1086        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    // The behaviour of `tree_sizes_around` is independent of the shielded protocol (the
1099    // protocol is only echoed back in errors), so these properties are checked for a
1100    // `ShieldedPool` drawn uniformly at random via `arb_protocol`.
1101    proptest! {
1102        /// A known prior tree size is the starting point, and each transaction's outputs
1103        /// are summed onto it to reach the final size. An empty block (no transactions, or
1104        /// transactions with no outputs) leaves the size unchanged.
1105        #[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        /// With no prior size and a block below the activation height, the tree starts
1124        /// empty.
1125        #[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            // `at_height` is strictly below the activation height.
1133            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        /// With no prior size and no activation height (e.g. a protocol not activated on
1146        /// this network), the tree starts empty regardless of the block height.
1147        #[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        /// A known prior size is used even when the block is below the activation height.
1165        #[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        /// At or above the activation height with no prior size, the starting size cannot
1186        /// be determined, and the error reports the queried protocol and height.
1187        #[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            // `at_height` is at or above the activation height.
1194            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        /// Applying the block's outputs would push the tree size beyond the `u32` range,
1211        /// and the error reports the queried protocol.
1212        #[test]
1213        fn overflow_is_reported(
1214            protocol in arb_protocol(),
1215            headroom in 0u32..100,
1216            extra in 1u32..100,
1217        ) {
1218            // A single transaction whose output count exceeds the remaining headroom takes
1219            // the tree size past `u32::MAX`.
1220            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        /// Reaching exactly `u32::MAX` is a valid (non-overflowing) final size.
1237        #[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        // A transaction adding exactly the remaining outputs contains the block's last
1270        // Sapling output; any other count does not land on the boundary.
1271        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        // Walk a block of three transactions with 2, 0 and 4 Sapling outputs; only the
1293        // last one lands on the boundary.
1294        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        // Failing to increment over every transaction in the block is a programming error,
1347        // surfaced as a panic.
1348        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}