Skip to main content

zebra_state/service/check/
anchors.rs

1//! Checks for whether cited anchors are previously-computed note commitment
2//! tree roots.
3
4use std::{collections::HashMap, sync::Arc};
5
6use rayon::prelude::*;
7
8use zebra_chain::{
9    block::{Block, Height},
10    sprout,
11    transaction::{Hash as TransactionHash, Transaction, UnminedTx},
12};
13
14use crate::{
15    service::{finalized_state::ZebraDb, non_finalized_state::Chain},
16    SemanticallyVerifiedBlock, ValidateContextError,
17};
18
19/// Checks the final Sapling and Orchard anchors specified by `transaction`
20///
21/// This method checks for anchors computed from the final treestate of each block in
22/// the `parent_chain` or `finalized_state`.
23#[tracing::instrument(level = "trace", skip(finalized_state, parent_chain, transaction))]
24fn sapling_orchard_anchors_refer_to_final_treestates(
25    finalized_state: &ZebraDb,
26    parent_chain: Option<&Arc<Chain>>,
27    transaction: &Arc<Transaction>,
28    transaction_hash: TransactionHash,
29    tx_index_in_block: Option<usize>,
30    height: Option<Height>,
31) -> Result<(), ValidateContextError> {
32    // Sapling Spends
33    //
34    // MUST refer to some earlier block’s final Sapling treestate.
35    //
36    // # Consensus
37    //
38    // > The anchor of each Spend description MUST refer to some earlier
39    // > block’s final Sapling treestate. The anchor is encoded separately
40    // > in each Spend description for v4 transactions, or encoded once and
41    // > shared between all Spend descriptions in a v5 transaction.
42    //
43    // <https://zips.z.cash/protocol/protocol.pdf#spendsandoutputs>
44    //
45    // This rule is also implemented in
46    // [`zebra_chain::sapling::shielded_data`].
47    //
48    // The "earlier treestate" check is implemented here.
49    for (anchor_index_in_tx, anchor) in transaction.sapling_anchors().into_iter().enumerate() {
50        tracing::debug!(
51            ?anchor,
52            ?anchor_index_in_tx,
53            ?tx_index_in_block,
54            ?height,
55            "observed sapling anchor",
56        );
57
58        if !parent_chain
59            .map(|chain| chain.sapling_anchors.contains(&anchor))
60            .unwrap_or(false)
61            && !finalized_state.contains_sapling_anchor(&anchor)
62        {
63            return Err(ValidateContextError::UnknownSaplingAnchor {
64                anchor,
65                height,
66                tx_index_in_block,
67                transaction_hash,
68            });
69        }
70
71        tracing::debug!(
72            ?anchor,
73            ?anchor_index_in_tx,
74            ?tx_index_in_block,
75            ?height,
76            "validated sapling anchor",
77        );
78    }
79
80    // Orchard Actions
81    //
82    // MUST refer to some earlier block’s final Orchard treestate.
83    //
84    // # Consensus
85    //
86    // > The anchorOrchard field of the transaction, whenever it exists
87    // > (i.e. when there are any Action descriptions), MUST refer to some
88    // > earlier block’s final Orchard treestate.
89    //
90    // <https://zips.z.cash/protocol/protocol.pdf#actions>
91    if let Some(anchor) = transaction.orchard_anchor() {
92        tracing::debug!(
93            ?anchor,
94            ?tx_index_in_block,
95            ?height,
96            "observed orchard anchor",
97        );
98
99        if !parent_chain
100            .map(|chain| chain.orchard_anchors.contains(&anchor))
101            .unwrap_or(false)
102            && !finalized_state.contains_orchard_anchor(&anchor)
103        {
104            return Err(ValidateContextError::UnknownOrchardAnchor {
105                anchor,
106                height,
107                tx_index_in_block,
108                transaction_hash,
109            });
110        }
111
112        tracing::debug!(
113            ?anchor,
114            ?tx_index_in_block,
115            ?height,
116            "validated orchard anchor",
117        );
118    }
119
120    // Ironwood Actions
121    //
122    // MUST refer to some earlier block’s final Ironwood treestate.
123    //
124    // # Consensus
125    //
126    // > The anchorIronwood field of the transaction, whenever it exists
127    // > (i.e. when there are any Ironwood Action descriptions), MUST refer to some
128    // > earlier block’s final Ironwood treestate.
129    //
130    // <https://zips.z.cash/protocol/protocol.pdf#actions>
131    //
132    // Ironwood reuses the Orchard tree root type, in a separate anchor set.
133    if let Some(anchor) = transaction.ironwood_anchor() {
134        tracing::debug!(
135            ?anchor,
136            ?tx_index_in_block,
137            ?height,
138            "observed ironwood anchor",
139        );
140
141        if !parent_chain
142            .map(|chain| chain.ironwood_anchors.contains(&anchor))
143            .unwrap_or(false)
144            && !finalized_state.contains_ironwood_anchor(&anchor)
145        {
146            return Err(ValidateContextError::UnknownIronwoodAnchor {
147                anchor,
148                height,
149                tx_index_in_block,
150                transaction_hash,
151            });
152        }
153
154        tracing::debug!(
155            ?anchor,
156            ?tx_index_in_block,
157            ?height,
158            "validated ironwood anchor",
159        );
160    }
161
162    Ok(())
163}
164
165/// This function fetches and returns the Sprout final treestates from the state,
166/// so [`sprout_anchors_refer_to_treestates()`] can check Sprout final and interstitial treestates,
167/// without accessing the disk.
168///
169/// Sprout anchors may also refer to the interstitial output treestate of any prior
170/// `JoinSplit` _within the same transaction_; these are created on the fly
171/// in [`sprout_anchors_refer_to_treestates()`].
172#[tracing::instrument(
173    level = "trace",
174    skip(sprout_final_treestates, finalized_state, parent_chain, transaction)
175)]
176fn fetch_sprout_final_treestates(
177    sprout_final_treestates: &mut HashMap<
178        sprout::tree::Root,
179        Arc<sprout::tree::NoteCommitmentTree>,
180    >,
181    finalized_state: &ZebraDb,
182    parent_chain: Option<&Arc<Chain>>,
183    transaction: &Arc<Transaction>,
184    tx_index_in_block: Option<usize>,
185    height: Option<Height>,
186) {
187    // Fetch and return Sprout JoinSplit final treestates
188    for (joinsplit_index_in_tx, js) in transaction.sprout_joinsplit_descriptions().enumerate() {
189        let anchor = sprout::tree::Root::from(js.anchor());
190
191        // Avoid duplicate fetches
192        if sprout_final_treestates.contains_key(&anchor) {
193            continue;
194        }
195
196        let input_tree = parent_chain
197            .and_then(|chain| chain.sprout_trees_by_anchor.get(&anchor).cloned())
198            .or_else(|| finalized_state.sprout_tree_by_anchor(&anchor));
199
200        if let Some(input_tree) = input_tree {
201            sprout_final_treestates.insert(anchor, input_tree);
202
203            tracing::debug!(
204                sprout_final_treestate_count = ?sprout_final_treestates.len(),
205                ?anchor,
206                ?joinsplit_index_in_tx,
207                ?tx_index_in_block,
208                ?height,
209                "observed sprout final treestate anchor",
210            );
211        }
212    }
213
214    tracing::trace!(
215        sprout_final_treestate_count = ?sprout_final_treestates.len(),
216        ?sprout_final_treestates,
217        ?height,
218        "returning sprout final treestate anchors",
219    );
220}
221
222/// Checks the Sprout anchors specified by `transactions`.
223///
224/// Sprout anchors may refer to some earlier block's final treestate (like
225/// Sapling and Orchard do exclusively) _or_ to the interstitial output
226/// treestate of any prior `JoinSplit` _within the same transaction_.
227///
228/// This method searches for anchors in the supplied `sprout_final_treestates`
229/// (which must be populated with all treestates pointed to in the `semantically_verified` block;
230/// see [`fetch_sprout_final_treestates()`]); or in the interstitial
231/// treestates which are computed on the fly in this function.
232#[tracing::instrument(level = "trace", skip(sprout_final_treestates, transaction))]
233fn sprout_anchors_refer_to_treestates(
234    sprout_final_treestates: &HashMap<sprout::tree::Root, Arc<sprout::tree::NoteCommitmentTree>>,
235    transaction: &Arc<Transaction>,
236    transaction_hash: TransactionHash,
237    tx_index_in_block: Option<usize>,
238    height: Option<Height>,
239) -> Result<(), ValidateContextError> {
240    // Sprout JoinSplits, with interstitial treestates to check as well.
241    let mut interstitial_trees: HashMap<sprout::tree::Root, Arc<sprout::tree::NoteCommitmentTree>> =
242        HashMap::new();
243
244    let js_descriptions: Vec<_> = transaction.sprout_joinsplit_descriptions().collect();
245    let joinsplit_count = js_descriptions.len();
246
247    for (joinsplit_index_in_tx, js) in js_descriptions.iter().enumerate() {
248        let anchor = sprout::tree::Root::from(js.anchor());
249        // Check all anchor sets, including the one for interstitial
250        // anchors.
251        //
252        // The anchor is checked and the matching tree is obtained,
253        // which is used to create the interstitial tree state for this
254        // JoinSplit:
255        //
256        // > For each JoinSplit description in a transaction, an
257        // > interstitial output treestate is constructed which adds the
258        // > note commitments and nullifiers specified in that JoinSplit
259        // > description to the input treestate referred to by its
260        // > anchor. This interstitial output treestate is available for
261        // > use as the anchor of subsequent JoinSplit descriptions in
262        // > the same transaction.
263        //
264        // <https://zips.z.cash/protocol/protocol.pdf#joinsplit>
265        //
266        // # Consensus
267        //
268        // > The anchor of each JoinSplit description in a transaction
269        // > MUST refer to either some earlier block’s final Sprout
270        // > treestate, or to the interstitial output treestate of any
271        // > prior JoinSplit description in the same transaction.
272        //
273        // > For the first JoinSplit description of a transaction, the
274        // > anchor MUST be the output Sprout treestate of a previous
275        // > block.
276        //
277        // <https://zips.z.cash/protocol/protocol.pdf#joinsplit>
278        //
279        // Note that in order to satisfy the latter consensus rule above,
280        // [`interstitial_trees`] is always empty in the first iteration
281        // of the loop.
282        let input_tree = interstitial_trees
283            .get(&anchor)
284            .cloned()
285            .or_else(|| sprout_final_treestates.get(&anchor).cloned());
286
287        tracing::trace!(
288            ?input_tree,
289            final_lookup = ?sprout_final_treestates.get(&anchor),
290            interstitial_lookup = ?interstitial_trees.get(&anchor),
291            interstitial_tree_count = ?interstitial_trees.len(),
292            ?interstitial_trees,
293            ?height,
294            "looked up sprout treestate anchor",
295        );
296
297        let mut input_tree = match input_tree {
298            Some(tree) => tree,
299            None => {
300                tracing::debug!(
301                    ?anchor,
302                    ?joinsplit_index_in_tx,
303                    ?tx_index_in_block,
304                    ?height,
305                    "failed to find sprout anchor",
306                );
307                return Err(ValidateContextError::UnknownSproutAnchor {
308                    anchor,
309                    height,
310                    tx_index_in_block,
311                    transaction_hash,
312                });
313            }
314        };
315
316        tracing::debug!(
317            ?anchor,
318            ?joinsplit_index_in_tx,
319            ?tx_index_in_block,
320            ?height,
321            "validated sprout anchor",
322        );
323
324        // The last interstitial treestate in a transaction can never be used,
325        // so we avoid generating it.
326        if joinsplit_index_in_tx == joinsplit_count - 1 {
327            continue;
328        }
329
330        let input_tree_inner = Arc::make_mut(&mut input_tree);
331
332        // Add new anchors to the interstitial note commitment tree.
333        for cm_bytes in js.commitments() {
334            let cm = sprout::commitment::NoteCommitment::from(*cm_bytes);
335            input_tree_inner.append(cm)?;
336        }
337
338        interstitial_trees.insert(input_tree.root(), input_tree);
339
340        tracing::debug!(
341            ?anchor,
342            ?joinsplit_index_in_tx,
343            ?tx_index_in_block,
344            ?height,
345            "observed sprout interstitial anchor",
346        );
347    }
348
349    Ok(())
350}
351
352/// Accepts a [`ZebraDb`], [`Chain`], and [`SemanticallyVerifiedBlock`].
353///
354/// Iterates over the transactions in the [`SemanticallyVerifiedBlock`] checking the final Sapling and Orchard anchors.
355///
356/// This method checks for anchors computed from the final treestate of each block in
357/// the `parent_chain` or `finalized_state`.
358#[tracing::instrument(skip_all)]
359pub(crate) fn block_sapling_orchard_anchors_refer_to_final_treestates(
360    finalized_state: &ZebraDb,
361    parent_chain: &Arc<Chain>,
362    semantically_verified: &SemanticallyVerifiedBlock,
363) -> Result<(), ValidateContextError> {
364    semantically_verified
365        .block
366        .transactions
367        .iter()
368        .enumerate()
369        .try_for_each(|(tx_index_in_block, transaction)| {
370            sapling_orchard_anchors_refer_to_final_treestates(
371                finalized_state,
372                Some(parent_chain),
373                transaction,
374                semantically_verified.transaction_hashes[tx_index_in_block],
375                Some(tx_index_in_block),
376                Some(semantically_verified.height),
377            )
378        })
379}
380
381/// Accepts a [`ZebraDb`], [`Arc<Chain>`](Chain), and [`SemanticallyVerifiedBlock`].
382///
383/// Iterates over the transactions in the [`SemanticallyVerifiedBlock`], and fetches the Sprout final treestates
384/// from the state.
385///
386/// Returns a `HashMap` of the Sprout final treestates from the state for [`sprout_anchors_refer_to_treestates()`]
387/// to check Sprout final and interstitial treestates without accessing the disk.
388///
389/// Sprout anchors may also refer to the interstitial output treestate of any prior
390/// `JoinSplit` _within the same transaction_; these are created on the fly
391/// in [`sprout_anchors_refer_to_treestates()`].
392#[tracing::instrument(skip_all)]
393pub(crate) fn block_fetch_sprout_final_treestates(
394    finalized_state: &ZebraDb,
395    parent_chain: &Arc<Chain>,
396    semantically_verified: &SemanticallyVerifiedBlock,
397) -> HashMap<sprout::tree::Root, Arc<sprout::tree::NoteCommitmentTree>> {
398    let mut sprout_final_treestates = HashMap::new();
399
400    for (tx_index_in_block, transaction) in
401        semantically_verified.block.transactions.iter().enumerate()
402    {
403        fetch_sprout_final_treestates(
404            &mut sprout_final_treestates,
405            finalized_state,
406            Some(parent_chain),
407            transaction,
408            Some(tx_index_in_block),
409            Some(semantically_verified.height),
410        );
411    }
412
413    sprout_final_treestates
414}
415
416/// Accepts a [`ZebraDb`], [`Arc<Chain>`](Chain), [`Arc<Block>`](Block), and an
417/// [`Arc<[transaction::Hash]>`](TransactionHash) of hashes corresponding to the transactions in [`Block`]
418///
419/// Iterates over the transactions in the [`Block`] checking the final Sprout anchors.
420///
421/// Sprout anchors may refer to some earlier block's final treestate (like
422/// Sapling and Orchard do exclusively) _or_ to the interstitial output
423/// treestate of any prior `JoinSplit` _within the same transaction_.
424///
425/// This method searches for anchors in the supplied `sprout_final_treestates`
426/// (which must be populated with all treestates pointed to in the `semantically_verified` block;
427/// see [`fetch_sprout_final_treestates()`]); or in the interstitial
428/// treestates which are computed on the fly in this function.
429#[tracing::instrument(skip(sprout_final_treestates, block, transaction_hashes))]
430pub(crate) fn block_sprout_anchors_refer_to_treestates(
431    sprout_final_treestates: HashMap<sprout::tree::Root, Arc<sprout::tree::NoteCommitmentTree>>,
432    block: Arc<Block>,
433    // Only used for debugging
434    transaction_hashes: Arc<[TransactionHash]>,
435    height: Height,
436) -> Result<(), ValidateContextError> {
437    tracing::trace!(
438        sprout_final_treestate_count = ?sprout_final_treestates.len(),
439        ?sprout_final_treestates,
440        ?height,
441        "received sprout final treestate anchors",
442    );
443
444    let check_tx_sprout_anchors = |(tx_index_in_block, transaction)| {
445        sprout_anchors_refer_to_treestates(
446            &sprout_final_treestates,
447            transaction,
448            transaction_hashes[tx_index_in_block],
449            Some(tx_index_in_block),
450            Some(height),
451        )?;
452
453        Ok(())
454    };
455
456    // The overhead for a parallel iterator is unwarranted if sprout_final_treestates is empty
457    // because it will either return an error for the first transaction or only check that `joinsplit_data`
458    // is `None` for each transaction.
459    if sprout_final_treestates.is_empty() {
460        // The block has no valid sprout anchors
461        block
462            .transactions
463            .iter()
464            .enumerate()
465            .try_for_each(check_tx_sprout_anchors)
466    } else {
467        block
468            .transactions
469            .par_iter()
470            .enumerate()
471            .try_for_each(check_tx_sprout_anchors)
472    }
473}
474
475/// Accepts a [`ZebraDb`], an optional [`Option<Arc<Chain>>`](Chain), and an [`UnminedTx`].
476///
477/// Checks the final Sprout, Sapling and Orchard anchors specified in the [`UnminedTx`].
478///
479/// This method checks for anchors computed from the final treestate of each block in
480/// the `parent_chain` or `finalized_state`.
481#[tracing::instrument(level = "trace", skip_all)]
482pub(crate) fn tx_anchors_refer_to_final_treestates(
483    finalized_state: &ZebraDb,
484    parent_chain: Option<&Arc<Chain>>,
485    unmined_tx: &UnminedTx,
486) -> Result<(), ValidateContextError> {
487    sapling_orchard_anchors_refer_to_final_treestates(
488        finalized_state,
489        parent_chain,
490        &unmined_tx.transaction,
491        unmined_tx.id.mined_id(),
492        None,
493        None,
494    )?;
495
496    // If there are no sprout transactions in the block, avoid running a rayon scope
497    if unmined_tx.transaction.has_sprout_joinsplit_data() {
498        let mut sprout_final_treestates = HashMap::new();
499
500        fetch_sprout_final_treestates(
501            &mut sprout_final_treestates,
502            finalized_state,
503            parent_chain,
504            &unmined_tx.transaction,
505            None,
506            None,
507        );
508
509        let mut sprout_anchors_result = None;
510        rayon::in_place_scope_fifo(|s| {
511            // This check is expensive, because it updates a note commitment tree for each sprout JoinSplit.
512            // Since we could be processing attacker-controlled mempool transactions, we need to run each one
513            // in its own thread, separately from tokio's blocking I/O threads. And if we are under heavy load,
514            // we want verification to finish in order, so that later transactions can't delay earlier ones.
515            s.spawn_fifo(|_s| {
516                tracing::trace!(
517                    sprout_final_treestate_count = ?sprout_final_treestates.len(),
518                    ?sprout_final_treestates,
519                    "received sprout final treestate anchors",
520                );
521
522                sprout_anchors_result = Some(sprout_anchors_refer_to_treestates(
523                    &sprout_final_treestates,
524                    &unmined_tx.transaction,
525                    unmined_tx.id.mined_id(),
526                    None,
527                    None,
528                ));
529            });
530        });
531
532        sprout_anchors_result.expect("scope has finished")?;
533    }
534
535    Ok(())
536}