Skip to main content

zcash_client_backend/data_api/ll/
wallet.rs

1use std::{
2    collections::{BTreeMap, BTreeSet},
3    hash::Hash,
4    ops::Range,
5};
6
7use shardtree::store::Checkpoint;
8
9#[cfg(feature = "orchard")]
10use crate::data_api::ORCHARD_SHARD_HEIGHT;
11
12use rayon::{
13    iter::{IndexedParallelIterator as _, ParallelIterator},
14    slice::ParallelSliceMut as _,
15};
16use tracing::{debug, info, trace, warn};
17
18use incrementalmerkletree::{Hashable, Marking, Position, Retention, frontier::Frontier};
19use shardtree::{
20    LocatedPrunableTree, ShardTree,
21    error::{InsertionError, ShardTreeError},
22    store::ShardStore,
23};
24use transparent::{address::TransparentAddress, bundle::OutPoint};
25use zcash_keys::{address::Receiver, encoding::AddressCodec as _};
26use zcash_primitives::transaction::Transaction;
27use zcash_protocol::{
28    PoolType, ShieldedPool,
29    consensus::{self, BlockHeight},
30    value::{BalanceError, Zatoshis},
31};
32use zcash_script::solver::ScriptKind;
33
34use crate::{
35    TransferType,
36    data_api::{
37        DecryptedTransaction, SAPLING_SHARD_HEIGHT, ScannedBlock, TransactionStatus,
38        WalletCommitmentTrees, anchor_retention::AnchorRetention, chain::ChainState,
39        ll::ReceivedShieldedOutput,
40    },
41    scanning::ScanError,
42    wallet::{Recipient, WalletTransparentOutput},
43};
44
45use super::{LowLevelWalletRead, LowLevelWalletWrite, PutBlockMetaError, TxMeta};
46
47#[cfg(feature = "orchard")]
48use crate::data_api::anchor_retention::{AnchorRetentionInterval, PoolMigrationParams};
49
50#[cfg(feature = "transparent-inputs")]
51use {
52    crate::data_api::Account,
53    std::collections::HashSet,
54    zcash_keys::keys::{
55        ReceiverRequirement::*,
56        UnifiedAddressRequest,
57        transparent::{
58            TransparentKeyScope,
59            gap_limits::{AddressStore, GapAddressesError, GapLimits, generate_gap_addresses},
60        },
61    },
62};
63
64/// The maximum number of blocks the wallet is allowed to rewind. This is
65/// consistent with the bound in zcashd, and allows block data deeper than
66/// this delta from the chain tip to be pruned.
67///
68/// It is also the checkpoint budget of each note commitment tree and the depth of the
69/// window in which [`put_blocks`] creates checkpoints ([`checkpoint_floor`]); a store that
70/// maintains a tree by other means must build it with the same budget.
71pub const PRUNING_DEPTH: u32 = 100;
72
73pub(crate) fn determine_fee<DbT, T: TxMeta>(
74    _wallet_db: &DbT,
75    tx: &T,
76) -> Result<Option<Zatoshis>, DbT::Error>
77where
78    DbT: LowLevelWalletRead,
79    DbT::Error: From<BalanceError>,
80{
81    tx.fee_paid(|_outpoint| {
82        #[cfg(not(feature = "transparent-inputs"))]
83        {
84            // Transparent inputs aren't supported, so this closure should never be
85            // called during transaction construction. But in case it is, handle it
86            // correctly.
87            Ok(None)
88        }
89
90        // This closure can do DB lookups to fetch the value of each transparent input.
91        #[cfg(feature = "transparent-inputs")]
92        if let Some(out) = _wallet_db.get_wallet_transparent_output(_outpoint, None)? {
93            Ok(Some(out.txout().value()))
94        } else {
95            // If we can’t find it, fee computation can't complete accurately
96            Ok(None)
97        }
98    })
99}
100
101/// Generates transparent gap addresses for a given account and key scope.
102///
103/// This is a convenience function that resolves the account's viewing keys from the wallet
104/// database and delegates to [`generate_gap_addresses`].
105#[cfg(feature = "transparent-inputs")]
106pub fn generate_transparent_gap_addresses<DbT, SE>(
107    wallet_db: &mut DbT,
108    gap_limits: GapLimits,
109    account_id: <DbT as LowLevelWalletRead>::AccountId,
110    key_scope: TransparentKeyScope,
111    request: UnifiedAddressRequest,
112) -> Result<(), GapAddressesError<SE>>
113where
114    DbT: LowLevelWalletWrite<Error = SE>
115        + AddressStore<Error = SE, AccountRef = <DbT as LowLevelWalletRead>::AccountRef>,
116    DbT::TxRef: Eq + Hash,
117{
118    let account_ref = wallet_db
119        .get_account_ref(account_id)
120        .map_err(GapAddressesError::Storage)?;
121
122    let account = wallet_db
123        .get_account_internal(account_ref)
124        .map_err(GapAddressesError::Storage)?
125        .ok_or(GapAddressesError::AccountUnknown)?;
126
127    generate_gap_addresses(
128        wallet_db,
129        &gap_limits,
130        account_ref,
131        &account.uivk(),
132        account.ufvk(),
133        key_scope,
134        request,
135        false,
136    )?;
137
138    Ok(())
139}
140
141#[derive(Debug)]
142#[non_exhaustive]
143pub enum PutBlocksError<SE, TE> {
144    /// Returned if a provided block sequence has gaps.
145    NonSequentialBlocks {
146        prev_height: BlockHeight,
147        block_height: BlockHeight,
148    },
149    /// The note commitment data of the batch, or the chain state it extends, conflicts with
150    /// tree state the wallet already holds. The carried error is a continuity error at the first
151    /// block of the batch. Block data written before the conflict was detected remains in the
152    /// caller's transaction, so the caller must roll that transaction back.
153    Continuity(ScanError),
154    /// Wraps an error produced by the underlying data storage system.
155    Storage(SE),
156    /// Wraps an error produced by [`shardtree`] insertion.
157    ShardTree(ShardTreeError<TE>),
158    /// Wraps an error produced by [`shardtree`] while inserting the note commitment data for a
159    /// range of scanned blocks into one of the wallet's note commitment trees. The `pool` and
160    /// `block_range` fields record the shielded pool whose note commitment tree was being updated
161    /// and the range of block heights (start-inclusive, end-exclusive) that were being added to
162    /// the wallet when the error occurred.
163    ShardTreeForBlockRange {
164        /// The shielded pool whose note commitment tree was being updated when the error occurred.
165        pool: ShieldedPool,
166        /// The range of block heights that were being added to the wallet when the error
167        /// occurred.
168        block_range: Range<BlockHeight>,
169        /// The underlying error produced by [`shardtree`] insertion.
170        error: ShardTreeError<TE>,
171    },
172    #[cfg(feature = "transparent-inputs")]
173    GapAddresses(GapAddressesError<SE>),
174}
175
176impl<SE, TE> PutBlocksError<SE, TE> {
177    /// Classifies an error from updating the note commitment tree of `pool` with the batch of
178    /// blocks above `from_height` through `last_scanned_height`. A conflict with existing tree
179    /// state is a continuity error at the batch's first block; any other error is reported
180    /// against the batch's block range.
181    fn tree_update(
182        pool: ShieldedPool,
183        from_height: BlockHeight,
184        last_scanned_height: BlockHeight,
185        error: ShardTreeError<TE>,
186    ) -> Self {
187        match error {
188            ShardTreeError::Insert(InsertionError::Conflict(address)) => {
189                PutBlocksError::Continuity(ScanError::CommitmentTreeConflict {
190                    pool,
191                    at_height: from_height + 1,
192                    address,
193                })
194            }
195            error => PutBlocksError::ShardTreeForBlockRange {
196                pool,
197                block_range: from_height..(last_scanned_height + 1),
198                error,
199            },
200        }
201    }
202}
203
204impl<SE, TE> From<ShardTreeError<TE>> for PutBlocksError<SE, TE> {
205    fn from(value: ShardTreeError<TE>) -> Self {
206        PutBlocksError::ShardTree(value)
207    }
208}
209
210#[cfg(feature = "transparent-inputs")]
211impl<SE, TE> From<GapAddressesError<SE>> for PutBlocksError<SE, TE> {
212    fn from(value: GapAddressesError<SE>) -> Self {
213        PutBlocksError::GapAddresses(value)
214    }
215}
216
217/// A trait alias capturing the database capabilities required by [`put_blocks`].
218#[cfg(not(feature = "transparent-inputs"))]
219pub trait PutBlocksDbT<SE, TE, AR>:
220    LowLevelWalletWrite<Error = SE> + WalletCommitmentTrees<Error = TE>
221{
222}
223
224#[cfg(not(feature = "transparent-inputs"))]
225impl<T: LowLevelWalletWrite<Error = SE> + WalletCommitmentTrees<Error = TE>, SE, TE, AR>
226    PutBlocksDbT<SE, TE, AR> for T
227{
228}
229
230/// A trait alias capturing the database capabilities required by [`put_blocks`].
231///
232/// The `transparent-inputs` feature is enabled in this build, so this additionally requires
233/// [`AddressStore`] so that transparent gap addresses can be maintained as new blocks are
234/// scanned.
235///
236/// [`AddressStore`]: zcash_keys::keys::transparent::gap_limits::AddressStore
237#[cfg(feature = "transparent-inputs")]
238pub trait PutBlocksDbT<SE, TE, AR>:
239    LowLevelWalletWrite<Error = SE>
240    + WalletCommitmentTrees<Error = TE>
241    + AddressStore<Error = SE, AccountRef = AR>
242{
243}
244
245#[cfg(feature = "transparent-inputs")]
246impl<
247    T: LowLevelWalletWrite<Error = SE>
248        + WalletCommitmentTrees<Error = TE>
249        + AddressStore<Error = SE, AccountRef = AR>,
250    SE,
251    TE,
252    AR,
253> PutBlocksDbT<SE, TE, AR> for T
254{
255}
256
257/// A trait alias capturing the database capabilities required by [`put_blocks_rows`].
258///
259/// Unlike [`PutBlocksDbT`], this does not require [`WalletCommitmentTrees`]: the row stage
260/// of [`put_blocks`] only writes through the [`LowLevelWalletWrite`] interface.
261#[cfg(not(feature = "transparent-inputs"))]
262pub trait PutBlocksRowsDbT<SE, AR>: LowLevelWalletWrite<Error = SE> {}
263
264#[cfg(not(feature = "transparent-inputs"))]
265impl<T: LowLevelWalletWrite<Error = SE>, SE, AR> PutBlocksRowsDbT<SE, AR> for T {}
266
267/// A trait alias capturing the database capabilities required by [`put_blocks_rows`].
268///
269/// Unlike [`PutBlocksDbT`], this does not require [`WalletCommitmentTrees`]: the row stage
270/// of [`put_blocks`] only writes through the [`LowLevelWalletWrite`] interface.
271///
272/// The `transparent-inputs` feature is enabled in this build, so this additionally requires
273/// [`AddressStore`] so that transparent gap addresses can be maintained as new blocks are
274/// scanned.
275///
276/// [`AddressStore`]: zcash_keys::keys::transparent::gap_limits::AddressStore
277#[cfg(feature = "transparent-inputs")]
278pub trait PutBlocksRowsDbT<SE, AR>:
279    LowLevelWalletWrite<Error = SE> + AddressStore<Error = SE, AccountRef = AR>
280{
281}
282
283#[cfg(feature = "transparent-inputs")]
284impl<T: LowLevelWalletWrite<Error = SE> + AddressStore<Error = SE, AccountRef = AR>, SE, AR>
285    PutBlocksRowsDbT<SE, AR> for T
286{
287}
288
289/// The note commitment data accumulated by [`put_blocks_rows`] across a sequence of scanned
290/// blocks: exactly the input that the note commitment tree stage of [`put_blocks`] consumes.
291///
292/// Commitment entries are wrapped in `Option` so that downstream subtree construction (see
293/// [`build_subtrees`]) can move them out of the buffer from within a `rayon` parallel iterator;
294/// every entry is `Some` on return from [`put_blocks_rows`].
295#[derive(Default)]
296pub struct PutBlocksRows {
297    /// The ordered vector of note commitments for Sapling outputs, beginning at the position
298    /// following the final Sapling tree state of the `from_state` argument.
299    pub sapling_commitments: Vec<Option<(sapling::Node, Retention<BlockHeight>)>>,
300    /// The ordered vector of note commitments for Orchard outputs, beginning at the position
301    /// following the final Orchard tree state of the `from_state` argument.
302    #[cfg(feature = "orchard")]
303    pub orchard_commitments:
304        Vec<Option<(orchard::tree::MerkleHashOrchard, Retention<BlockHeight>)>>,
305    /// The ordered vector of note commitments for Ironwood outputs, beginning at the position
306    /// following the final Ironwood tree state of the `from_state` argument.
307    #[cfg(feature = "orchard")]
308    pub ironwood_commitments:
309        Vec<Option<(orchard::tree::MerkleHashOrchard, Retention<BlockHeight>)>>,
310    /// The note commitment tree positions of outputs received by the wallet, for use with
311    /// [`LowLevelWalletWrite::notify_scan_complete`].
312    pub note_positions: Vec<(ShieldedPool, Position)>,
313    /// The height of the last block in the persisted sequence; `None` if and only if the
314    /// provided block vector was empty.
315    pub last_scanned_height: Option<BlockHeight>,
316}
317
318/// Persists the row-level (non-tree) data for a sequence of scanned blocks: block metadata,
319/// transaction and note rows, spent-note marking, nullifier tracking and pruning, and — when
320/// the `transparent-inputs` feature is enabled — transparent gap address maintenance for the
321/// involved accounts.
322///
323/// This is the first stage of [`put_blocks`], which is equivalent to `put_blocks_rows` followed
324/// by the note commitment tree updates (see [`build_subtrees`] and [`update_tree`]) and
325/// [`LowLevelWalletWrite::notify_scan_complete`]. It is exposed so that wallet stores that
326/// maintain their note commitment trees by other means can reuse the row-writing logic through
327/// the [`LowLevelWalletWrite`] interface without also taking on the [`WalletCommitmentTrees`]
328/// requirement.
329///
330/// The `TE` type parameter is unconstrained here (the row stage cannot produce a tree error);
331/// it exists so that errors propagate directly as the [`PutBlocksError`] of the enclosing
332/// [`put_blocks`] call.
333///
334/// # Parameters
335/// - `wallet_db`: A handle to the underlying data store.
336/// - `from_state`: The note commitment tree state as of the end of the last block prior to the
337///   first block in the provided block vector; [`PutBlocksError::NonSequentialBlocks`] will be
338///   returned if this invariant is violated.
339/// - `blocks`: The scanned block data to be added to the data store. This vector must contain
340///   data for blocks in sequentially increasing height order;
341///   [`PutBlocksError::NonSequentialBlocks`] will be returned if this invariant is violated.
342///
343/// # Spend tracking
344///
345/// When a batch extends the wallet's contiguous fully-scanned frontier (i.e.
346/// [`LowLevelWalletRead::block_fully_scanned_height`] equals the `from_state` height, so
347/// every block from the wallet birthday through the previous block has been scanned),
348/// spend-map insertion is skipped for blocks more than
349/// [`SPEND_MAP_RETENTION_BLOCKS`] below the end of the batch. Under that precondition
350/// the skipped entries are provably unobservable: the spend maps exist to detect
351/// spends observed before the corresponding output's block has been scanned, which cannot
352/// occur below a contiguous frontier — any wallet output spendable in a skipped block was
353/// either received in an already-scanned block (so its spend is detected directly against
354/// the wallet's own nullifiers and outpoints rather than the map) or is received later in
355/// this same ascending batch (so the spend is linked when the receiving transaction is
356/// processed). For every out-of-order range — scanning after a gap, recent-first, or
357/// chain-tip pre-scans — every block's spends are tracked.
358///
359/// This governs the shielded nullifier maps and the transparent spend map alike; the
360/// argument above is indifferent to which kind of output identifier is being tracked.
361pub fn put_blocks_rows<DbT, P, SE, TE>(
362    wallet_db: &mut DbT,
363    params: &P,
364    #[cfg(feature = "transparent-inputs")] gap_limits: GapLimits,
365    from_state: &ChainState,
366    blocks: Vec<ScannedBlock<<DbT as LowLevelWalletRead>::AccountId>>,
367) -> Result<PutBlocksRows, PutBlocksError<SE, TE>>
368where
369    DbT: PutBlocksRowsDbT<SE, <DbT as LowLevelWalletRead>::AccountRef>,
370    DbT::TxRef: Eq + Hash,
371    P: consensus::Parameters,
372{
373    if blocks.is_empty() {
374        return Ok(PutBlocksRows::default());
375    }
376
377    let initial_block = blocks.first().expect("blocks is known to be nonempty");
378    let mut initial_block_sequential = from_state.block_height() + 1 == initial_block.height();
379    {
380        initial_block_sequential &= from_state.final_sapling_tree().tree_size()
381            + u64::try_from(initial_block.sapling().commitments().len()).unwrap()
382            == u64::from(initial_block.sapling().final_tree_size());
383    }
384    #[cfg(feature = "orchard")]
385    {
386        initial_block_sequential &= from_state.final_orchard_tree().tree_size()
387            + u64::try_from(initial_block.orchard().commitments().len()).unwrap()
388            == u64::from(initial_block.orchard().final_tree_size());
389        initial_block_sequential &= from_state.final_ironwood_tree().tree_size()
390            + u64::try_from(initial_block.ironwood().commitments().len()).unwrap()
391            == u64::from(initial_block.ironwood().final_tree_size());
392    }
393    if !initial_block_sequential {
394        return Err(PutBlocksError::NonSequentialBlocks {
395            prev_height: from_state.block_height(),
396            block_height: initial_block.height(),
397        });
398    }
399
400    let spend_tracking_floor = spend_tracking_floor(
401        wallet_db
402            .block_fully_scanned_height()
403            .map_err(PutBlocksError::Storage)?,
404        from_state.block_height(),
405        blocks.last().map(|block| block.height()),
406    );
407
408    let mut sapling_commitments = vec![];
409    #[cfg(feature = "orchard")]
410    let mut orchard_commitments = vec![];
411    #[cfg(feature = "orchard")]
412    let mut ironwood_commitments = vec![];
413    let mut last_scanned_height = None;
414    let mut note_positions = vec![];
415
416    #[cfg(feature = "transparent-inputs")]
417    let mut tx_refs = HashSet::new();
418
419    for block in blocks.into_iter() {
420        if last_scanned_height
421            .iter()
422            .any(|prev| block.height() != *prev + 1)
423        {
424            return Err(PutBlocksError::NonSequentialBlocks {
425                prev_height: last_scanned_height.expect("last scanned height is known"),
426                block_height: block.height(),
427            });
428        }
429
430        // Insert the block into the database.
431        wallet_db
432            .put_block_meta(
433                block.height(),
434                block.block_hash(),
435                block.block_time(),
436                block.sapling().final_tree_size(),
437                block.sapling().commitments().len().try_into().unwrap(),
438                #[cfg(feature = "orchard")]
439                block.orchard().final_tree_size(),
440                #[cfg(feature = "orchard")]
441                block.orchard().commitments().len().try_into().unwrap(),
442                #[cfg(feature = "orchard")]
443                block.ironwood().final_tree_size(),
444                #[cfg(feature = "orchard")]
445                block.ironwood().commitments().len().try_into().unwrap(),
446            )
447            .map_err(|error| match error {
448                PutBlockMetaError::HashMismatch { stored } => {
449                    PutBlocksError::Continuity(ScanError::BlockHashMismatch {
450                        at_height: block.height(),
451                        stored,
452                        scanned: block.block_hash(),
453                    })
454                }
455                PutBlockMetaError::Storage(error) => PutBlocksError::Storage(error),
456            })?;
457
458        for tx in block.transactions() {
459            let tx_ref = wallet_db
460                .put_tx_meta(tx, block.height())
461                .map_err(PutBlocksError::Storage)?;
462
463            #[cfg(feature = "transparent-inputs")]
464            tx_refs.insert(tx_ref);
465
466            wallet_db
467                .queue_tx_retrieval(std::iter::once(tx.txid()), None)
468                .map_err(PutBlocksError::Storage)?;
469
470            // The scan has determined that this transaction involves the wallet, so record the
471            // transparent addresses its data names. Which involvement directions the scan could
472            // observe depends on whether the block was compact or full; the record is an
473            // idempotent upsert, so a later observation at higher fidelity completes it.
474            #[cfg(feature = "transparent-inputs")]
475            wallet_db
476                .put_transparent_address_observations(tx_ref, tx.transparent_address_observations())
477                .map_err(PutBlocksError::Storage)?;
478
479            // Mark notes and transparent outputs as spent, and remove them from the scanning
480            // cache. Only spends of outputs the wallet already knew of appear here; those it
481            // could not yet recognize are handled by the spend map below.
482            let _ = mark_notes_spent(
483                wallet_db,
484                tx_ref,
485                #[cfg(feature = "transparent-inputs")]
486                tx.transparent_spends().iter().map(|spend| spend.outpoint()),
487                tx.sapling_spends().iter().map(|spend| spend.nf()),
488                #[cfg(feature = "orchard")]
489                tx.orchard_spends().iter().map(|spend| spend.nf()),
490                #[cfg(feature = "orchard")]
491                tx.ironwood_spends().iter().map(|spend| spend.nf()),
492            )
493            .map_err(PutBlocksError::Storage)?;
494
495            put_shielded_outputs(
496                wallet_db,
497                params,
498                tx_ref,
499                None,
500                tx.sapling_outputs(),
501                // Check whether this note was spent in a later block range that
502                // we previously scanned.
503                |wallet_db, output| {
504                    Ok(output
505                        .nf()
506                        .map(|nf| wallet_db.detect_sapling_spend(nf))
507                        .transpose()?
508                        .flatten())
509                },
510                |wallet_db, output, tx_ref, spent_in| {
511                    wallet_db.put_received_sapling_note(
512                        output,
513                        tx_ref,
514                        Some(block.height()),
515                        spent_in,
516                    )
517                },
518                |_account_id| (),
519            )
520            .map_err(PutBlocksError::Storage)?;
521
522            #[cfg(feature = "orchard")]
523            put_shielded_outputs(
524                wallet_db,
525                params,
526                tx_ref,
527                None,
528                tx.orchard_outputs(),
529                // Check whether this note was spent in a later block range that
530                // we previously scanned.
531                |wallet_db, output| {
532                    Ok(output
533                        .nf()
534                        .map(|nf| wallet_db.detect_orchard_spend(nf))
535                        .transpose()?
536                        .flatten())
537                },
538                |wallet_db, output, tx_ref, spent_in| {
539                    wallet_db.put_received_orchard_note(
540                        output,
541                        tx_ref,
542                        Some(block.height()),
543                        spent_in,
544                    )
545                },
546                |_account_id| (),
547            )
548            .map_err(PutBlocksError::Storage)?;
549
550            #[cfg(feature = "orchard")]
551            put_shielded_outputs(
552                wallet_db,
553                params,
554                tx_ref,
555                None,
556                tx.ironwood_outputs(),
557                // Check whether this note was spent in a later block range that
558                // we previously scanned.
559                |wallet_db, output| {
560                    Ok(output
561                        .nf()
562                        .map(|nf| wallet_db.detect_ironwood_spend(nf))
563                        .transpose()?
564                        .flatten())
565                },
566                |wallet_db, output, tx_ref, spent_in| {
567                    wallet_db.put_received_ironwood_note(
568                        output,
569                        tx_ref,
570                        Some(block.height()),
571                        spent_in,
572                    )
573                },
574                |_account_id| (),
575            )
576            .map_err(PutBlocksError::Storage)?;
577
578            // Record the transparent outputs of the transaction that pay this wallet. As for
579            // the shielded pools above, only the receive side is recorded here; the sent
580            // outputs of a transaction the wallet funded are recorded when the complete
581            // transaction data arrives via `put_decrypted_tx`, which this scan has queued for
582            // retrieval. The gap-address regeneration that follows the block loop observes
583            // these receives, so no separate notification is needed.
584            #[cfg(feature = "transparent-inputs")]
585            for output in tx.transparent_outputs() {
586                put_received_transparent_output(
587                    wallet_db,
588                    tx_ref,
589                    output,
590                    block.height(),
591                    |_, _| (),
592                )
593                .map_err(PutBlocksError::Storage)?;
594            }
595        }
596
597        // Insert this block's unmatched nullifiers and transparent prevouts into the spend maps,
598        // unless the height lies below the spend-tracking floor.
599        if should_track_spends(spend_tracking_floor, block.height()) {
600            wallet_db
601                .track_block_sapling_nullifiers(block.height(), block.sapling().nullifier_map())
602                .map_err(PutBlocksError::Storage)?;
603
604            #[cfg(feature = "orchard")]
605            wallet_db
606                .track_block_orchard_nullifiers(block.height(), block.orchard().nullifier_map())
607                .map_err(PutBlocksError::Storage)?;
608
609            #[cfg(feature = "orchard")]
610            wallet_db
611                .track_block_ironwood_nullifiers(block.height(), block.ironwood().nullifier_map())
612                .map_err(PutBlocksError::Storage)?;
613
614            #[cfg(feature = "transparent-inputs")]
615            wallet_db
616                .track_block_transparent_spends(block.height(), block.transparent_spend_map())
617                .map_err(PutBlocksError::Storage)?;
618        }
619
620        note_positions.extend(block.transactions().iter().flat_map(|wtx| {
621            let iter = wtx
622                .sapling_outputs()
623                .iter()
624                .map(|out| (ShieldedPool::Sapling, out.note_commitment_tree_position()));
625            #[cfg(feature = "orchard")]
626            let iter = iter.chain(
627                wtx.orchard_outputs()
628                    .iter()
629                    .map(|out| (ShieldedPool::Orchard, out.note_commitment_tree_position())),
630            );
631            #[cfg(feature = "orchard")]
632            let iter = iter.chain(
633                wtx.ironwood_outputs()
634                    .iter()
635                    .map(|out| (ShieldedPool::Ironwood, out.note_commitment_tree_position())),
636            );
637
638            iter
639        }));
640
641        last_scanned_height = Some(block.height());
642        let block_commitments = block.into_commitments();
643        trace!(
644            "Sapling commitments for {:?}: {:?}",
645            last_scanned_height,
646            block_commitments
647                .sapling
648                .iter()
649                .map(|(_, r)| *r)
650                .collect::<Vec<_>>()
651        );
652        #[cfg(feature = "orchard")]
653        trace!(
654            "Orchard commitments for {:?}: {:?}",
655            last_scanned_height,
656            block_commitments
657                .orchard
658                .iter()
659                .map(|(_, r)| *r)
660                .collect::<Vec<_>>()
661        );
662
663        sapling_commitments.extend(block_commitments.sapling.into_iter().map(Some));
664        #[cfg(feature = "orchard")]
665        orchard_commitments.extend(block_commitments.orchard.into_iter().map(Some));
666        #[cfg(feature = "orchard")]
667        ironwood_commitments.extend(block_commitments.ironwood.into_iter().map(Some));
668    }
669
670    #[cfg(feature = "transparent-inputs")]
671    for (account_id, key_scope) in wallet_db
672        .find_involved_accounts(tx_refs)
673        .map_err(PutBlocksError::Storage)?
674    {
675        if let Some(t_key_scope) = key_scope {
676            generate_transparent_gap_addresses(
677                wallet_db,
678                gap_limits,
679                account_id,
680                t_key_scope,
681                UnifiedAddressRequest::unsafe_custom(Allow, Allow, Require),
682            )
683            .map_err(PutBlocksError::GapAddresses)?;
684        }
685    }
686
687    // Prune the nullifier and transparent spend maps of entries we no longer need.
688    wallet_db
689        .prune_tracked_spends(PRUNING_DEPTH)
690        .map_err(PutBlocksError::Storage)?;
691
692    Ok(PutBlocksRows {
693        sapling_commitments,
694        #[cfg(feature = "orchard")]
695        orchard_commitments,
696        #[cfg(feature = "orchard")]
697        ironwood_commitments,
698        note_positions,
699        last_scanned_height,
700    })
701}
702
703/// Adds information about a sequence of scanned blocks to the provided data store.
704///
705/// This is equivalent to persisting the row-level data via [`put_blocks_rows`] and then
706/// updating the note commitment trees with the returned commitments.
707///
708/// # Parameters
709/// - `wallet_db`: A handle to the underlying data store.
710/// - `from_state`: The note commitment tree state as of the end of the last block prior to the
711///   first block in the provided block vector; [`PutBlocksError::NonSequentialBlocks`] will be
712///   returned if this invariant is violated.
713/// - `blocks`: The scanned block data to be added to the data store. This vector must contain
714///   data for blocks in sequentially increasing height order;
715///   [`PutBlocksError::NonSequentialBlocks`] will be returned if this invariant is violated.
716/// - `anchor_retention`: If `Some(retention)`, the checkpoints the policy
717///   [retains](AnchorRetention::retains) — those at or above its floor that fall on its interval —
718///   are kept as durable anchors, exempting them from automatic pruning of excess checkpoints.
719///   A checkpoint is CREATED at every retained height in the scanned range that would not
720///   otherwise receive one: scanning only checkpoints a block at its last note commitment, so a
721///   boundary block containing no shielded outputs in any pool would otherwise leave a permanent
722///   hole in the retained grid, and the anchor there could never be proved against. `None`
723///   disables anchor retention.
724/// - `chain_tip`: The wallet's view of the chain tip, if known. `Checkpoint` retention is used
725///   only within `PRUNING_DEPTH` blocks of the later of this height and the last block in
726///   `blocks`: every scanned height inside that window receives a checkpoint in every tree,
727///   whether or not a block there carries a commitment, so that an anchor exists at the
728///   confirmations-policy depth. A block-end checkpoint below the window is not created, since
729///   it would be pruned as soon as the window advanced; its commitment keeps only the marking
730///   that protects a wallet note. Retained anchor heights are checkpointed regardless.
731pub fn put_blocks<DbT, P, SE, TE>(
732    wallet_db: &mut DbT,
733    params: &P,
734    #[cfg(feature = "transparent-inputs")] gap_limits: GapLimits,
735    from_state: &ChainState,
736    blocks: Vec<ScannedBlock<<DbT as LowLevelWalletRead>::AccountId>>,
737    chain_tip: Option<BlockHeight>,
738    anchor_retention: Option<&AnchorRetention>,
739) -> Result<(), PutBlocksError<SE, TE>>
740where
741    DbT: PutBlocksDbT<SE, TE, <DbT as LowLevelWalletRead>::AccountRef>,
742    DbT::TxRef: Eq + Hash,
743    P: consensus::Parameters,
744{
745    let rows = put_blocks_rows(
746        wallet_db,
747        params,
748        #[cfg(feature = "transparent-inputs")]
749        gap_limits,
750        from_state,
751        blocks,
752    )?;
753
754    let mut sapling_commitments = rows.sapling_commitments;
755    #[cfg(feature = "orchard")]
756    let mut orchard_commitments = rows.orchard_commitments;
757    #[cfg(feature = "orchard")]
758    let mut ironwood_commitments = rows.ironwood_commitments;
759    let note_positions = rows.note_positions;
760    let last_scanned_height = rows.last_scanned_height;
761
762    // We will have a start position and a last scanned height in all cases where
763    // `blocks` is non-empty.
764    if let Some(last_scanned_height) = last_scanned_height {
765        let mut checkpoints = batch_checkpoints(
766            from_state,
767            last_scanned_height,
768            chain_tip,
769            anchor_retention,
770            &sapling_commitments,
771            #[cfg(feature = "orchard")]
772            &orchard_commitments,
773            #[cfg(feature = "orchard")]
774            &ironwood_commitments,
775        );
776        let checkpoint_floor = checkpoints.checkpoint_floor;
777
778        assign_block_end_retention(
779            &mut sapling_commitments,
780            Position::from(from_state.final_sapling_tree().tree_size()),
781            checkpoint_floor,
782            anchor_retention,
783            &mut checkpoints.sapling,
784        );
785        #[cfg(feature = "orchard")]
786        assign_block_end_retention(
787            &mut orchard_commitments,
788            Position::from(from_state.final_orchard_tree().tree_size()),
789            checkpoint_floor,
790            anchor_retention,
791            &mut checkpoints.orchard,
792        );
793        #[cfg(feature = "orchard")]
794        assign_block_end_retention(
795            &mut ironwood_commitments,
796            Position::from(from_state.final_ironwood_tree().tree_size()),
797            checkpoint_floor,
798            anchor_retention,
799            &mut checkpoints.ironwood,
800        );
801
802        // Create subtrees from the note commitments in parallel.
803        const CHUNK_SIZE: usize = 1024;
804        let sapling_subtrees = build_subtrees::<_, SAPLING_SHARD_HEIGHT>(
805            Position::from(from_state.final_sapling_tree().tree_size()),
806            &mut sapling_commitments,
807            CHUNK_SIZE,
808        );
809
810        #[cfg(feature = "orchard")]
811        let orchard_subtrees = build_subtrees::<_, ORCHARD_SHARD_HEIGHT>(
812            Position::from(from_state.final_orchard_tree().tree_size()),
813            &mut orchard_commitments,
814            CHUNK_SIZE,
815        );
816
817        // The Ironwood note commitment tree is Orchard-shaped and so uses the Orchard shard
818        // height, but is a distinct pool with its own tree.
819        #[cfg(feature = "orchard")]
820        let ironwood_subtrees = build_subtrees::<_, ORCHARD_SHARD_HEIGHT>(
821            Position::from(from_state.final_ironwood_tree().tree_size()),
822            &mut ironwood_commitments,
823            CHUNK_SIZE,
824        );
825
826        // Update the Sapling note commitment tree with all newly read note commitments
827        {
828            let mut sapling_subtrees = sapling_subtrees.into_iter();
829            let mut missing_checkpoints = checkpoints.sapling.into_iter();
830            wallet_db.with_sapling_tree_mut(|sapling_tree| {
831                update_tree(
832                    "Sapling",
833                    from_state.final_sapling_tree(),
834                    from_state.block_height(),
835                    checkpoint_floor,
836                    sapling_tree,
837                    anchor_retention,
838                    &mut sapling_subtrees,
839                    &mut missing_checkpoints,
840                )
841                .map_err(|error| {
842                    PutBlocksError::tree_update(
843                        ShieldedPool::Sapling,
844                        from_state.block_height(),
845                        last_scanned_height,
846                        error,
847                    )
848                })
849            })?;
850        }
851
852        // Update the Orchard note commitment tree with all newly read note commitments
853        #[cfg(feature = "orchard")]
854        {
855            let mut orchard_subtrees = orchard_subtrees.into_iter();
856            let mut missing_checkpoints = checkpoints.orchard.into_iter();
857            wallet_db.with_orchard_tree_mut(|orchard_tree| {
858                update_tree(
859                    "Orchard",
860                    from_state.final_orchard_tree(),
861                    from_state.block_height(),
862                    checkpoint_floor,
863                    orchard_tree,
864                    anchor_retention,
865                    &mut orchard_subtrees,
866                    &mut missing_checkpoints,
867                )
868                .map_err(|error| {
869                    PutBlocksError::tree_update(
870                        ShieldedPool::Orchard,
871                        from_state.block_height(),
872                        last_scanned_height,
873                        error,
874                    )
875                })
876            })?;
877        }
878
879        // Update the Ironwood note commitment tree with all newly read note commitments
880        #[cfg(feature = "orchard")]
881        {
882            let mut ironwood_subtrees = ironwood_subtrees.into_iter();
883            let mut missing_checkpoints = checkpoints.ironwood.into_iter();
884            wallet_db.with_ironwood_tree_mut(|ironwood_tree| {
885                update_tree(
886                    "Ironwood",
887                    from_state.final_ironwood_tree(),
888                    from_state.block_height(),
889                    checkpoint_floor,
890                    ironwood_tree,
891                    anchor_retention,
892                    &mut ironwood_subtrees,
893                    &mut missing_checkpoints,
894                )
895                .map_err(|error| {
896                    PutBlocksError::tree_update(
897                        ShieldedPool::Ironwood,
898                        from_state.block_height(),
899                        last_scanned_height,
900                        error,
901                    )
902                })
903            })?;
904        }
905
906        wallet_db
907            .notify_scan_complete(
908                Range {
909                    start: from_state.block_height() + 1,
910                    end: last_scanned_height + 1,
911                },
912                &note_positions,
913            )
914            .map_err(PutBlocksError::Storage)?;
915    }
916
917    Ok(())
918}
919
920#[cfg(not(feature = "transparent-inputs"))]
921type GapError<DbT> = <DbT as LowLevelWalletRead>::Error;
922
923/// A trait alias capturing the database capabilities required by [`store_decrypted_tx`].
924#[cfg(not(feature = "transparent-inputs"))]
925pub trait StoreDecryptedTxDbT: LowLevelWalletWrite {}
926
927#[cfg(not(feature = "transparent-inputs"))]
928impl<T: LowLevelWalletWrite> StoreDecryptedTxDbT for T {}
929
930#[cfg(feature = "transparent-inputs")]
931type GapError<DbT> = GapAddressesError<<DbT as LowLevelWalletRead>::Error>;
932
933/// A trait alias capturing the database capabilities required by [`store_decrypted_tx`].
934///
935/// The `transparent-inputs` feature is enabled in this build, so this additionally requires
936/// [`AddressStore`] so that transparent gap addresses can be regenerated after storing a
937/// decrypted transaction.
938///
939/// [`AddressStore`]: zcash_keys::keys::transparent::gap_limits::AddressStore
940#[cfg(feature = "transparent-inputs")]
941pub trait StoreDecryptedTxDbT:
942    LowLevelWalletWrite
943    + AddressStore<
944        Error = <Self as LowLevelWalletRead>::Error,
945        AccountRef = <Self as LowLevelWalletRead>::AccountRef,
946    >
947where
948    <Self as LowLevelWalletRead>::Error: From<GapError<Self>>,
949{
950}
951
952#[cfg(feature = "transparent-inputs")]
953impl<
954    T: LowLevelWalletWrite
955        + AddressStore<
956            Error = <T as LowLevelWalletRead>::Error,
957            AccountRef = <T as LowLevelWalletRead>::AccountRef,
958        >,
959> StoreDecryptedTxDbT for T
960where
961    <T as LowLevelWalletRead>::Error: From<GapError<T>>,
962{
963}
964
965/// Persists a decrypted transaction to the wallet database.
966///
967/// This function stores a transaction that has been decrypted by the wallet, including:
968/// - The transaction data and any computed fee (if all inputs are known)
969/// - Received shielded notes (Sapling and Orchard)
970/// - Sent outputs with recipient information
971/// - Transparent outputs received by or sent from the wallet
972/// - Nullifier tracking for spent notes
973///
974/// The function also queues requests for retrieval of any unknown transparent inputs,
975/// which may be needed to compute the transaction fee or track wallet history.
976///
977/// # Parameters
978/// - `wallet_db`: The wallet database to update.
979/// - `params`: The network parameters.
980/// - `chain_tip_height`: The current chain tip height, used as the observation height for
981///   unmined transactions.
982/// - `d_tx`: The decrypted transaction to store.
983///
984/// # Returns
985/// Returns `Ok(())` if the transaction was successfully stored, or an error if a database
986/// operation failed.
987pub fn store_decrypted_tx<DbT, P>(
988    wallet_db: &mut DbT,
989    params: &P,
990    #[cfg(feature = "transparent-inputs")] gap_limits: GapLimits,
991    chain_tip_height: BlockHeight,
992    d_tx: DecryptedTransaction<Transaction, <DbT as LowLevelWalletRead>::AccountId>,
993) -> Result<(), <DbT as LowLevelWalletRead>::Error>
994where
995    DbT: StoreDecryptedTxDbT,
996    <DbT as LowLevelWalletRead>::AccountId: core::fmt::Debug,
997    <DbT as LowLevelWalletRead>::Error: From<BalanceError> + From<GapError<DbT>>,
998    P: consensus::Parameters,
999{
1000    let funding_accounts = wallet_db.get_funding_accounts(d_tx.tx())?;
1001
1002    // TODO(#1305): Correctly track accounts that fund each transaction output.
1003    let funding_account = funding_accounts.iter().next().copied();
1004    if funding_accounts.len() > 1 {
1005        warn!(
1006            "More than one wallet account detected as funding transaction {:?}, selecting {:?}",
1007            d_tx.tx().txid(),
1008            funding_account.unwrap()
1009        )
1010    }
1011
1012    let wallet_transparent_outputs =
1013        detect_wallet_transparent_outputs::<_, _, <DbT as LowLevelWalletRead>::Error>(
1014            params,
1015            d_tx.tx(),
1016            d_tx.mined_height(),
1017            funding_account,
1018            #[cfg(feature = "transparent-inputs")]
1019            |address| wallet_db.find_account_for_transparent_address(address),
1020        )?;
1021
1022    // If there is no wallet involvement, we don't need to store the transaction, so just return
1023    // here.
1024    if funding_account.is_none()
1025        && wallet_transparent_outputs.is_empty()
1026        && !d_tx.has_decrypted_outputs()
1027    {
1028        wallet_db.delete_retrieval_queue_entries(d_tx.tx().txid())?;
1029        return Ok(());
1030    }
1031
1032    info!("Storing decrypted transaction with id {}", d_tx.tx().txid());
1033    let observed_height = d_tx.mined_height().unwrap_or(chain_tip_height + 1);
1034
1035    // If the transaction is fully shielded, or all transparent inputs are available, set the
1036    // fee value.
1037    let fee = determine_fee(wallet_db, d_tx.tx())?;
1038
1039    let tx_ref = wallet_db.put_tx_data(d_tx.tx(), fee, None, None, observed_height)?;
1040    if let Some(height) = d_tx.mined_height() {
1041        wallet_db.set_transaction_status(d_tx.tx().txid(), TransactionStatus::Mined(height))?;
1042    }
1043
1044    // Complete transaction data is in hand, so both involvement directions can be recorded: the
1045    // addresses paid by the outputs, and the addresses revealed by the inputs' `scriptSig`s.
1046    #[cfg(feature = "transparent-inputs")]
1047    wallet_db.put_transparent_address_observations(
1048        tx_ref,
1049        &crate::wallet::transparent_address_observations(d_tx.tx()),
1050    )?;
1051
1052    // Record how the transaction classifies against ZIP 318, so that a wallet can label a
1053    // migration transaction in its history without a migration plan, which does not survive a
1054    // seed restore. This is the one moment at which the parsed transaction and the decrypted
1055    // outputs are both in hand; a store recomputing it later would have neither.
1056    //
1057    // The SPECIFIED parameters are used rather than the store's own. The only value a wallet
1058    // overrides is the anchor bucket interval, and this evidence source cannot evaluate the anchor
1059    // clause at all (resolving an anchor to a height needs the retained boundary checkpoints), so
1060    // the override cannot change the answer. Deliberately not read from the store: `LowLevelWalletRead`
1061    // does not expose it, and adding a second accessor for a grid the store is the authority on is
1062    // exactly how two call sites come to disagree. Thread the store's parameters in here if a
1063    // future clause ever consults the grid.
1064    #[cfg(feature = "orchard")]
1065    {
1066        let migration_params = PoolMigrationParams::new(
1067            zcash_protocol::zip318::BlockSpacing::for_network(params),
1068            AnchorRetentionInterval::default(),
1069        );
1070        let classification = crate::data_api::zip318::classify_decrypted_tx(
1071            d_tx.tx(),
1072            d_tx.orchard_outputs(),
1073            d_tx.ironwood_outputs(),
1074            &migration_params,
1075        );
1076        wallet_db.put_zip318_classification(tx_ref, classification)?;
1077    }
1078
1079    let has_wallet_shielded_spend = mark_notes_spent(
1080        wallet_db,
1081        tx_ref,
1082        #[cfg(feature = "transparent-inputs")]
1083        d_tx.tx()
1084            .transparent_bundle()
1085            .iter()
1086            .flat_map(|b| b.vin.iter())
1087            .map(|txin| txin.prevout()),
1088        d_tx.tx()
1089            .sapling_bundle()
1090            .iter()
1091            .flat_map(|b| b.shielded_spends().iter())
1092            .map(|spend| spend.nullifier()),
1093        #[cfg(feature = "orchard")]
1094        d_tx.tx()
1095            .orchard_bundle()
1096            .iter()
1097            .flat_map(|b| b.actions().iter())
1098            .map(|action| action.nullifier()),
1099        #[cfg(feature = "orchard")]
1100        d_tx.tx()
1101            .ironwood_bundle()
1102            .iter()
1103            .flat_map(|b| b.actions().iter())
1104            .map(|action| action.nullifier()),
1105    )?;
1106
1107    // A flag used to determine whether it is necessary to query for transactions that
1108    // provided transparent inputs to this transaction, in order to be able to correctly
1109    // recover transparent transaction history.
1110    #[cfg(feature = "transparent-inputs")]
1111    let mut tx_has_wallet_outputs = false;
1112    #[cfg(feature = "transparent-inputs")]
1113    {
1114        tx_has_wallet_outputs |= !d_tx.sapling_outputs().is_empty();
1115
1116        #[cfg(feature = "orchard")]
1117        {
1118            tx_has_wallet_outputs |= !d_tx.orchard_outputs().is_empty();
1119            tx_has_wallet_outputs |= !d_tx.ironwood_outputs().is_empty();
1120        }
1121
1122        // Two cases handled here:
1123        // - If the wallet created the transparent output, we need to ensure
1124        //   that any transparent inputs belonging to the wallet will be
1125        //   discovered.
1126        // - Even if we know the funding account, we don't know that we have
1127        //   information for all of the transparent inputs to the transaction.
1128        tx_has_wallet_outputs |= !wallet_transparent_outputs.is_empty();
1129    }
1130
1131    // The set of account/scope pairs for which to update the gap limit.
1132    #[cfg(feature = "transparent-inputs")]
1133    let mut gap_update_set = HashSet::new();
1134
1135    put_shielded_outputs(
1136        wallet_db,
1137        params,
1138        tx_ref,
1139        funding_account,
1140        d_tx.sapling_outputs(),
1141        |_, _| Ok(None),
1142        |wallet_db, output, tx_ref, spent_in| {
1143            wallet_db.put_received_sapling_note(output, tx_ref, d_tx.mined_height(), spent_in)
1144        },
1145        |_account_id| {
1146            #[cfg(feature = "transparent-inputs")]
1147            gap_update_set.insert((_account_id, TransparentKeyScope::EXTERNAL));
1148        },
1149    )?;
1150
1151    #[cfg(feature = "orchard")]
1152    put_shielded_outputs(
1153        wallet_db,
1154        params,
1155        tx_ref,
1156        funding_account,
1157        d_tx.orchard_outputs(),
1158        |_, _| Ok(None),
1159        |wallet_db, output, tx_ref, spent_in| {
1160            wallet_db.put_received_orchard_note(output, tx_ref, d_tx.mined_height(), spent_in)
1161        },
1162        |_account_id| {
1163            #[cfg(feature = "transparent-inputs")]
1164            gap_update_set.insert((_account_id, TransparentKeyScope::EXTERNAL));
1165        },
1166    )?;
1167
1168    // Ironwood outputs are Orchard-shaped but belong to a distinct pool; store them in the
1169    // Ironwood tables rather than misfiling them alongside Orchard notes.
1170    #[cfg(feature = "orchard")]
1171    put_shielded_outputs(
1172        wallet_db,
1173        params,
1174        tx_ref,
1175        funding_account,
1176        d_tx.ironwood_outputs(),
1177        |_, _| Ok(None),
1178        |wallet_db, output, tx_ref, spent_in| {
1179            wallet_db.put_received_ironwood_note(output, tx_ref, d_tx.mined_height(), spent_in)
1180        },
1181        |_account_id| {
1182            #[cfg(feature = "transparent-inputs")]
1183            gap_update_set.insert((_account_id, TransparentKeyScope::EXTERNAL));
1184        },
1185    )?;
1186
1187    put_transparent_outputs(
1188        wallet_db,
1189        params,
1190        tx_ref,
1191        &wallet_transparent_outputs,
1192        #[cfg(feature = "transparent-inputs")]
1193        observed_height,
1194        #[cfg(feature = "transparent-inputs")]
1195        |account_id, t_key_scope| {
1196            gap_update_set.insert((account_id, t_key_scope));
1197        },
1198    )?;
1199
1200    // Regenerate the gap limit addresses.
1201    #[cfg(feature = "transparent-inputs")]
1202    for (account_id, key_scope) in gap_update_set {
1203        generate_transparent_gap_addresses(
1204            wallet_db,
1205            gap_limits,
1206            account_id,
1207            key_scope,
1208            UnifiedAddressRequest::unsafe_custom(Allow, Allow, Require),
1209        )?;
1210    }
1211
1212    // For each transaction that spends a transparent output of this transaction and does not
1213    // already have a known fee value, set the fee if possible.
1214    for (spending_tx_ref, spending_tx) in wallet_db.get_unknown_fee_spenders_of(tx_ref)? {
1215        if let Some(fee) = determine_fee(wallet_db, &spending_tx)? {
1216            wallet_db.update_tx_fee(spending_tx_ref, fee)?;
1217        }
1218    }
1219
1220    // If the transaction has outputs that belong to the wallet as well as transparent
1221    // inputs, we may need to download the transactions corresponding to the transparent
1222    // prevout references to determine whether the transaction was created (at least in
1223    // part) by this wallet.
1224    #[cfg(feature = "transparent-inputs")]
1225    if tx_has_wallet_outputs {
1226        wallet_db.queue_transparent_input_retrieval(tx_ref, &d_tx)?
1227    }
1228
1229    // Receiving complete transaction data satisfies enhancement intent, but must not erase a
1230    // durable status-observation intent created when the transaction was sent.
1231    wallet_db.delete_retrieval_queue_entries(d_tx.tx().txid())?;
1232
1233    // A shielded bundle is observable through compact-block scanning only when this wallet can
1234    // match one of its real nullifiers or decrypt one of its outputs. Transactions without either
1235    // capability require explicit status observation by txid.
1236    if d_tx.mined_height().is_none() && !(has_wallet_shielded_spend || d_tx.has_decrypted_outputs())
1237    {
1238        wallet_db.queue_tx_status(d_tx.tx().txid())?;
1239    }
1240
1241    Ok(())
1242}
1243
1244/// Returns the transparent outputs of `tx` for which the wallet should store records: those
1245/// paying an address of a wallet account, and, when `funding_account` is given, those paying
1246/// anyone else.
1247///
1248/// Each returned output carries the account that received it (`None` for a recipient outside the
1249/// wallet), the key scope at which the receiving address was derived, and `funding_account`. An
1250/// output whose script names no address the wallet understands is omitted.
1251///
1252/// `find_account_for_address` resolves a transparent address to the wallet account controlling
1253/// it, and the key scope at which it was derived.
1254pub fn detect_wallet_transparent_outputs<P, AccountId, E>(
1255    params: &P,
1256    tx: &Transaction,
1257    mined_height: Option<BlockHeight>,
1258    funding_account: Option<AccountId>,
1259    #[cfg(feature = "transparent-inputs")] find_account_for_address: impl Fn(
1260        &TransparentAddress,
1261    ) -> Result<
1262        Option<(AccountId, Option<TransparentKeyScope>)>,
1263        E,
1264    >,
1265) -> Result<Vec<WalletTransparentOutput<AccountId>>, E>
1266where
1267    P: consensus::Parameters,
1268    AccountId: Copy + core::fmt::Debug + std::hash::Hash + std::cmp::Eq,
1269{
1270    let mut result = vec![];
1271    for (output_index, txout) in tx
1272        .transparent_bundle()
1273        .iter()
1274        .flat_map(|b| b.vout.iter())
1275        .enumerate()
1276    {
1277        let script_kind = txout.script_kind();
1278        if let Some(address) = script_kind
1279            .as_ref()
1280            .and_then(TransparentAddress::from_script_kind)
1281        {
1282            debug!(
1283                "{:?} output {} has recipient {}",
1284                tx.txid(),
1285                output_index,
1286                address.encode(params)
1287            );
1288
1289            #[allow(unused_mut)]
1290            let mut detected = false;
1291
1292            // If the output belongs to the wallet, add it to `transparent_received_outputs`.
1293            #[cfg(feature = "transparent-inputs")]
1294            if let Some((account_uuid, key_scope)) = find_account_for_address(&address)? {
1295                debug!(
1296                    "{:?} output {} belongs to account {:?}",
1297                    tx.txid(),
1298                    output_index,
1299                    account_uuid
1300                );
1301                result.push(
1302                    WalletTransparentOutput::from_parts(
1303                        OutPoint::new(tx.txid().into(), u32::try_from(output_index).unwrap()),
1304                        txout.clone(),
1305                        mined_height,
1306                        Some(account_uuid),
1307                        key_scope,
1308                        funding_account,
1309                    )
1310                    .expect("txout.recipient_address extraction previously checked"),
1311                );
1312                detected = true;
1313            } else {
1314                debug!(
1315                    "Address {} is not recognized as belonging to any of our accounts.",
1316                    address.encode(params)
1317                );
1318            }
1319
1320            if !detected {
1321                // If a transaction we observe contains spends from our wallet, we will
1322                // store its transparent outputs in the same way they would be stored by
1323                // create_spend_to_address.
1324                if let Some(account_id) = funding_account {
1325                    result.push(
1326                        WalletTransparentOutput::from_parts(
1327                            OutPoint::new(tx.txid().into(), u32::try_from(output_index).unwrap()),
1328                            txout.clone(),
1329                            mined_height,
1330                            None,
1331                            None,
1332                            Some(account_id),
1333                        )
1334                        .expect("txout.recipient_address extraction previously checked"),
1335                    );
1336                }
1337            }
1338        } else if let Some(script_kind) = script_kind {
1339            // `OP_RETURN` (nulldata) outputs are provably-unspendable data carriers with
1340            // no recipient address; they are never wallet outputs, so skip them silently
1341            // rather than reporting them as unsupported.
1342            if !matches!(script_kind, ScriptKind::NullData { .. }) {
1343                warn!(
1344                    "Ignoring unsupported script kind '{}' for tx {} output {}",
1345                    script_kind.as_str(),
1346                    tx.txid(),
1347                    output_index
1348                );
1349            }
1350        } else {
1351            warn!(
1352                "Unable to determine recipient address for tx {} output {}",
1353                tx.txid(),
1354                output_index
1355            );
1356        }
1357    }
1358
1359    Ok(result)
1360}
1361
1362fn mark_notes_spent<'a, DbT>(
1363    wallet_db: &mut DbT,
1364    tx_ref: <DbT as LowLevelWalletRead>::TxRef,
1365    #[cfg(feature = "transparent-inputs")] transparent_prevouts: impl Iterator<
1366        Item = &'a transparent::bundle::OutPoint,
1367    >,
1368    sapling_nfs: impl Iterator<Item = &'a sapling::Nullifier>,
1369    #[cfg(feature = "orchard")] orchard_nfs: impl Iterator<Item = &'a orchard::note::Nullifier>,
1370    #[cfg(feature = "orchard")] ironwood_nfs: impl Iterator<Item = &'a orchard::note::Nullifier>,
1371) -> Result<bool, <DbT as LowLevelWalletRead>::Error>
1372where
1373    DbT: LowLevelWalletWrite,
1374{
1375    let mut has_wallet_shielded_spend = false;
1376
1377    // If any of the utxos spent in the transaction are ours, mark them as spent.
1378    #[cfg(feature = "transparent-inputs")]
1379    for outpoint in transparent_prevouts {
1380        wallet_db.mark_transparent_utxo_spent(outpoint, tx_ref)?;
1381    }
1382
1383    // Mark Sapling notes as spent when we observe their nullifiers.
1384    for nf in sapling_nfs {
1385        has_wallet_shielded_spend |= wallet_db.mark_sapling_note_spent(nf, tx_ref)?;
1386    }
1387
1388    // Mark Orchard notes as spent when we observe their nullifiers.
1389    #[cfg(feature = "orchard")]
1390    for nf in orchard_nfs {
1391        has_wallet_shielded_spend |= wallet_db.mark_orchard_note_spent(nf, tx_ref)?;
1392    }
1393
1394    // Mark Ironwood notes as spent when we observe their nullifiers.
1395    #[cfg(feature = "orchard")]
1396    for nf in ironwood_nfs {
1397        has_wallet_shielded_spend |= wallet_db.mark_ironwood_note_spent(nf, tx_ref)?;
1398    }
1399
1400    Ok(has_wallet_shielded_spend)
1401}
1402
1403/// Stores the wallet's records of the decrypted shielded outputs of one transaction.
1404///
1405/// Two kinds of record are stored for each output in `outputs`, which must all belong to the
1406/// transaction `tx_ref`:
1407///
1408/// - A received note, if a wallet account received the output. `put_received_note` stores it,
1409///   together with the transaction that `detect_note_spent_in` reports as already spending it.
1410///   `on_external_account` is then called with the receiving account if the output was received
1411///   at an external address. An output recovered with an outgoing viewing key was not received
1412///   by the wallet, so it has no received note.
1413/// - A sent-output record, if [`shielded_sent_output_recipient`] reports the output as a send
1414///   given `funding_account`, the wallet account known to have funded the transaction. This is
1415///   the only record stored for an output recovered with an outgoing viewing key.
1416#[allow(clippy::too_many_arguments)]
1417fn put_shielded_outputs<DbT, P, Output>(
1418    wallet_db: &mut DbT,
1419    params: &P,
1420    tx_ref: <DbT as LowLevelWalletRead>::TxRef,
1421    funding_account: Option<DbT::AccountId>,
1422    outputs: &[Output],
1423    detect_note_spent_in: impl Fn(
1424        &mut DbT,
1425        &Output,
1426    ) -> Result<
1427        Option<<DbT as LowLevelWalletRead>::TxRef>,
1428        <DbT as LowLevelWalletRead>::Error,
1429    >,
1430    put_received_note: impl Fn(
1431        &mut DbT,
1432        &Output,
1433        <DbT as LowLevelWalletRead>::TxRef,
1434        Option<<DbT as LowLevelWalletRead>::TxRef>,
1435    ) -> Result<(), <DbT as LowLevelWalletRead>::Error>,
1436    mut on_external_account: impl FnMut(<DbT as LowLevelWalletRead>::AccountId),
1437) -> Result<(), <DbT as LowLevelWalletRead>::Error>
1438where
1439    DbT: LowLevelWalletWrite,
1440    P: consensus::Parameters,
1441    Output: ReceivedShieldedOutput<AccountId = <DbT as LowLevelWalletRead>::AccountId>,
1442{
1443    for output in outputs {
1444        // Store the received note of an output that a wallet account received. An outgoing output
1445        // is one the wallet recovered with an outgoing viewing key, so the wallet did not receive
1446        // it; the only record stored for it is the sent-output record below.
1447        match output.transfer_type() {
1448            TransferType::AccountInternal => {
1449                let spent_in = detect_note_spent_in(wallet_db, output)?;
1450                put_received_note(wallet_db, output, tx_ref, spent_in)?;
1451            }
1452            TransferType::Incoming => {
1453                let spent_in = detect_note_spent_in(wallet_db, output)?;
1454                put_received_note(wallet_db, output, tx_ref, spent_in)?;
1455                on_external_account(output.account_id());
1456            }
1457            TransferType::Outgoing => {}
1458            TransferType::WalletInternal => unreachable!(
1459                "TransferType::WalletInternal is only produced for transparent outputs"
1460            ),
1461        }
1462
1463        if let Some((from_account_uuid, recipient, value)) =
1464            shielded_sent_output_recipient(params, output, funding_account, |account, receiver| {
1465                wallet_db.select_receiving_address(account, receiver)
1466            })?
1467        {
1468            wallet_db.put_sent_output(
1469                from_account_uuid,
1470                tx_ref,
1471                output.index(),
1472                &recipient,
1473                value,
1474                output.memo(),
1475            )?;
1476        }
1477    }
1478
1479    Ok(())
1480}
1481
1482/// The record a wallet makes for an output one of its accounts sent: the account that funded the
1483/// output, the recipient it paid, and its value.
1484pub type SentOutput<AccountId> = (AccountId, Recipient<AccountId>, Zatoshis);
1485
1486/// Returns the account to record as having sent a decrypted shielded output, the recipient to
1487/// record against it, and its value; or `None` where the wallet has no send to record.
1488///
1489/// An output recovered with an outgoing viewing key is a send from the account holding that key
1490/// to an external recipient. One decrypted with an account's internal key is a transfer within
1491/// that account. One decrypted with an account's external key is a send only when a wallet
1492/// account is known to have funded the transaction, and is then recorded as a transfer to the
1493/// receiving account, carrying the address it paid even though that address is external.
1494///
1495/// A recipient outside the wallet is reported at the wallet address containing the paid receiver
1496/// where `select_receiving_address` finds one, and at the receiver's own encoding otherwise.
1497/// `select_receiving_address` is consulted only for an output that names a recipient address: an
1498/// outgoing output, and an incoming output of a transaction with a known funding account.
1499///
1500/// # Panics
1501///
1502/// Panics if `output` reports [`TransferType::WalletInternal`], which is produced only for
1503/// transparent outputs.
1504pub fn shielded_sent_output_recipient<P, Output, E>(
1505    params: &P,
1506    output: &Output,
1507    funding_account: Option<Output::AccountId>,
1508    select_receiving_address: impl FnOnce(
1509        Output::AccountId,
1510        &Receiver,
1511    ) -> Result<Option<zcash_address::ZcashAddress>, E>,
1512) -> Result<Option<SentOutput<Output::AccountId>>, E>
1513where
1514    P: consensus::Parameters,
1515    Output: ReceivedShieldedOutput,
1516    Output::AccountId: Copy,
1517{
1518    Ok(match output.transfer_type() {
1519        TransferType::Outgoing => {
1520            let note = output.to_wallet_note();
1521
1522            let receiver = note.receiver();
1523            let recipient = Recipient::External {
1524                recipient_address: select_receiving_address(output.account_id(), &receiver)?
1525                    .unwrap_or_else(|| receiver.to_zcash_address(params.network_type())),
1526                output_pool: PoolType::Shielded(note.pool()),
1527            };
1528
1529            Some((output.account_id(), recipient, note.value()))
1530        }
1531        TransferType::AccountInternal => {
1532            let note = output.to_wallet_note();
1533            let value = note.value();
1534
1535            let recipient = Recipient::InternalShielded {
1536                receiving_account: output.account_id(),
1537                external_address: None,
1538                note: Box::new(note),
1539            };
1540
1541            Some((output.account_id(), recipient, value))
1542        }
1543        TransferType::Incoming => match funding_account {
1544            Some(account_id) => {
1545                let note = output.to_wallet_note();
1546                let value = note.value();
1547
1548                // Even if the recipient address is external, record the send as internal.
1549                let receiver = note.receiver();
1550                let recipient = Recipient::InternalShielded {
1551                    receiving_account: output.account_id(),
1552                    external_address: Some(
1553                        select_receiving_address(output.account_id(), &receiver)?
1554                            .unwrap_or_else(|| receiver.to_zcash_address(params.network_type())),
1555                    ),
1556                    note: Box::new(note),
1557                };
1558
1559                Some((account_id, recipient, value))
1560            }
1561            None => None,
1562        },
1563        TransferType::WalletInternal => {
1564            unreachable!("TransferType::WalletInternal is only produced for transparent outputs")
1565        }
1566    })
1567}
1568
1569/// Records the wallet's receipt of `output` if its recipient address belongs to a wallet
1570/// account, and queues the resulting outpoint for transparent spend detection.
1571///
1572/// An output whose recipient address belongs to no wallet account is ignored; recording such an
1573/// output as a send is the caller's responsibility.
1574///
1575/// `observation_height` is the height as of which the output was observed: the height of the
1576/// containing block for an output discovered in a mined block, or the caller's best estimate of
1577/// the chain tip for one discovered in an unmined transaction. The output is never recorded as
1578/// known-unspent, because neither observing it in a block nor receiving complete data for the
1579/// transaction that created it establishes that it is still a member of the UTXO set; only a
1580/// query of that set can do so.
1581///
1582/// `on_received` is invoked with the receiving account and key scope when the output is recorded,
1583/// so that a caller which does not otherwise track address use can extend the transparent address
1584/// gap for that account.
1585#[cfg(feature = "transparent-inputs")]
1586fn put_received_transparent_output<DbT>(
1587    wallet_db: &mut DbT,
1588    tx_ref: <DbT as LowLevelWalletRead>::TxRef,
1589    output: &WalletTransparentOutput<<DbT as LowLevelWalletRead>::AccountId>,
1590    observation_height: BlockHeight,
1591    mut on_received: impl FnMut(<DbT as LowLevelWalletRead>::AccountId, TransparentKeyScope),
1592) -> Result<(), <DbT as LowLevelWalletRead>::Error>
1593where
1594    DbT: LowLevelWalletWrite,
1595{
1596    if output.recipient_account().is_none() {
1597        return Ok(());
1598    }
1599
1600    let (account_id, _) = wallet_db.put_transparent_output(output, observation_height, false)?;
1601
1602    if let Some(t_key_scope) = output.recipient_key_scope() {
1603        on_received(account_id, t_key_scope);
1604    }
1605
1606    // Queue this outpoint for explicit transparent-spend detection.
1607    //
1608    // Unlike shielded notes -- whose spends are detected naturally during
1609    // scanning via nullifier matching -- transparent spends are only found
1610    // when the wallet already knows which outpoints to watch. For receives at
1611    // ordinary transparent addresses this is handled by indexer-driven address
1612    // watches, but for receives at ephemeral addresses (e.g. the middle hop of
1613    // a ZIP 320 / TEX flow) there is no ongoing watch. A purely-transparent
1614    // spend of such an output would otherwise go undetected. This is especially
1615    // a problem in wallet recovery, where transactions can be processed out of
1616    // order: queuing here ensures the spend is detected even when the receive
1617    // side is processed first.
1618    wallet_db.queue_transparent_spend_detection(
1619        *output.recipient_address(),
1620        tx_ref,
1621        output.outpoint().n(),
1622    )?;
1623
1624    Ok(())
1625}
1626
1627/// Records both sides of each transparent output of a transaction: the wallet's receipt of
1628/// those outputs that pay one of its accounts, and, for each output that names a funding
1629/// account, the corresponding sent output.
1630///
1631/// `observation_height` is the height as of which the outputs were observed; see
1632/// [`put_received_transparent_output`].
1633fn put_transparent_outputs<DbT, P>(
1634    wallet_db: &mut DbT,
1635    params: &P,
1636    tx_ref: <DbT as LowLevelWalletRead>::TxRef,
1637    outputs: &[WalletTransparentOutput<<DbT as LowLevelWalletRead>::AccountId>],
1638    #[cfg(feature = "transparent-inputs")] observation_height: BlockHeight,
1639    #[cfg(feature = "transparent-inputs")] mut on_received: impl FnMut(
1640        <DbT as LowLevelWalletRead>::AccountId,
1641        TransparentKeyScope,
1642    ),
1643) -> Result<(), <DbT as LowLevelWalletRead>::Error>
1644where
1645    DbT: LowLevelWalletWrite,
1646    P: consensus::Parameters,
1647{
1648    for output in outputs {
1649        // Receive side: record the output as received whenever its recipient
1650        // address belongs to a wallet account.
1651        #[cfg(feature = "transparent-inputs")]
1652        put_received_transparent_output(
1653            wallet_db,
1654            tx_ref,
1655            output,
1656            observation_height,
1657            &mut on_received,
1658        )?;
1659
1660        // Send side: record the output as sent for the wallet account that
1661        // funded the transaction, if any. If the recipient is also a wallet
1662        // account, the send is recorded as an internal transfer.
1663        if let Some((from_account, recipient)) =
1664            transparent_sent_output_recipient(params, output, |account, receiver| {
1665                wallet_db.select_receiving_address(account, receiver)
1666            })?
1667        {
1668            wallet_db.put_sent_output(
1669                from_account,
1670                tx_ref,
1671                output.index(),
1672                &recipient,
1673                output.value(),
1674                None,
1675            )?;
1676        }
1677    }
1678
1679    Ok(())
1680}
1681
1682/// Returns the account that funded a transparent output and the recipient to record against it,
1683/// or `None` if no wallet account is known to have funded it.
1684///
1685/// An output paying an address of a wallet account is an internal transfer; one paying any other
1686/// address is a send to an external recipient, reported at the wallet address containing the
1687/// paid receiver where `select_receiving_address` finds one and at the bare transparent address
1688/// otherwise.
1689///
1690/// `select_receiving_address` returns the most likely wallet address containing the given
1691/// receiver, or `None` if the receiver belongs to no address of that account. It is consulted in
1692/// every feature configuration. The `transparent-inputs` feature governs only whether an output
1693/// can be recognized as paying a wallet account: without it none is, so every output is recorded
1694/// as a send to an external recipient, still reported at the address containing the receiver.
1695pub fn transparent_sent_output_recipient<AccountId, P, E>(
1696    params: &P,
1697    output: &WalletTransparentOutput<AccountId>,
1698    select_receiving_address: impl FnOnce(
1699        AccountId,
1700        &Receiver,
1701    ) -> Result<Option<zcash_address::ZcashAddress>, E>,
1702) -> Result<Option<(AccountId, Recipient<AccountId>)>, E>
1703where
1704    AccountId: Copy,
1705    P: consensus::Parameters,
1706{
1707    let Some(&from_account) = output.funding_account() else {
1708        return Ok(None);
1709    };
1710
1711    let recipient = match output.recipient_account() {
1712        #[cfg(feature = "transparent-inputs")]
1713        Some(&receiving_account) => Recipient::InternalTransparent {
1714            receiving_account,
1715            recipient_address: *output.recipient_address(),
1716        },
1717        #[cfg(not(feature = "transparent-inputs"))]
1718        Some(_) => Recipient::External {
1719            recipient_address: Receiver::Transparent(*output.recipient_address())
1720                .to_zcash_address(params.network_type()),
1721            output_pool: PoolType::TRANSPARENT,
1722        },
1723        None => {
1724            let receiver = Receiver::Transparent(*output.recipient_address());
1725            let recipient_address = select_receiving_address(from_account, &receiver)?
1726                .unwrap_or_else(|| receiver.to_zcash_address(params.network_type()));
1727
1728            Recipient::External {
1729                recipient_address,
1730                output_pool: PoolType::TRANSPARENT,
1731            }
1732        }
1733    };
1734
1735    Ok(Some((from_account, recipient)))
1736}
1737
1738/// Creates subtrees from note commitments in parallel.
1739///
1740/// `commitments` is an `&mut [Option<_>]` to emulate move semantics inside a `rayon`
1741/// parallel iterator; every entry must be `Some` on entry, and every entry will have been
1742/// taken on return.
1743///
1744/// Returns each located subtree together with the map from checkpointed block height to
1745/// note commitment tree position within that subtree.
1746pub fn build_subtrees<H, const SHARD_HEIGHT: u8>(
1747    start_position: Position,
1748    commitments: &mut [Option<(H, Retention<BlockHeight>)>],
1749    chunk_size: usize,
1750) -> Vec<(LocatedPrunableTree<H>, BTreeMap<BlockHeight, Position>)>
1751where
1752    H: Clone + PartialEq + Hashable + Send + Sync,
1753{
1754    commitments
1755        .par_chunks_mut(chunk_size)
1756        .enumerate()
1757        .filter_map(|(i, chunk)| {
1758            let start = start_position + (i * chunk_size) as u64;
1759            let end = start + chunk.len() as u64;
1760
1761            shardtree::LocatedTree::from_iter(
1762                start..end,
1763                SHARD_HEIGHT.into(),
1764                chunk.iter_mut().map(|n| n.take().expect("always Some")),
1765            )
1766        })
1767        .map(|res| (res.subtree, res.checkpoints))
1768        .collect()
1769}
1770
1771/// Produces an overall set of checkpoints from a list of subtrees.
1772pub fn checkpoint_positions<H>(
1773    subtrees: &[(LocatedPrunableTree<H>, BTreeMap<BlockHeight, Position>)],
1774) -> BTreeMap<BlockHeight, Position> {
1775    subtrees
1776        .iter()
1777        .flat_map(|(_, checkpoints)| checkpoints.iter())
1778        .map(|(k, v)| (*k, *v))
1779        .collect()
1780}
1781
1782/// Produces the checkpoints that must be added to a pool's note commitment tree so that it
1783/// gains a checkpoint at each of the requested heights. A height in `created_checkpoints` is
1784/// skipped, since inserting the batch's subtrees creates its checkpoint. Any other height
1785/// receives a checkpoint at the position recorded in `block_end_positions` for the nearest block
1786/// at or below it that carries a commitment, or at the provided frontier's position when no
1787/// such block precedes it in the batch.
1788pub fn ensure_checkpoints<'a, H, I: Iterator<Item = &'a BlockHeight>, const DEPTH: u8>(
1789    ensure_heights: I,
1790    created_checkpoints: &BTreeSet<BlockHeight>,
1791    block_end_positions: &BTreeMap<BlockHeight, Position>,
1792    state_final_tree: &Frontier<H, DEPTH>,
1793) -> Vec<(BlockHeight, Checkpoint)> {
1794    ensure_heights
1795        .filter(|ensure_height| !created_checkpoints.contains(ensure_height))
1796        .map(|ensure_height| {
1797            let checkpoint = block_end_positions
1798                .range::<BlockHeight, _>(..=*ensure_height)
1799                .last()
1800                .map_or_else(
1801                    || {
1802                        state_final_tree
1803                            .value()
1804                            .map_or_else(Checkpoint::tree_empty, |t| {
1805                                Checkpoint::at_position(t.position())
1806                            })
1807                    },
1808                    |(_, position)| Checkpoint::at_position(*position),
1809                );
1810            (*ensure_height, checkpoint)
1811        })
1812        .collect::<Vec<_>>()
1813}
1814
1815/// The number of trailing blocks in a batch whose spend-map entries are always retained,
1816/// even when [`put_blocks_rows`] can prove that insertion is skippable. This keeps the
1817/// maps' contents aligned with a [`LowLevelWalletWrite::prune_tracked_spends`] pruning
1818/// depth of the same value, and comfortably exceeds the maximum reorg depth the wallet
1819/// tolerates.
1820///
1821/// [`LowLevelWalletWrite::prune_tracked_spends`]: super::LowLevelWalletWrite::prune_tracked_spends
1822pub const SPEND_MAP_RETENTION_BLOCKS: u32 = 100;
1823
1824/// Derives the spend-tracking floor for one [`put_blocks_rows`] batch (see the
1825/// "Spend tracking" section of its documentation).
1826///
1827/// Returns `Some` only when the batch extends the contiguous fully-scanned frontier
1828/// (`fully_scanned == Some(from_state_height)`) and is long enough that a floor above
1829/// `from_state_height` retains the full [`SPEND_MAP_RETENTION_BLOCKS`] trailing
1830/// window; every out-of-order or short batch derives `None` and tracks fully.
1831fn spend_tracking_floor(
1832    fully_scanned: Option<BlockHeight>,
1833    from_state_height: BlockHeight,
1834    batch_end: Option<BlockHeight>,
1835) -> Option<BlockHeight> {
1836    if fully_scanned == Some(from_state_height) {
1837        batch_end.and_then(|last| {
1838            let floor =
1839                BlockHeight::from(u32::from(last).saturating_sub(SPEND_MAP_RETENTION_BLOCKS));
1840            (floor > from_state_height + 1).then_some(floor)
1841        })
1842    } else {
1843        None
1844    }
1845}
1846
1847/// Returns whether the spends observed in a block at `block_height` should be inserted into
1848/// the spend maps.
1849///
1850/// Tracking is skipped only when a `spend_tracking_floor` was derived and
1851/// `block_height` lies strictly below it; with no floor, every block's spends are
1852/// tracked. See the "Spend tracking" section of [`put_blocks_rows`].
1853fn should_track_spends(
1854    spend_tracking_floor: Option<BlockHeight>,
1855    block_height: BlockHeight,
1856) -> bool {
1857    spend_tracking_floor.is_none_or(|floor| block_height >= floor)
1858}
1859
1860/// Returns whether the checkpoint at `height` should be retained as a durable anchor: anchor
1861/// retention is enabled at all (`anchor_retention` is `Some`) and its policy
1862/// [retains](AnchorRetention::retains) `height`.
1863fn should_retain_anchor(anchor_retention: Option<&AnchorRetention>, height: BlockHeight) -> bool {
1864    anchor_retention.is_some_and(|retention| retention.retains(height))
1865}
1866
1867/// Retains `height` as a durable anchor checkpoint when [`should_retain_anchor`] holds.
1868fn retain_anchor_checkpoint<S, const DEPTH: u8, const SHARD_HEIGHT: u8>(
1869    tree: &mut ShardTree<S, DEPTH, SHARD_HEIGHT>,
1870    anchor_retention: Option<&AnchorRetention>,
1871    height: BlockHeight,
1872) -> Result<(), ShardTreeError<S::Error>>
1873where
1874    S: ShardStore<CheckpointId = BlockHeight>,
1875    S::H: Clone + PartialEq + Hashable,
1876{
1877    if should_retain_anchor(anchor_retention, height) {
1878        tree.ensure_retained(height)?;
1879    }
1880    Ok(())
1881}
1882
1883/// Given the checkpoint heights present in each of the three shielded pools' note commitment
1884/// trees, in the order (Sapling, Orchard, Ironwood), returns for each pool the set of checkpoint
1885/// heights it must ensure so that every pool ends up checkpointed at every height that is
1886/// checkpointed in any pool.
1887///
1888/// The set returned for a given pool is the union of the checkpoint heights of the other two
1889/// pools. Consequently the union of a pool's existing checkpoint heights with the heights returned
1890/// for it equals the union of all three pools' checkpoint heights, so all three trees end up
1891/// checkpointed at the same set of heights. When one pool has no checkpoints, the sets returned for
1892/// the other two reduce to each other's heights, matching the prior two-pool behavior.
1893pub fn cross_pool_ensure_heights(
1894    sapling: &BTreeSet<BlockHeight>,
1895    orchard: &BTreeSet<BlockHeight>,
1896    ironwood: &BTreeSet<BlockHeight>,
1897) -> [BTreeSet<BlockHeight>; 3] {
1898    let union = |a: &BTreeSet<BlockHeight>, b: &BTreeSet<BlockHeight>| {
1899        a.union(b).copied().collect::<BTreeSet<BlockHeight>>()
1900    };
1901    [
1902        union(orchard, ironwood),
1903        union(sapling, ironwood),
1904        union(sapling, orchard),
1905    ]
1906}
1907
1908/// Given the checkpoint heights present in each of the three shielded pools' note commitment trees,
1909/// in the order (Sapling, Orchard, Ironwood), returns for each pool the complete set of checkpoint
1910/// heights it must ensure for a batch of scanned blocks covering `range`.
1911///
1912/// This is the whole of the rule, and the set a caller passes to [`ensure_checkpoints`]. It is the
1913/// union of two obligations, and satisfying only the first is a silent correctness bug:
1914///
1915/// 1. **Cross-pool alignment** ([`cross_pool_ensure_heights`]): every pool must be checkpointed at
1916///    every height that is checkpointed in any pool, so anchors align across trees.
1917/// 2. **Anchor retention**: every height `anchor_retention` retains within `range`. Scanning
1918///    checkpoints a block only at its last note commitment, so a grid boundary landing on a block
1919///    with no shielded output in ANY pool is never checkpointed by (1) either — and a retention
1920///    policy can only keep alive a checkpoint that EXISTS. [`AnchorRetention`] is a promise to
1921///    preserve a checkpoint, never to create one: omit this step and a consumer marks boundary
1922///    heights that never materialize, leaving anything anchored to them permanently unprovable.
1923///
1924/// Obligation (2) has no effect when `anchor_retention` is `None`, so a caller with no retention
1925/// policy gets exactly [`cross_pool_ensure_heights`].
1926///
1927/// [`put_blocks`] calls this. It is public so that a consumer maintaining its note commitment trees
1928/// by other means — accumulating updates in memory and flushing in bulk, or building shards out of
1929/// band — composes the same set rather than rediscovering the rule, which is why the two obligations
1930/// live behind one function instead of at each call site.
1931pub fn batch_ensure_heights(
1932    sapling: &BTreeSet<BlockHeight>,
1933    orchard: &BTreeSet<BlockHeight>,
1934    ironwood: &BTreeSet<BlockHeight>,
1935    anchor_retention: Option<&AnchorRetention>,
1936    range: std::ops::RangeInclusive<BlockHeight>,
1937    window_heights: &BTreeSet<BlockHeight>,
1938) -> [BTreeSet<BlockHeight>; 3] {
1939    let mut ensure = cross_pool_ensure_heights(sapling, orchard, ironwood);
1940
1941    for pool in ensure.iter_mut() {
1942        pool.extend(window_heights.iter().copied());
1943    }
1944
1945    if let Some(retention) = anchor_retention {
1946        let retained = retention.retained_in_range(range);
1947        for pool in ensure.iter_mut() {
1948            pool.extend(retained.iter().copied());
1949        }
1950    }
1951
1952    ensure
1953}
1954
1955/// Updates the given note commitment tree with all newly read note commitments starting
1956/// at the block `frontier_height + 1`.
1957///
1958/// `missing_checkpoints` supplies the checkpoints that no commitment in `subtrees` creates. Each
1959/// is added whatever its height. The frontier's leaf is inserted as follows:
1960///
1961/// - If `frontier_height` is above `checkpoint_floor`, or `anchor_retention` retains it, the
1962///   frontier is checkpointed at `frontier_height`.
1963/// - Otherwise, if an entry of `missing_checkpoints` lies at the frontier's position, the
1964///   frontier carries the checkpoint for the lowest such entry, so the tree keeps the leaf that
1965///   the other entries at that position refer to.
1966/// - Otherwise the frontier's leaf is kept as a reference only.
1967///
1968/// If `anchor_retention` is `Some`, every checkpoint the policy
1969/// [retains](AnchorRetention::retains) is kept as a durable anchor.
1970///
1971/// This is generic over the [`ShardStore`] backing the tree, so stores that maintain their note
1972/// commitment trees by other means (for example, accumulating updates in memory and flushing
1973/// them in bulk) can reuse the exact tree-update logic that [`put_blocks`] applies.
1974#[allow(clippy::too_many_arguments)]
1975pub fn update_tree<S, const DEPTH: u8, const SHARD_HEIGHT: u8>(
1976    protocol: &'static str,
1977    frontier: &Frontier<S::H, DEPTH>,
1978    frontier_height: BlockHeight,
1979    checkpoint_floor: BlockHeight,
1980    tree: &mut ShardTree<S, DEPTH, SHARD_HEIGHT>,
1981    anchor_retention: Option<&AnchorRetention>,
1982    subtrees: impl Iterator<Item = (LocatedPrunableTree<S::H>, BTreeMap<BlockHeight, Position>)>,
1983    missing_checkpoints: impl Iterator<Item = (BlockHeight, Checkpoint)>,
1984) -> Result<(), ShardTreeError<S::Error>>
1985where
1986    S: ShardStore<CheckpointId = BlockHeight>,
1987    S::H: Clone + PartialEq + Hashable,
1988{
1989    debug!(
1990        "{protocol} initial tree size at {frontier_height:?}: {:?}",
1991        frontier.tree_size()
1992    );
1993    let mut missing_checkpoints = missing_checkpoints.collect::<Vec<_>>();
1994
1995    // Inside the checkpoint window the frontier is inserted with `Checkpoint` retention, so
1996    // that the tree can be truncated back to this point. Below the window, the frontier carries
1997    // the lowest missing checkpoint at its position, if there is one; that entry is then created
1998    // with the frontier, so the tree keeps the leaf the other entries at the position refer to.
1999    // Otherwise the frontier's leaf is kept as a reference only.
2000    let frontier_checkpoint = if frontier_height > checkpoint_floor
2001        || should_retain_anchor(anchor_retention, frontier_height)
2002    {
2003        Some(frontier_height)
2004    } else {
2005        let frontier_position = frontier.value().map(|leaf| leaf.position());
2006        missing_checkpoints
2007            .iter()
2008            .enumerate()
2009            .filter(|(_, (_, checkpoint))| {
2010                frontier_position.is_some() && checkpoint.position() == frontier_position
2011            })
2012            .min_by_key(|(_, (height, _))| *height)
2013            .map(|(entry_index, _)| entry_index)
2014            .map(|entry_index| missing_checkpoints.remove(entry_index).0)
2015    };
2016    let frontier_retention =
2017        frontier_checkpoint.map_or(Retention::Reference, |id| Retention::Checkpoint {
2018            id,
2019            marking: Marking::Reference,
2020        });
2021    if let Some(id) = frontier_checkpoint {
2022        retain_anchor_checkpoint(tree, anchor_retention, id)?;
2023    }
2024    tree.insert_frontier(frontier.clone(), frontier_retention)?;
2025
2026    for (subtree, checkpoints) in subtrees {
2027        // Register anchor retention for this batch's checkpoint heights *before* `insert_tree`,
2028        // which prunes down to `max_checkpoints` during insertion. A batch larger than the
2029        // checkpoint budget would otherwise prune an anchor before it could be retained, so
2030        // retention must be recorded first; `ShardTree::ensure_retained` accepts a checkpoint
2031        // height whose checkpoint does not yet exist.
2032        for height in checkpoints.keys() {
2033            retain_anchor_checkpoint(tree, anchor_retention, *height)?;
2034        }
2035        tree.insert_tree(subtree, checkpoints)?;
2036    }
2037
2038    // Add each remaining checkpoint. A checkpoint created above, at the same position, keeps
2039    // the leaf that each of these refers to, so they are added at any height, including below
2040    // the tree's oldest checkpoint.
2041    for (height, checkpoint) in missing_checkpoints {
2042        debug!(
2043            "Adding missing {protocol} checkpoint for height: {:?}: {:?}",
2044            height,
2045            checkpoint.position()
2046        );
2047        retain_anchor_checkpoint(tree, anchor_retention, height)?;
2048        tree.store_mut()
2049            .add_checkpoint(height, checkpoint)
2050            .map_err(ShardTreeError::Storage)?;
2051    }
2052
2053    Ok(())
2054}
2055
2056/// The checkpoint floor of a batch of scanned blocks ending at `last_scanned_height`: the
2057/// height at and below which no block end of the batch keeps its own checkpoint.
2058///
2059/// `Checkpoint` retention is used only within [`PRUNING_DEPTH`] blocks of the later of
2060/// `chain_tip` (the wallet's view of the chain tip, if known) and `last_scanned_height`. A
2061/// block-end checkpoint below that window would be pruned as soon as the window advanced, so
2062/// such a commitment keeps only the marking that protects a wallet note. Retained anchor
2063/// heights are checkpointed regardless ([`keeps_checkpoint`]).
2064pub fn checkpoint_floor(
2065    chain_tip: Option<BlockHeight>,
2066    last_scanned_height: BlockHeight,
2067) -> BlockHeight {
2068    let reference_tip = chain_tip.map_or(last_scanned_height, |tip| tip.max(last_scanned_height));
2069    reference_tip.saturating_sub(PRUNING_DEPTH)
2070}
2071
2072/// Whether a block end at `height` keeps its own checkpoint: it does inside the checkpoint
2073/// window (above `checkpoint_floor`, see [`checkpoint_floor`]), and at a height the
2074/// anchor-retention policy retains.
2075pub fn keeps_checkpoint(
2076    checkpoint_floor: BlockHeight,
2077    anchor_retention: Option<&AnchorRetention>,
2078    height: BlockHeight,
2079) -> bool {
2080    height > checkpoint_floor || should_retain_anchor(anchor_retention, height)
2081}
2082
2083/// The checkpoints that a batch of scanned blocks adds to the wallet's note commitment trees
2084/// beyond those its own commitments create, as [`put_blocks`] computes them before it builds
2085/// the batch's subtrees ([`batch_checkpoints`]).
2086#[derive(Debug)]
2087pub struct BatchCheckpoints {
2088    /// The batch's checkpoint floor ([`checkpoint_floor`]).
2089    pub checkpoint_floor: BlockHeight,
2090    /// The checkpoints to add to the Sapling tree, each at the tree position it refers to.
2091    pub sapling: Vec<(BlockHeight, Checkpoint)>,
2092    /// The checkpoints to add to the Orchard tree.
2093    #[cfg(feature = "orchard")]
2094    pub orchard: Vec<(BlockHeight, Checkpoint)>,
2095    /// The checkpoints to add to the Ironwood tree.
2096    #[cfg(feature = "orchard")]
2097    pub ironwood: Vec<(BlockHeight, Checkpoint)>,
2098}
2099
2100/// Computes the checkpoints that the batch of scanned blocks above `from_state` through
2101/// `last_scanned_height` must add to each note commitment tree beyond those its own
2102/// commitments create. Each `*_commitments` slice is a pool's commitment stream for the batch
2103/// as [`put_blocks_rows`] returns it, with the scanner's `Checkpoint` retention still on every
2104/// block end: the stream is read before any demotion, so that a checkpoint ensured below the
2105/// window (a retained anchor) still lands on the right tree state.
2106///
2107/// Every tree gains a checkpoint at every height that is checkpointed in any of the other
2108/// trees, so that anchors align across trees. Every scanned height inside the checkpoint window
2109/// ([`checkpoint_floor`]) is checkpointed in every tree, whether or not a block there carries a
2110/// commitment, so that an anchor exists at the confirmations-policy depth. The heights the
2111/// anchor-retention policy retains within the batch are checkpointed likewise: a grid boundary
2112/// landing on a block with no shielded outputs in ANY pool would otherwise never be
2113/// checkpointed at all, and a retention policy can only keep alive a checkpoint that exists.
2114/// An ensured checkpoint carries the tree state as of the last commitment at or before its
2115/// height, which is exactly the state an anchor at that height commits to. A height whose
2116/// block end keeps its own checkpoint ([`keeps_checkpoint`]) is left to that block end.
2117///
2118/// This is the checkpoint planning of [`put_blocks`], exposed so that a store that maintains
2119/// its note commitment trees by other means (accumulating updates in memory and flushing them
2120/// in bulk, or building shards out of band) applies the same rule rather than rediscovering
2121/// it. Such a caller assigns the block-end retentions of the commitments it builds with
2122/// [`assign_block_end_retention`], then hands the entries that remain to [`update_tree`].
2123pub fn batch_checkpoints<SH, #[cfg(feature = "orchard")] OH>(
2124    from_state: &ChainState,
2125    last_scanned_height: BlockHeight,
2126    chain_tip: Option<BlockHeight>,
2127    anchor_retention: Option<&AnchorRetention>,
2128    sapling_commitments: &[Option<(SH, Retention<BlockHeight>)>],
2129    #[cfg(feature = "orchard")] orchard_commitments: &[Option<(OH, Retention<BlockHeight>)>],
2130    #[cfg(feature = "orchard")] ironwood_commitments: &[Option<(OH, Retention<BlockHeight>)>],
2131) -> BatchCheckpoints {
2132    let checkpoint_floor = checkpoint_floor(chain_tip, last_scanned_height);
2133
2134    // The tree position at the end of every block that carries a commitment.
2135    let sapling_block_ends = block_end_positions(
2136        Position::from(from_state.final_sapling_tree().tree_size()),
2137        sapling_commitments,
2138    );
2139    #[cfg(feature = "orchard")]
2140    let orchard_block_ends = block_end_positions(
2141        Position::from(from_state.final_orchard_tree().tree_size()),
2142        orchard_commitments,
2143    );
2144    #[cfg(feature = "orchard")]
2145    let ironwood_block_ends = block_end_positions(
2146        Position::from(from_state.final_ironwood_tree().tree_size()),
2147        ironwood_commitments,
2148    );
2149
2150    // Every block end that keeps its own checkpoint.
2151    let created_heights = |block_ends: &BTreeMap<BlockHeight, Position>| {
2152        block_ends
2153            .keys()
2154            .copied()
2155            .filter(|height| keeps_checkpoint(checkpoint_floor, anchor_retention, *height))
2156            .collect::<BTreeSet<BlockHeight>>()
2157    };
2158    let sapling_created = created_heights(&sapling_block_ends);
2159    #[cfg(feature = "orchard")]
2160    let orchard_created = created_heights(&orchard_block_ends);
2161    #[cfg(feature = "orchard")]
2162    let ironwood_created = created_heights(&ironwood_block_ends);
2163    #[cfg(not(feature = "orchard"))]
2164    let (orchard_created, ironwood_created) = (BTreeSet::new(), BTreeSet::new());
2165
2166    let window_heights = (u32::from(from_state.block_height()) + 1
2167        ..=u32::from(last_scanned_height))
2168        .map(BlockHeight::from)
2169        .filter(|height| *height > checkpoint_floor)
2170        .collect::<BTreeSet<BlockHeight>>();
2171
2172    let [ensure_sapling, ensure_orchard, ensure_ironwood] = batch_ensure_heights(
2173        &sapling_created,
2174        &orchard_created,
2175        &ironwood_created,
2176        anchor_retention,
2177        from_state.block_height() + 1..=last_scanned_height,
2178        &window_heights,
2179    );
2180    #[cfg(not(feature = "orchard"))]
2181    let _ = (ensure_orchard, ensure_ironwood);
2182
2183    BatchCheckpoints {
2184        checkpoint_floor,
2185        sapling: ensure_checkpoints(
2186            ensure_sapling.iter(),
2187            &sapling_created,
2188            &sapling_block_ends,
2189            from_state.final_sapling_tree(),
2190        ),
2191        #[cfg(feature = "orchard")]
2192        orchard: ensure_checkpoints(
2193            ensure_orchard.iter(),
2194            &orchard_created,
2195            &orchard_block_ends,
2196            from_state.final_orchard_tree(),
2197        ),
2198        #[cfg(feature = "orchard")]
2199        ironwood: ensure_checkpoints(
2200            ensure_ironwood.iter(),
2201            &ironwood_created,
2202            &ironwood_block_ends,
2203            from_state.final_ironwood_tree(),
2204        ),
2205    }
2206}
2207
2208/// Returns the tree position at the end of each block in `commitments` that carries a
2209/// commitment, keyed by block height. The scanner marks a block's last commitment with
2210/// `Checkpoint` retention, which is what identifies the block end here.
2211fn block_end_positions<H>(
2212    start_position: Position,
2213    commitments: &[Option<(H, Retention<BlockHeight>)>],
2214) -> BTreeMap<BlockHeight, Position> {
2215    commitments
2216        .iter()
2217        .enumerate()
2218        .filter_map(|(i, entry)| match entry {
2219            Some((_, Retention::Checkpoint { id, .. })) => Some((*id, start_position + i as u64)),
2220            _ => None,
2221        })
2222        .collect()
2223}
2224
2225/// Sets the retention of each block-end commitment in `commitments`, the first of which is at
2226/// `start_position`.
2227///
2228/// A block end that [keeps its checkpoint](keeps_checkpoint) under `checkpoint_floor` and
2229/// `anchor_retention` is left as it is. Any other block end gives up its checkpoint, except
2230/// where an entry of `missing_checkpoints` lies at its position: the commitment then carries
2231/// the checkpoint for the lowest such height, and that entry is removed from
2232/// `missing_checkpoints`. The commitment and its checkpoint are then inserted together, so the
2233/// tree keeps the leaf that the remaining entries at that position refer to. A commitment that
2234/// gives up its checkpoint keeps only its marking: a wallet note's commitment stays `Marked`, a
2235/// referenced commitment stays `Reference`, and any other commitment becomes `Ephemeral`.
2236///
2237/// `missing_checkpoints` is a batch's [`BatchCheckpoints`] for the pool. A store that builds
2238/// only part of a batch's commitments now (and the rest out of band) assigns each part it
2239/// builds, from that part's first position; an entry at a position it does not build stays in
2240/// `missing_checkpoints`, and [`update_tree`] adds it as a checkpoint of the store.
2241pub fn assign_block_end_retention<H>(
2242    commitments: &mut [Option<(H, Retention<BlockHeight>)>],
2243    start_position: Position,
2244    checkpoint_floor: BlockHeight,
2245    anchor_retention: Option<&AnchorRetention>,
2246    missing_checkpoints: &mut Vec<(BlockHeight, Checkpoint)>,
2247) {
2248    for (index, (_, retention)) in commitments
2249        .iter_mut()
2250        .enumerate()
2251        .filter_map(|(index, entry)| entry.as_mut().map(|entry| (index, entry)))
2252    {
2253        if let Retention::Checkpoint { id, marking } = retention
2254            && !keeps_checkpoint(checkpoint_floor, anchor_retention, *id)
2255        {
2256            let position = start_position + index as u64;
2257            let carried = missing_checkpoints
2258                .iter()
2259                .enumerate()
2260                .filter(|(_, (_, checkpoint))| checkpoint.position() == Some(position))
2261                .min_by_key(|(_, (height, _))| *height)
2262                .map(|(entry_index, _)| entry_index);
2263            *retention = match carried {
2264                Some(entry_index) => Retention::Checkpoint {
2265                    id: missing_checkpoints.remove(entry_index).0,
2266                    marking: *marking,
2267                },
2268                None => match marking {
2269                    Marking::Marked => Retention::Marked,
2270                    Marking::Reference => Retention::Reference,
2271                    Marking::None => Retention::Ephemeral,
2272                },
2273            };
2274        }
2275    }
2276}
2277
2278#[cfg(test)]
2279mod tests {
2280    #[cfg(feature = "orchard")]
2281    use {super::cross_pool_ensure_heights, std::collections::BTreeSet};
2282
2283    use core::num::NonZeroU32;
2284
2285    use proptest::prelude::*;
2286    use zcash_protocol::consensus::BlockHeight;
2287
2288    #[cfg(feature = "orchard")]
2289    use super::batch_ensure_heights;
2290    use super::{
2291        SPEND_MAP_RETENTION_BLOCKS, should_retain_anchor, should_track_spends, spend_tracking_floor,
2292    };
2293    use crate::data_api::anchor_retention::{AnchorRetention, AnchorRetentionInterval};
2294
2295    /// A range scanned after a gap of unscanned history (or below the frontier, or with no
2296    /// frontier at all) must track every nullifier: a skipped entry could belong to a note
2297    /// in the gap whose spentness would then be undetectable once the gap is scanned.
2298    #[test]
2299    fn out_of_order_ranges_track_fully() {
2300        let h = BlockHeight::from;
2301        // Frontier far below this range's start: gap ⇒ no floor.
2302        assert_eq!(
2303            spend_tracking_floor(Some(h(1_000)), h(500_000), Some(h(510_000))),
2304            None
2305        );
2306        // No frontier at all ⇒ no floor.
2307        assert_eq!(
2308            spend_tracking_floor(None, h(500_000), Some(h(510_000))),
2309            None
2310        );
2311        // Frontier above the range start (re-scan below the frontier) ⇒ no floor.
2312        assert_eq!(
2313            spend_tracking_floor(Some(h(600_000)), h(500_000), Some(h(510_000))),
2314            None
2315        );
2316    }
2317
2318    /// Extending the contiguous frontier skips inserts below the trailing retention
2319    /// window and keeps the window itself; batches no longer than the window (and empty
2320    /// batches) track fully.
2321    #[test]
2322    fn frontier_batches_retain_the_trailing_window() {
2323        let from = BlockHeight::from(500_000);
2324        let last = BlockHeight::from(510_000);
2325        let floor = spend_tracking_floor(Some(from), from, Some(last)).expect("frontier ⇒ floor");
2326        assert_eq!(
2327            u32::from(last) - u32::from(floor),
2328            SPEND_MAP_RETENTION_BLOCKS
2329        );
2330
2331        let short = BlockHeight::from(500_000 + SPEND_MAP_RETENTION_BLOCKS / 2);
2332        assert_eq!(spend_tracking_floor(Some(from), from, Some(short)), None);
2333        assert_eq!(spend_tracking_floor(Some(from), from, None), None);
2334    }
2335
2336    #[test]
2337    fn spend_tracking_floor_gating() {
2338        let floor = BlockHeight::from(1000);
2339
2340        // With no floor, every block's spends are tracked.
2341        assert!(should_track_spends(None, BlockHeight::from(0)));
2342        assert!(should_track_spends(None, BlockHeight::from(999)));
2343
2344        // At or above the floor: tracked.
2345        assert!(should_track_spends(Some(floor), BlockHeight::from(1000)));
2346        assert!(should_track_spends(Some(floor), BlockHeight::from(1001)));
2347
2348        // Strictly below the floor: skipped.
2349        assert!(!should_track_spends(Some(floor), BlockHeight::from(999)));
2350        assert!(!should_track_spends(Some(floor), BlockHeight::from(0)));
2351    }
2352
2353    /// The gating semantics hold identically at the ZIP 318 interval and at a non-default one, so
2354    /// a wallet configured with a short interval retains exactly its own grid.
2355    #[test]
2356    fn anchor_retention_gating() {
2357        for interval in [
2358            AnchorRetentionInterval::ZIP_318,
2359            AnchorRetentionInterval::custom(NonZeroU32::new(12).expect("nonzero")),
2360        ] {
2361            let blocks = interval.block_count().get();
2362            let floor = BlockHeight::from(4 * blocks);
2363            let policy = AnchorRetention::new(
2364                floor,
2365                zcash_protocol::zip318::BlockSpacing::UNIFORM,
2366                interval,
2367            );
2368            let retention = Some(&policy);
2369
2370            // With retention disabled, nothing is retained, even on the interval.
2371            assert!(!should_retain_anchor(None, BlockHeight::from(8 * blocks)));
2372
2373            // On the interval and at or above the floor: retained.
2374            assert!(should_retain_anchor(
2375                retention,
2376                BlockHeight::from(4 * blocks)
2377            ));
2378            assert!(should_retain_anchor(
2379                retention,
2380                BlockHeight::from(8 * blocks)
2381            ));
2382
2383            // On the interval but below the floor: not retained.
2384            assert!(!should_retain_anchor(
2385                retention,
2386                BlockHeight::from(3 * blocks)
2387            ));
2388
2389            // At or above the floor but not on the interval: not retained.
2390            assert!(!should_retain_anchor(
2391                retention,
2392                BlockHeight::from(4 * blocks + 1)
2393            ));
2394            assert!(!should_retain_anchor(
2395                retention,
2396                BlockHeight::from(5 * blocks - 1)
2397            ));
2398        }
2399    }
2400
2401    #[cfg(feature = "orchard")]
2402    prop_compose! {
2403        /// An arbitrary set of note-commitment-tree checkpoint block heights.
2404        fn arb_heights()(
2405            heights in proptest::collection::vec(0u32..100, 0..20),
2406        ) -> BTreeSet<BlockHeight> {
2407            heights.into_iter().map(BlockHeight::from).collect()
2408        }
2409    }
2410
2411    #[cfg(feature = "orchard")]
2412    fn union(a: &BTreeSet<BlockHeight>, b: &BTreeSet<BlockHeight>) -> BTreeSet<BlockHeight> {
2413        a.union(b).copied().collect()
2414    }
2415
2416    proptest! {
2417        /// After reconciliation every pool is checkpointed at exactly the union of all three
2418        /// pools' checkpoint heights, so the three note commitment trees end up with an identical
2419        /// set of checkpoint heights. This is the invariant that keeps cross-pool rewinds
2420        /// consistent.
2421        #[test]
2422        #[cfg(feature = "orchard")]
2423        fn ensure_heights_align_all_pools(
2424            sapling in arb_heights(),
2425            orchard in arb_heights(),
2426            ironwood in arb_heights(),
2427        ) {
2428            let [ensure_sapling, ensure_orchard, ensure_ironwood] =
2429                cross_pool_ensure_heights(&sapling, &orchard, &ironwood);
2430
2431            let total = union(&union(&sapling, &orchard), &ironwood);
2432
2433            prop_assert_eq!(union(&sapling, &ensure_sapling), total.clone());
2434            prop_assert_eq!(union(&orchard, &ensure_orchard), total.clone());
2435            prop_assert_eq!(union(&ironwood, &ensure_ironwood), total);
2436
2437            // The heights ensured for a pool are exactly the union of the other two pools'
2438            // checkpoint heights.
2439            prop_assert_eq!(ensure_sapling, union(&orchard, &ironwood));
2440            prop_assert_eq!(ensure_orchard, union(&sapling, &ironwood));
2441            prop_assert_eq!(ensure_ironwood, union(&sapling, &orchard));
2442        }
2443
2444        /// With no Ironwood checkpoints (the pre-Ironwood-activation reality), reconciliation of
2445        /// the Sapling and Orchard trees is unchanged from the prior two-pool behavior: each
2446        /// ensures the other's heights, and the empty Ironwood tree ensures the union of both.
2447        #[test]
2448        #[cfg(feature = "orchard")]
2449        fn ensure_heights_degrade_to_two_pools(
2450            sapling in arb_heights(),
2451            orchard in arb_heights(),
2452        ) {
2453            let [ensure_sapling, ensure_orchard, ensure_ironwood] =
2454                cross_pool_ensure_heights(&sapling, &orchard, &BTreeSet::new());
2455
2456            prop_assert_eq!(ensure_sapling, orchard.clone());
2457            prop_assert_eq!(ensure_orchard, sapling.clone());
2458            prop_assert_eq!(ensure_ironwood, union(&sapling, &orchard));
2459        }
2460    }
2461
2462    /// THE anchor-retention obligation: a retained boundary landing on a block with no shielded
2463    /// output in ANY pool must still be ensured in every pool.
2464    ///
2465    /// Cross-pool alignment cannot supply this one — it unions heights that some pool already
2466    /// checkpointed, and here no pool did. Retention cannot supply it either: a policy preserves a
2467    /// checkpoint, it never creates one. So the boundary is checkpointed by this step or by nothing,
2468    /// and "by nothing" is silent — the wallet keeps scanning, balances stay correct, and only a
2469    /// transaction pre-signed against that boundary ever notices, by being unprovable forever.
2470    #[cfg(feature = "orchard")]
2471    #[test]
2472    fn retained_boundary_on_a_commitment_free_block_is_ensured() {
2473        let h = BlockHeight::from;
2474        // Interval 12, so 1_200 is a boundary. Every pool's commitments sit elsewhere, which is the
2475        // ordinary case on a sparse chain: most blocks carry no shielded output at all.
2476        let retention = AnchorRetention::new(
2477            h(1_000),
2478            zcash_protocol::zip318::BlockSpacing::UNIFORM,
2479            AnchorRetentionInterval::custom(NonZeroU32::new(12).unwrap()),
2480        );
2481
2482        let (sap_cp, orch_cp, iw_cp) = (
2483            BTreeSet::from([h(1_198)]),
2484            BTreeSet::from([h(1_205)]),
2485            BTreeSet::new(),
2486        );
2487
2488        // CONTROL, so this test can never pass for the wrong reason: cross-pool alignment alone
2489        // does NOT produce 1200. Were the retention union ever dropped, the assertions below would
2490        // fail rather than silently agree with a weaker implementation.
2491        for heights in cross_pool_ensure_heights(&sap_cp, &orch_cp, &iw_cp) {
2492            assert!(
2493                !heights.contains(&h(1_200)),
2494                "cross-pool alignment must not supply the boundary; the union is what does"
2495            );
2496        }
2497
2498        let [sapling, orchard, ironwood] = batch_ensure_heights(
2499            &sap_cp,
2500            &orch_cp,
2501            &iw_cp,
2502            Some(&retention),
2503            h(1_150)..=h(1_250),
2504            &BTreeSet::new(),
2505        );
2506
2507        for (pool, heights) in [
2508            ("sapling", &sapling),
2509            ("orchard", &orchard),
2510            ("ironwood", &ironwood),
2511        ] {
2512            assert!(
2513                heights.contains(&h(1_200)),
2514                "{pool} must ensure the retained boundary 1200, got {heights:?}"
2515            );
2516        }
2517    }
2518
2519    /// The retention step is additive, never substitutive: with no policy the result is EXACTLY
2520    /// `cross_pool_ensure_heights`. This is what makes the composition safe to adopt at every call
2521    /// site — a consumer that does not pre-sign against boundaries sees byte-identical behaviour.
2522    #[cfg(feature = "orchard")]
2523    #[test]
2524    fn no_retention_policy_is_exactly_cross_pool() {
2525        let h = BlockHeight::from;
2526        let sapling = BTreeSet::from([h(100), h(140)]);
2527        let orchard = BTreeSet::from([h(120)]);
2528        let ironwood = BTreeSet::from([h(160)]);
2529
2530        assert_eq!(
2531            batch_ensure_heights(
2532                &sapling,
2533                &orchard,
2534                &ironwood,
2535                None,
2536                h(1)..=h(1_000),
2537                &BTreeSet::new()
2538            ),
2539            cross_pool_ensure_heights(&sapling, &orchard, &ironwood)
2540        );
2541    }
2542}