Skip to main content

zebra_state/service/read/
block.rs

1//! Shared block, header, and transaction reading code.
2//!
3//! In the functions in this module:
4//!
5//! The block write task commits blocks to the finalized state before updating
6//! `chain` or `non_finalized_state` with a cached copy of the non-finalized chains
7//! in `NonFinalizedState.chain_set`. Then the block commit task can
8//! commit additional blocks to the finalized state after we've cloned the
9//! `chain` or `non_finalized_state`.
10//!
11//! This means that some blocks can be in both:
12//! - the cached [`Chain`] or [`NonFinalizedState`], and
13//! - the shared finalized [`ZebraDb`] reference.
14
15use std::{collections::HashMap, sync::Arc};
16
17use chrono::{DateTime, Utc};
18
19use zebra_chain::{
20    block::{self, Block, Height},
21    block_info::BlockInfo,
22    serialization::ZcashSerialize as _,
23    transaction::{self, Transaction},
24    transparent::{self, Utxo},
25};
26
27use crate::{
28    response::{AnyTx, MinedTx},
29    service::{
30        finalized_state::ZebraDb,
31        non_finalized_state::{Chain, NonFinalizedState},
32        read::tip,
33    },
34    BlockReadError, HashOrHeight,
35};
36
37#[cfg(feature = "indexer")]
38use crate::request::Spend;
39
40/// Returns the [`Block`] with [`block::Hash`] or
41/// [`Height`], if it exists in the non-finalized `chains` or finalized `db`.
42///
43/// Returns an error if primary data is incomplete. An incomplete secondary view returns `None`.
44pub fn any_block<'a, C: AsRef<Chain> + 'a>(
45    mut chains: impl Iterator<Item = &'a C>,
46    db: &ZebraDb,
47    hash_or_height: HashOrHeight,
48) -> Result<Option<Arc<Block>>, BlockReadError> {
49    // # Correctness
50    //
51    // Since blocks are the same in the finalized and non-finalized state, we
52    // check the most efficient alternative first. (`chain` is always in memory,
53    // but `db` stores blocks on disk, with a memory cache.)
54    chains
55        .find_map(|c| c.as_ref().block(hash_or_height))
56        .map(|contextual| contextual.block.clone())
57        .map_or_else(|| db.block(hash_or_height), |block| Ok(Some(block)))
58}
59
60/// Returns the [`Block`] with [`block::Hash`] or
61/// [`Height`], if it exists in the non-finalized `chain` or finalized `db`.
62///
63/// Returns an error if primary data is incomplete. An incomplete secondary view returns `None`.
64pub fn block<C>(
65    chain: Option<C>,
66    db: &ZebraDb,
67    hash_or_height: HashOrHeight,
68) -> Result<Option<Arc<Block>>, BlockReadError>
69where
70    C: AsRef<Chain>,
71{
72    any_block(chain.iter(), db, hash_or_height)
73}
74
75/// Returns the [`Block`] with [`block::Hash`] or
76/// [`Height`], if it exists in the non-finalized `chain` or finalized `db`.
77///
78/// Returns an error if primary data is incomplete. An incomplete secondary view returns `None`.
79pub fn block_and_size<C>(
80    chain: Option<C>,
81    db: &ZebraDb,
82    hash_or_height: HashOrHeight,
83) -> Result<Option<(Arc<Block>, usize)>, BlockReadError>
84where
85    C: AsRef<Chain>,
86{
87    // # Correctness
88    //
89    // Since blocks are the same in the finalized and non-finalized state, we
90    // check the most efficient alternative first. (`chain` is always in memory,
91    // but `db` stores blocks on disk, with a memory cache.)
92    chain
93        .as_ref()
94        .and_then(|chain| chain.as_ref().block(hash_or_height))
95        .map(|contextual| {
96            let size = contextual.block.zcash_serialize_to_vec().unwrap().len();
97            (contextual.block.clone(), size)
98        })
99        .map_or_else(
100            || db.block_and_size(hash_or_height),
101            |block| Ok(Some(block)),
102        )
103}
104
105/// Returns the [`block::Header`] with [`block::Hash`] or
106/// [`Height`], if it exists in the non-finalized `chain` or finalized `db`.
107pub fn block_header<C>(
108    chain: Option<C>,
109    db: &ZebraDb,
110    hash_or_height: HashOrHeight,
111) -> Option<Arc<block::Header>>
112where
113    C: AsRef<Chain>,
114{
115    // # Correctness
116    //
117    // Since blocks are the same in the finalized and non-finalized state, we
118    // check the most efficient alternative first. (`chain` is always in memory,
119    // but `db` stores blocks on disk, with a memory cache.)
120    chain
121        .as_ref()
122        .and_then(|chain| chain.as_ref().block(hash_or_height))
123        .map(|contextual| contextual.block.header.clone())
124        .or_else(|| db.block_header(hash_or_height))
125}
126
127/// Returns the [`Transaction`] with [`transaction::Hash`], if it exists in the
128/// non-finalized `chain` or finalized `db`.
129fn transaction<C>(
130    chain: Option<C>,
131    db: &ZebraDb,
132    hash: transaction::Hash,
133) -> Option<(Arc<Transaction>, Height, DateTime<Utc>)>
134where
135    C: AsRef<Chain>,
136{
137    // # Correctness
138    //
139    // Since transactions are the same in the finalized and non-finalized state,
140    // we check the most efficient alternative first. (`chain` is always in
141    // memory, but `db` stores transactions on disk, with a memory cache.)
142    chain
143        .and_then(|chain| {
144            chain
145                .as_ref()
146                .transaction(hash)
147                .map(|(tx, height, time)| (tx.clone(), height, time))
148        })
149        .or_else(|| db.transaction(hash))
150}
151
152/// Returns a [`MinedTx`] for a [`Transaction`] with [`transaction::Hash`],
153/// if one exists in the non-finalized `chain` or finalized `db`.
154pub fn mined_transaction<C>(
155    chain: Option<C>,
156    db: &ZebraDb,
157    hash: transaction::Hash,
158) -> Option<MinedTx>
159where
160    C: AsRef<Chain>,
161{
162    // # Correctness
163    //
164    // It is ok to do this lookup in two different calls. Finalized state updates
165    // can only add overlapping blocks, and hashes are unique.
166    let chain = chain.as_ref();
167
168    let (tx, height, time) = transaction(chain, db, hash)?;
169    let (tip_height, tip_hash) = tip(chain, db)?;
170    let confirmations = 1 + tip_height.0 - height.0;
171
172    Some(MinedTx::new(tx, height, confirmations, time, tip_hash))
173}
174
175/// Returns the transparent outputs spent by the non-coinbase inputs of the block with
176/// `hash_or_height`, keyed by the [`OutPoint`](transparent::OutPoint) that spends them, if the
177/// block exists in the non-finalized `chain` or finalized `db`.
178///
179/// Used by the `getblock` RPC at verbosity 3 to fill in each input's prevout and the
180/// transaction fee.
181///
182/// Returns an error if primary data is incomplete. An incomplete secondary view returns `None`.
183///
184/// # Correctness
185///
186/// The block and all of its spent outputs are read from the same `chain`/`db` snapshot, so the
187/// prevouts are consistent with the block.
188///
189/// A spent output that cannot be found (for example, an input of a side-chain block that spends
190/// an output not in the best chain) is omitted from the map. Callers must treat a missing
191/// outpoint as "prevout unknown", not as an error.
192///
193/// Coinbase transactions spend no outputs, so they contribute nothing to the map.
194///
195/// # Performance
196///
197/// Spent outputs are deleted from the finalized UTXO set, so an output already spent in the
198/// finalized chain is recovered by reading its whole parent transaction. Each distinct parent
199/// transaction is read at most once, so this is `O(distinct spent parent transactions)` reads —
200/// the same cost as resolving the prevouts individually, but in a single state request under one
201/// snapshot.
202///
203/// UTXO lookups only help for a non-finalized block: its spent outputs are still in the
204/// non-finalized chain's created UTXOs or the finalized UTXO set. A finalized block skips them
205/// and reads the parent transactions directly.
206pub fn spent_outputs_for_block<C>(
207    chain: Option<C>,
208    db: &ZebraDb,
209    hash_or_height: HashOrHeight,
210) -> Result<Option<HashMap<transparent::OutPoint, Utxo>>, BlockReadError>
211where
212    C: AsRef<Chain>,
213{
214    let chain = chain.as_ref();
215    let Some(block) = block(chain, db, hash_or_height)? else {
216        return Ok(None);
217    };
218
219    // The finalized tip can only advance between these reads, which can only turn a UTXO hit
220    // into a parent read, never the reverse.
221    let is_finalized = match (block.coinbase_height(), db.finalized_tip_height()) {
222        (Some(height), Some(finalized_tip)) => height <= finalized_tip,
223        _ => false,
224    };
225
226    let mut spent_outputs = HashMap::new();
227
228    // Outpoints missing from the UTXO set, grouped by parent so each parent is read once,
229    // used, and dropped before the next one is read.
230    let mut by_parent: HashMap<transaction::Hash, Vec<transparent::OutPoint>> = HashMap::new();
231
232    for tx in block.transactions.iter().filter(|tx| !tx.is_coinbase()) {
233        for outpoint in tx.spent_outpoints() {
234            let unspent = if is_finalized {
235                None
236            } else {
237                utxo(chain, db, outpoint)
238            };
239            if let Some(utxo) = unspent {
240                spent_outputs.insert(outpoint, utxo);
241            } else {
242                by_parent.entry(outpoint.hash).or_default().push(outpoint);
243            }
244        }
245    }
246
247    for (parent_hash, outpoints) in by_parent {
248        let Some((parent_tx, height, _)) = transaction(chain, db, parent_hash) else {
249            continue;
250        };
251        let from_coinbase = parent_tx.is_coinbase();
252        let outputs = parent_tx.outputs();
253        for outpoint in outpoints {
254            if let Some(output) = outputs.get(outpoint.index as usize) {
255                spent_outputs.insert(outpoint, Utxo::new(output.clone(), height, from_coinbase));
256            }
257        }
258    }
259
260    Ok(Some(spent_outputs))
261}
262
263/// Returns a [`AnyTx`] for a [`Transaction`] with [`transaction::Hash`],
264/// if one exists in any chain in `chains` or finalized `db`.
265/// The first chain in `chains` must be the best chain.
266pub fn any_transaction<'a>(
267    chains: impl Iterator<Item = &'a Arc<Chain>>,
268    db: &ZebraDb,
269    hash: transaction::Hash,
270) -> Option<AnyTx> {
271    // # Correctness
272    //
273    // It is ok to do this lookup in multiple different calls. Finalized state updates
274    // can only add overlapping blocks, and hashes are unique.
275    //
276    // Capture the best chain tip before searching, not inside the search closure.
277    // The closure only runs when the tx is found in a non-finalized chain; if the tx
278    // is only in the finalized DB, the closure never fires and best_chain would stay
279    // None, causing tip_height to undercount confirmations by ~MAX_BLOCK_REORG_HEIGHT.
280    // See <https://github.com/ZcashFoundation/zebra/issues/10470>.
281    // peekable() reads the first element without consuming it, so the iterator can
282    // still be used in find_map below.
283    let mut chains = chains.peekable();
284    let best_chain = chains.peek().copied();
285    let (tx, height, time, in_best_chain, containing_chain) = chains
286        .enumerate()
287        .find_map(|(i, chain)| {
288            chain
289                .as_ref()
290                .transaction(hash)
291                .map(|(tx, height, time)| (tx.clone(), height, time, i == 0, Some(chain)))
292        })
293        .or_else(|| {
294            db.transaction(hash)
295                .map(|(tx, height, time)| (tx.clone(), height, time, true, None))
296        })?;
297
298    if in_best_chain {
299        let (tip_height, tip_hash) = tip(best_chain, db)?;
300        let confirmations = 1 + tip_height.0 - height.0;
301        Some(AnyTx::Mined(MinedTx::new(
302            tx,
303            height,
304            confirmations,
305            time,
306            tip_hash,
307        )))
308    } else {
309        let block_hash = containing_chain?.block(height.into())?.hash;
310        Some(AnyTx::Side((tx, block_hash)))
311    }
312}
313
314/// Returns the [`transaction::Hash`]es for the block with `hash_or_height`,
315/// if it exists in the non-finalized `chain` or finalized `db`.
316///
317/// The returned hashes are in block order.
318///
319/// Returns `None` if the block is not found.
320pub fn transaction_hashes_for_block<C>(
321    chain: Option<C>,
322    db: &ZebraDb,
323    hash_or_height: HashOrHeight,
324) -> Option<Arc<[transaction::Hash]>>
325where
326    C: AsRef<Chain>,
327{
328    // # Correctness
329    //
330    // Since blocks are the same in the finalized and non-finalized state, we
331    // check the most efficient alternative first. (`chain` is always in memory,
332    // but `db` stores blocks on disk, with a memory cache.)
333    chain
334        .as_ref()
335        .and_then(|chain| chain.as_ref().transaction_hashes_for_block(hash_or_height))
336        .or_else(|| db.transaction_hashes_for_block(hash_or_height))
337}
338
339/// Returns the [`transaction::Hash`]es for the block with `hash_or_height`,
340/// if it exists in any chain in `chains` or finalized `db`.
341/// The first chain in `chains` must be the best chain.
342///
343/// The returned hashes are in block order.
344///
345/// Returns `None` if the block is not found.
346pub fn transaction_hashes_for_any_block<'a>(
347    chains: impl Iterator<Item = &'a Arc<Chain>>,
348    db: &ZebraDb,
349    hash_or_height: HashOrHeight,
350) -> Option<(Arc<[transaction::Hash]>, bool)> {
351    // # Correctness
352    //
353    // Since blocks are the same in the finalized and non-finalized state, we
354    // check the most efficient alternative first. (`chain` is always in memory,
355    // but `db` stores blocks on disk, with a memory cache.)
356    chains
357        .enumerate()
358        .find_map(|(i, chain)| {
359            chain
360                .as_ref()
361                .transaction_hashes_for_block(hash_or_height)
362                .map(|hashes| (hashes.clone(), i == 0))
363        })
364        .or_else(|| {
365            db.transaction_hashes_for_block(hash_or_height)
366                .map(|hashes| (hashes, true))
367        })
368}
369
370/// Returns the [`Utxo`] for [`transparent::OutPoint`], if it exists in the
371/// non-finalized `chain` or finalized `db`.
372///
373/// Non-finalized UTXOs are returned regardless of whether they have been spent.
374///
375/// Finalized UTXOs are only returned if they are unspent in the finalized chain.
376/// They may have been spent in the non-finalized chain,
377/// but this function returns them without checking for non-finalized spends,
378/// because we don't know which non-finalized chain will be committed to the finalized state.
379pub fn utxo<C>(chain: Option<C>, db: &ZebraDb, outpoint: transparent::OutPoint) -> Option<Utxo>
380where
381    C: AsRef<Chain>,
382{
383    // # Correctness
384    //
385    // Since UTXOs are the same in the finalized and non-finalized state,
386    // we check the most efficient alternative first. (`chain` is always in
387    // memory, but `db` stores transactions on disk, with a memory cache.)
388    chain
389        .and_then(|chain| chain.as_ref().created_utxo(&outpoint))
390        .or_else(|| db.utxo(&outpoint).map(|utxo| utxo.utxo))
391}
392
393/// Returns the [`Utxo`] for [`transparent::OutPoint`], if it exists and is unspent in the
394/// non-finalized `chain` or finalized `db`.
395pub fn unspent_utxo<C>(
396    chain: Option<C>,
397    db: &ZebraDb,
398    outpoint: transparent::OutPoint,
399) -> Option<Utxo>
400where
401    C: AsRef<Chain>,
402{
403    match chain {
404        Some(chain) if chain.as_ref().spent_utxos.contains_key(&outpoint) => None,
405        chain => utxo(chain, db, outpoint),
406    }
407}
408
409/// Returns the [`Hash`](transaction::Hash) of the transaction that spent an output at
410/// the provided [`transparent::OutPoint`] or revealed the provided nullifier, if it exists
411/// and is spent or revealed in the non-finalized `chain` or finalized `db` and its
412/// spending transaction hash has been indexed.
413#[cfg(feature = "indexer")]
414pub fn spending_transaction_hash<C>(
415    chain: Option<C>,
416    db: &ZebraDb,
417    spend: Spend,
418) -> Option<transaction::Hash>
419where
420    C: AsRef<Chain>,
421{
422    chain
423        .and_then(|chain| chain.as_ref().spending_transaction_hash(&spend))
424        .or_else(|| db.spending_transaction_hash(&spend))
425}
426
427/// Returns the [`Utxo`] for [`transparent::OutPoint`], if it exists in any chain
428/// in the `non_finalized_state`, or in the finalized `db`.
429///
430/// Non-finalized UTXOs are returned regardless of whether they have been spent.
431///
432/// Finalized UTXOs are only returned if they are unspent in the finalized chain.
433/// They may have been spent in one or more non-finalized chains,
434/// but this function returns them without checking for non-finalized spends,
435/// because we don't know which non-finalized chain the request belongs to.
436///
437/// UTXO spends are checked once the block reaches the non-finalized state,
438/// by [`check::utxo::transparent_spend()`](crate::service::check::utxo::transparent_spend).
439pub fn any_utxo(
440    non_finalized_state: NonFinalizedState,
441    db: &ZebraDb,
442    outpoint: transparent::OutPoint,
443) -> Option<Utxo> {
444    // # Correctness
445    //
446    // Since UTXOs are the same in the finalized and non-finalized state,
447    // we check the most efficient alternative first. (`non_finalized_state` is always in
448    // memory, but `db` stores transactions on disk, with a memory cache.)
449    non_finalized_state
450        .any_utxo(&outpoint)
451        .or_else(|| db.utxo(&outpoint).map(|utxo| utxo.utxo))
452}
453
454/// Returns the [`BlockInfo`] with [`block::Hash`] or
455/// [`Height`], if it exists in the non-finalized `chain` or finalized `db`.
456pub fn block_info<C>(
457    chain: Option<C>,
458    db: &ZebraDb,
459    hash_or_height: HashOrHeight,
460) -> Option<BlockInfo>
461where
462    C: AsRef<Chain>,
463{
464    // # Correctness
465    //
466    // Since blocks are the same in the finalized and non-finalized state, we
467    // check the most efficient alternative first. (`chain` is always in memory,
468    // but `db` stores blocks on disk, with a memory cache.)
469    chain
470        .as_ref()
471        .and_then(|chain| chain.as_ref().block_info(hash_or_height))
472        .or_else(|| db.block_info(hash_or_height))
473}