Skip to main content

zebra_state/service/finalized_state/zebra_db/
block.rs

1//! Provides high-level access to database [`Block`]s and [`Transaction`]s.
2//!
3//! This module makes sure that:
4//! - all disk writes happen inside a RocksDB transaction, and
5//! - format-specific invariants are maintained.
6//!
7//! # Correctness
8//!
9//! [`crate::constants::state_database_format_version_in_code()`] must be incremented
10//! each time the database format (column, serialization, etc) changes.
11
12use std::{
13    collections::{BTreeMap, HashMap, HashSet},
14    ops::RangeBounds,
15    sync::Arc,
16};
17
18use chrono::{DateTime, Utc};
19use itertools::Itertools;
20
21use zebra_chain::{
22    amount::NonNegative,
23    block::{self, Block, Height},
24    orchard,
25    parallel::tree::NoteCommitmentTrees,
26    parameters::{Network, GENESIS_PREVIOUS_BLOCK_HASH},
27    primitives::byte_array::increment_big_endian,
28    sapling,
29    serialization::{CompactSizeMessage, TrustedPreallocate, ZcashSerialize as _},
30    transaction::{self, Transaction},
31    transparent,
32    value_balance::ValueBalance,
33};
34
35use crate::{
36    error::{BlockReadError, CommitCheckpointVerifiedError},
37    request::FinalizedBlock,
38    service::finalized_state::{
39        disk_db::{DiskDb, DiskWriteBatch, ReadDisk, WriteDisk},
40        disk_format::{
41            block::TransactionLocation,
42            transparent::{AddressBalanceLocationUpdates, OutputLocation},
43        },
44        zebra_db::{metrics::block_precommit_metrics, ZebraDb},
45        FromDisk, IntoDisk, RawBytes,
46    },
47    HashOrHeight,
48};
49
50#[cfg(feature = "indexer")]
51use crate::request::Spend;
52
53#[cfg(test)]
54mod tests;
55
56impl ZebraDb {
57    // Read block methods
58
59    /// Returns true if the database is empty.
60    //
61    // TODO: move this method to the tip section
62    pub fn is_empty(&self) -> bool {
63        let hash_by_height = self.db.cf_handle("hash_by_height").unwrap();
64        self.db.zs_is_empty(&hash_by_height)
65    }
66
67    /// Returns the tip height and hash, if there is one.
68    //
69    // TODO: rename to finalized_tip()
70    //       move this method to the tip section
71    #[allow(clippy::unwrap_in_result)]
72    pub fn tip(&self) -> Option<(block::Height, block::Hash)> {
73        let hash_by_height = self.db.cf_handle("hash_by_height").unwrap();
74        self.db.zs_last_key_value(&hash_by_height)
75    }
76
77    /// Returns `true` if `height` is present in the finalized state.
78    #[allow(clippy::unwrap_in_result)]
79    pub fn contains_height(&self, height: block::Height) -> bool {
80        let hash_by_height = self.db.cf_handle("hash_by_height").unwrap();
81
82        self.db.zs_contains(&hash_by_height, &height)
83    }
84
85    /// Returns the finalized hash for a given `block::Height` if it is present.
86    #[allow(clippy::unwrap_in_result)]
87    pub fn hash(&self, height: block::Height) -> Option<block::Hash> {
88        let hash_by_height = self.db.cf_handle("hash_by_height").unwrap();
89        self.db.zs_get(&hash_by_height, &height)
90    }
91
92    /// Returns `true` if `hash` is present in the finalized state.
93    #[allow(clippy::unwrap_in_result)]
94    pub fn contains_hash(&self, hash: block::Hash) -> bool {
95        let height_by_hash = self.db.cf_handle("height_by_hash").unwrap();
96
97        self.db.zs_contains(&height_by_hash, &hash)
98    }
99
100    /// Returns the height of the given block if it exists.
101    #[allow(clippy::unwrap_in_result)]
102    pub fn height(&self, hash: block::Hash) -> Option<block::Height> {
103        let height_by_hash = self.db.cf_handle("height_by_hash").unwrap();
104        self.db.zs_get(&height_by_hash, &hash)
105    }
106
107    /// Returns the previous block hash for the given block hash in the finalized state.
108    #[allow(dead_code)]
109    pub fn prev_block_hash_for_hash(&self, hash: block::Hash) -> Option<block::Hash> {
110        let height = self.height(hash)?;
111        let prev_height = height.previous().ok()?;
112
113        self.hash(prev_height)
114    }
115
116    /// Returns the previous block height for the given block hash in the finalized state.
117    #[allow(dead_code)]
118    pub fn prev_block_height_for_hash(&self, hash: block::Hash) -> Option<block::Height> {
119        let height = self.height(hash)?;
120
121        height.previous().ok()
122    }
123
124    /// Returns the [`block::Header`] with [`block::Hash`] or
125    /// [`Height`], if it exists in the finalized chain.
126    //
127    // TODO: move this method to the start of the section
128    #[allow(clippy::unwrap_in_result)]
129    pub fn block_header(&self, hash_or_height: HashOrHeight) -> Option<Arc<block::Header>> {
130        // Block Header
131        let block_header_by_height = self.db.cf_handle("block_header_by_height").unwrap();
132
133        let height = hash_or_height.height_or_else(|hash| self.height(hash))?;
134        let header = self.db.zs_get(&block_header_by_height, &height)?;
135
136        Some(header)
137    }
138
139    /// Returns the complete block, or `None` if its hash or height is unknown.
140    ///
141    /// Returns an error if primary data is incomplete. An incomplete secondary view returns `None`.
142    pub fn block(
143        &self,
144        hash_or_height: HashOrHeight,
145    ) -> Result<Option<Arc<Block>>, BlockReadError> {
146        Ok(self
147            .complete_block(hash_or_height, |header: &Arc<block::Header>| {
148                header.merkle_root
149            })?
150            .map(|(header, transactions)| {
151                Arc::new(Block {
152                    header,
153                    transactions,
154                })
155            }))
156    }
157
158    /// Returns the complete block and its serialized size, or `None` for an unknown block.
159    ///
160    /// Returns an error if primary data is incomplete. An incomplete secondary view returns `None`.
161    #[allow(clippy::unwrap_in_result)]
162    pub fn block_and_size(
163        &self,
164        hash_or_height: HashOrHeight,
165    ) -> Result<Option<(Arc<Block>, usize)>, BlockReadError> {
166        let Some((raw_header, raw_txs)) = self.raw_block(hash_or_height)? else {
167            return Ok(None);
168        };
169
170        let header = Arc::<block::Header>::from_bytes(raw_header.raw_bytes());
171        let txs: Vec<_> = raw_txs
172            .iter()
173            .map(|raw_tx| Arc::<Transaction>::from_bytes(raw_tx.raw_bytes()))
174            .collect();
175
176        // Compute the size of the block from the size of header and size of
177        // transactions. This requires summing them all and also adding the
178        // size of the CompactSize-encoded transaction count.
179        // See https://developer.bitcoin.org/reference/block_chain.html#serialized-blocks
180        let tx_count = CompactSizeMessage::try_from(txs.len())
181            .expect("must work for a previously serialized block");
182        let tx_raw = tx_count
183            .zcash_serialize_to_vec()
184            .expect("must work for a previously serialized block");
185        let size = raw_header.raw_bytes().len()
186            + raw_txs
187                .iter()
188                .map(|raw_tx| raw_tx.raw_bytes().len())
189                .sum::<usize>()
190            + tx_raw.len();
191
192        let block = Block {
193            header,
194            transactions: txs,
195        };
196        Ok(Some((Arc::new(block), size)))
197    }
198
199    /// Returns the complete serialized header and transactions, or `None` for an unknown block.
200    fn raw_block(
201        &self,
202        hash_or_height: HashOrHeight,
203    ) -> Result<Option<(RawBytes, Vec<RawBytes>)>, BlockReadError> {
204        self.complete_block(hash_or_height, |header: &RawBytes| {
205            block::Header::from_bytes(header.raw_bytes()).merkle_root
206        })
207    }
208
209    /// Reads one complete body without intermediate serialized copies.
210    ///
211    /// Headers and transaction indexes are retained permanently. Check the body's contiguous
212    /// locations against the final indexed location, so deletion cannot produce a partial block.
213    /// This also works on secondary databases, which do not support RocksDB snapshots.
214    /// Secondary reads also check the Merkle root because catch-up can expose partial indexes.
215    #[allow(clippy::unwrap_in_result)]
216    fn complete_block<H: FromDisk, T: FromDisk>(
217        &self,
218        hash_or_height: HashOrHeight,
219        header_merkle_root: impl FnOnce(&H) -> block::merkle::Root,
220    ) -> Result<Option<(H, Vec<T>)>, BlockReadError> {
221        let Some(height) = hash_or_height.height_or_else(|hash| self.height(hash)) else {
222            return Ok(None);
223        };
224        let incomplete = |error| {
225            // Secondary catch-up is not atomic across columns, so an incomplete view is not yet
226            // visible. The retained-body floor will later distinguish genuinely pruned bodies.
227            if self.db.is_read_only() {
228                Ok(None)
229            } else {
230                Err(error)
231            }
232        };
233        let headers = self.db.cf_handle("block_header_by_height").unwrap();
234        let header = match self.db.zs_get(&headers, &height) {
235            Some(header) => header,
236            None => {
237                #[cfg(test)]
238                tests::AFTER_MISSING_HEADER.with(|hook| {
239                    if let Some(commit) = hook.borrow_mut().take() {
240                        commit();
241                    }
242                });
243                if !matches!(hash_or_height, HashOrHeight::Hash(_)) && !self.contains_height(height)
244                {
245                    return Ok(None);
246                }
247                // A commit can land between the header and height reads.
248                match self.db.zs_get(&headers, &height) {
249                    Some(header) => header,
250                    None => return incomplete(BlockReadError::CorruptBlock { height }),
251                }
252            }
253        };
254
255        let tx_by_loc = self.db.cf_handle("tx_by_loc").unwrap();
256        let hash_by_tx_loc = self.db.cf_handle("hash_by_tx_loc").unwrap();
257        let first = TransactionLocation::min_for_height(height).as_bytes();
258        let last = TransactionLocation::max_for_height(height).as_bytes();
259        let mut hashes = self
260            .db
261            .raw_iterator_cf_opt(&hash_by_tx_loc, Default::default());
262        hashes.seek_for_prev(last);
263        hashes.status().expect("unexpected database failure");
264        let Some(last_location) = hashes
265            .key()
266            .map(TransactionLocation::from_bytes)
267            .filter(|location| location.height == height)
268        else {
269            return incomplete(BlockReadError::CorruptBlock { height });
270        };
271        let expected_count = last_location.index.as_usize() + 1;
272
273        let mut upper_bound = Vec::with_capacity(last.len() + 1);
274        upper_bound.extend_from_slice(&last);
275        if increment_big_endian(&mut upper_bound) {
276            upper_bound.insert(0, 1);
277        }
278        let mut options = rocksdb::ReadOptions::default();
279        options.set_iterate_upper_bound(upper_bound);
280        let mut bodies = self.db.raw_iterator_cf_opt(&tx_by_loc, options);
281        bodies.seek(first);
282        let mut transactions = Vec::with_capacity(expected_count);
283        // TODO: consider separating transaction reads from deserialization so decoding can run
284        // in parallel. Benchmark blocks with multiple large shielded transactions to check
285        // whether the speedup justifies buffering the serialized transactions.
286        while let Some(key) = bodies.key().filter(|key| *key <= last.as_ref()) {
287            let location = TransactionLocation::from_bytes(key);
288            if location.index.as_usize() != transactions.len() {
289                return incomplete(BlockReadError::BlockBodyUnavailable { height });
290            }
291            if transactions.len() >= expected_count {
292                return incomplete(BlockReadError::CorruptBlock { height });
293            }
294            transactions.push(T::from_bytes(
295                bodies.value().expect("a valid iterator has a value"),
296            ));
297            bodies.next();
298        }
299        bodies.status().expect("unexpected database failure");
300        if transactions.len() != expected_count {
301            return incomplete(BlockReadError::BlockBodyUnavailable { height });
302        }
303
304        if self.db.is_read_only() {
305            // Secondary WAL replay can expose matching prefixes of both columns. Only the header
306            // commits to the complete transaction list; primary write batches are atomically visible.
307            hashes.seek(first);
308            hashes.status().expect("unexpected database failure");
309            if hashes.key() != Some(first.as_ref()) {
310                return Ok(None);
311            }
312            let mut remaining = expected_count;
313            let root: block::merkle::Root = std::iter::from_fn(|| {
314                if remaining == 0 {
315                    return None;
316                }
317                let (key, value) = hashes.item()?;
318                if key > last.as_ref() {
319                    return None;
320                }
321                let hash = transaction::Hash::from_bytes(value);
322                remaining -= 1;
323                if remaining > 0 {
324                    hashes.next();
325                }
326                Some(hash)
327            })
328            .collect();
329            hashes.status().expect("unexpected database failure");
330            if remaining != 0 || root != header_merkle_root(&header) {
331                return Ok(None);
332            }
333        }
334
335        Ok(Some((header, transactions)))
336    }
337
338    /// Returns the Sapling [`note commitment tree`](sapling::tree::NoteCommitmentTree) specified by
339    /// a hash or height, if it exists in the finalized state.
340    #[allow(clippy::unwrap_in_result)]
341    pub fn sapling_tree_by_hash_or_height(
342        &self,
343        hash_or_height: HashOrHeight,
344    ) -> Option<Arc<sapling::tree::NoteCommitmentTree>> {
345        let height = hash_or_height.height_or_else(|hash| self.height(hash))?;
346
347        self.sapling_tree_by_height(&height)
348    }
349
350    /// Returns the Orchard [`note commitment tree`](orchard::tree::NoteCommitmentTree) specified by
351    /// a hash or height, if it exists in the finalized state.
352    #[allow(clippy::unwrap_in_result)]
353    pub fn orchard_tree_by_hash_or_height(
354        &self,
355        hash_or_height: HashOrHeight,
356    ) -> Option<Arc<orchard::tree::NoteCommitmentTree>> {
357        let height = hash_or_height.height_or_else(|hash| self.height(hash))?;
358
359        self.orchard_tree_by_height(&height)
360    }
361
362    /// Returns the Ironwood [`note commitment tree`](orchard::tree::NoteCommitmentTree) specified by
363    /// a hash or height, if it exists in the finalized state.
364    #[allow(clippy::unwrap_in_result)]
365    pub fn ironwood_tree_by_hash_or_height(
366        &self,
367        hash_or_height: HashOrHeight,
368    ) -> Option<Arc<orchard::tree::NoteCommitmentTree>> {
369        let height = hash_or_height.height_or_else(|hash| self.height(hash))?;
370
371        self.ironwood_tree_by_height(&height)
372    }
373
374    // Read tip block methods
375
376    /// Returns the hash of the current finalized tip block.
377    pub fn finalized_tip_hash(&self) -> block::Hash {
378        self.tip()
379            .map(|(_, hash)| hash)
380            // if the state is empty, return the genesis previous block hash
381            .unwrap_or(GENESIS_PREVIOUS_BLOCK_HASH)
382    }
383
384    /// Returns the height of the current finalized tip block.
385    pub fn finalized_tip_height(&self) -> Option<block::Height> {
386        self.tip().map(|(height, _)| height)
387    }
388
389    /// Returns the complete tip block, or `None` for an empty database.
390    ///
391    /// Returns an error if primary data is incomplete. An incomplete secondary view returns `None`.
392    pub fn tip_block(&self) -> Result<Option<Arc<Block>>, BlockReadError> {
393        match self.tip() {
394            Some((height, _)) => self.block(height.into()),
395            None => Ok(None),
396        }
397    }
398
399    // Read transaction methods
400
401    /// Returns the [`Transaction`] with [`transaction::Hash`], and its [`Height`],
402    /// if a transaction with that hash exists in the finalized chain.
403    #[allow(clippy::unwrap_in_result)]
404    pub fn transaction(
405        &self,
406        hash: transaction::Hash,
407    ) -> Option<(Arc<Transaction>, Height, DateTime<Utc>)> {
408        let tx_by_loc = self.db.cf_handle("tx_by_loc").unwrap();
409
410        let transaction_location = self.transaction_location(hash)?;
411
412        let block_time = self
413            .block_header(transaction_location.height.into())
414            .map(|header| header.time);
415
416        self.db
417            .zs_get(&tx_by_loc, &transaction_location)
418            .and_then(|tx| block_time.map(|time| (tx, transaction_location.height, time)))
419    }
420
421    /// Returns an iterator of all [`Transaction`]s for a provided block height in finalized state.
422    #[allow(clippy::unwrap_in_result)]
423    pub fn transactions_by_height(
424        &self,
425        height: Height,
426    ) -> impl Iterator<Item = (TransactionLocation, Transaction)> + '_ {
427        self.transactions_by_location_range(
428            TransactionLocation::min_for_height(height)
429                ..=TransactionLocation::max_for_height(height),
430        )
431    }
432
433    /// Returns an iterator of all [`Transaction`]s in the provided range
434    /// of [`TransactionLocation`]s in finalized state.
435    #[allow(clippy::unwrap_in_result)]
436    pub fn transactions_by_location_range<R>(
437        &self,
438        range: R,
439    ) -> impl Iterator<Item = (TransactionLocation, Transaction)> + '_
440    where
441        R: RangeBounds<TransactionLocation>,
442    {
443        let tx_by_loc = self.db.cf_handle("tx_by_loc").unwrap();
444        self.db.zs_forward_range_iter(tx_by_loc, range)
445    }
446
447    /// Returns an iterator of all raw [`Transaction`]s in the provided range
448    /// of [`TransactionLocation`]s in finalized state.
449    #[allow(clippy::unwrap_in_result)]
450    pub fn raw_transactions_by_location_range<R>(
451        &self,
452        range: R,
453    ) -> impl Iterator<Item = (TransactionLocation, RawBytes)> + '_
454    where
455        R: RangeBounds<TransactionLocation>,
456    {
457        let tx_by_loc = self.db.cf_handle("tx_by_loc").unwrap();
458        self.db.zs_forward_range_iter(tx_by_loc, range)
459    }
460
461    /// Returns the [`TransactionLocation`] for [`transaction::Hash`],
462    /// if it exists in the finalized chain.
463    #[allow(clippy::unwrap_in_result)]
464    pub fn transaction_location(&self, hash: transaction::Hash) -> Option<TransactionLocation> {
465        let tx_loc_by_hash = self.db.cf_handle("tx_loc_by_hash").unwrap();
466        self.db.zs_get(&tx_loc_by_hash, &hash)
467    }
468
469    /// Returns the [`transaction::Hash`] for [`TransactionLocation`],
470    /// if it exists in the finalized chain.
471    #[allow(clippy::unwrap_in_result)]
472    #[allow(dead_code)]
473    pub fn transaction_hash(&self, location: TransactionLocation) -> Option<transaction::Hash> {
474        let hash_by_tx_loc = self.db.cf_handle("hash_by_tx_loc").unwrap();
475        self.db.zs_get(&hash_by_tx_loc, &location)
476    }
477
478    /// Returns the [`transaction::Hash`] of the transaction that spent or revealed the given
479    /// [`transparent::OutPoint`] or nullifier, if it is spent or revealed in the finalized state.
480    #[cfg(feature = "indexer")]
481    pub fn spending_transaction_hash(&self, spend: &Spend) -> Option<transaction::Hash> {
482        let tx_loc = match spend {
483            Spend::OutPoint(outpoint) => self.spending_tx_loc(outpoint)?,
484            Spend::Sprout(nullifier) => self.sprout_revealing_tx_loc(nullifier)?,
485            Spend::Sapling(nullifier) => self.sapling_revealing_tx_loc(nullifier)?,
486            Spend::Orchard(nullifier) => self.orchard_revealing_tx_loc(nullifier)?,
487            Spend::Ironwood(nullifier) => self.ironwood_revealing_tx_loc(nullifier)?,
488        };
489
490        self.transaction_hash(tx_loc)
491    }
492
493    /// Returns the [`transaction::Hash`]es in the block with `hash_or_height`,
494    /// if it exists in this chain.
495    ///
496    /// Hashes are returned in block order.
497    ///
498    /// Returns `None` if the block is not found.
499    #[allow(clippy::unwrap_in_result)]
500    pub fn transaction_hashes_for_block(
501        &self,
502        hash_or_height: HashOrHeight,
503    ) -> Option<Arc<[transaction::Hash]>> {
504        // Block
505        let height = hash_or_height.height_or_else(|hash| self.height(hash))?;
506
507        // Transaction hashes
508        let hash_by_tx_loc = self.db.cf_handle("hash_by_tx_loc").unwrap();
509
510        // Manually fetch the entire block's transaction hashes
511        let mut transaction_hashes = Vec::new();
512
513        for tx_index in 0..=Transaction::max_allocation() {
514            let tx_loc = TransactionLocation::from_u64(height, tx_index);
515
516            if let Some(tx_hash) = self.db.zs_get(&hash_by_tx_loc, &tx_loc) {
517                transaction_hashes.push(tx_hash);
518            } else {
519                break;
520            }
521        }
522
523        Some(transaction_hashes.into())
524    }
525
526    // Write block methods
527
528    /// Write `finalized` to the finalized state.
529    ///
530    /// Uses:
531    /// - `history_tree`: the current tip's history tree
532    /// - `network`: the configured network
533    /// - `source`: the source of the block in log messages
534    ///
535    /// # Errors
536    ///
537    /// - Propagates any errors from writing to the DB
538    /// - Propagates any errors from computing the block's chain value balance change or
539    ///   from applying the change to the chain value balance
540    #[allow(clippy::unwrap_in_result)]
541    pub(in super::super) fn write_block(
542        &mut self,
543        finalized: FinalizedBlock,
544        prev_note_commitment_trees: Option<NoteCommitmentTrees>,
545        network: &Network,
546        source: &str,
547        phase_timer: &mut Option<std::time::Instant>,
548    ) -> Result<block::Hash, CommitCheckpointVerifiedError> {
549        let tx_hash_indexes: HashMap<transaction::Hash, usize> = finalized
550            .transaction_hashes
551            .iter()
552            .enumerate()
553            .map(|(index, hash)| (*hash, index))
554            .collect();
555
556        // Get a list of the new UTXOs in the format we need for database updates.
557        //
558        // TODO: index new_outputs by TransactionLocation,
559        //       simplify the spent_utxos location lookup code,
560        //       and remove the extra new_outputs_by_out_loc argument
561        let new_outputs_by_out_loc: BTreeMap<OutputLocation, transparent::Utxo> = finalized
562            .new_outputs
563            .iter()
564            .map(|(outpoint, ordered_utxo)| {
565                (
566                    lookup_out_loc(finalized.height, outpoint, &tx_hash_indexes),
567                    ordered_utxo.utxo.clone(),
568                )
569            })
570            .collect();
571
572        // Get a list of the spent UTXOs, before we delete any from the database
573        let spent_utxos: Vec<(transparent::OutPoint, OutputLocation, transparent::Utxo)> =
574            finalized
575                .block
576                .transactions
577                .iter()
578                .flat_map(|tx| tx.inputs().into_iter())
579                .flat_map(|input| input.outpoint())
580                .map(|outpoint| {
581                    (
582                        outpoint,
583                        // Some utxos are spent in the same block, so they will be in
584                        // `tx_hash_indexes` and `new_outputs`
585                        self.output_location(&outpoint).unwrap_or_else(|| {
586                            lookup_out_loc(finalized.height, &outpoint, &tx_hash_indexes)
587                        }),
588                        self.utxo(&outpoint)
589                            .map(|ordered_utxo| ordered_utxo.utxo)
590                            .or_else(|| {
591                                finalized
592                                    .new_outputs
593                                    .get(&outpoint)
594                                    .map(|ordered_utxo| ordered_utxo.utxo.clone())
595                            })
596                            .expect("already checked UTXO was in state or block"),
597                    )
598                })
599                .collect();
600
601        let spent_utxos_by_outpoint: HashMap<transparent::OutPoint, transparent::Utxo> =
602            spent_utxos
603                .iter()
604                .map(|(outpoint, _output_loc, utxo)| (*outpoint, utxo.clone()))
605                .collect();
606
607        // TODO: Add `OutputLocation`s to the values in `spent_utxos_by_outpoint` to avoid creating a second hashmap with the same keys
608        #[cfg(feature = "indexer")]
609        let out_loc_by_outpoint: HashMap<transparent::OutPoint, OutputLocation> = spent_utxos
610            .iter()
611            .map(|(outpoint, out_loc, _utxo)| (*outpoint, *out_loc))
612            .collect();
613        let spent_utxos_by_out_loc: BTreeMap<OutputLocation, transparent::Utxo> = spent_utxos
614            .into_iter()
615            .map(|(_outpoint, out_loc, utxo)| (out_loc, utxo))
616            .collect();
617        record_phase!(phase_timer, "checkpoint_spent_outputs");
618
619        // Get the transparent addresses with changed balances/UTXOs
620        let changed_addresses: HashSet<transparent::Address> = spent_utxos_by_out_loc
621            .values()
622            .chain(
623                finalized
624                    .new_outputs
625                    .values()
626                    .map(|ordered_utxo| &ordered_utxo.utxo),
627            )
628            .filter_map(|utxo| utxo.output.address(network))
629            .unique()
630            .collect();
631
632        // Get the current address balances, before the transactions in this block
633
634        fn read_addr_locs<T, F: Fn(&transparent::Address) -> Option<T>>(
635            changed_addresses: HashSet<transparent::Address>,
636            f: F,
637        ) -> HashMap<transparent::Address, T> {
638            changed_addresses
639                .into_iter()
640                .filter_map(|address| Some((address, f(&address)?)))
641                .collect()
642        }
643
644        // # Performance
645        //
646        // It's better to update entries in RocksDB with insertions over merge operations when there is no risk that
647        // insertions may overwrite values that are updated concurrently in database format upgrades as inserted values
648        // are quicker to read and require less background compaction.
649        //
650        // Reading entries that have been updated with merge ops often requires reading the latest fully-merged value,
651        // reading all of the pending merge operands (potentially hundreds), and applying pending merge operands to the
652        // fully-merged value such that it's much faster to read entries that have been updated with insertions than it
653        // is to read entries that have been updated with merge operations.
654        let address_balances: AddressBalanceLocationUpdates = if self.finished_format_upgrades() {
655            AddressBalanceLocationUpdates::Insert(read_addr_locs(changed_addresses, |addr| {
656                self.address_balance_location(addr)
657            }))
658        } else {
659            AddressBalanceLocationUpdates::Merge(read_addr_locs(changed_addresses, |addr| {
660                Some(self.address_balance_location(addr)?.into_new_change())
661            }))
662        };
663        record_phase!(phase_timer, "checkpoint_address_balances");
664
665        let mut batch = DiskWriteBatch::new();
666
667        // In case of errors, propagate and do not write the batch.
668        batch.prepare_block_batch(
669            self,
670            network,
671            &finalized,
672            new_outputs_by_out_loc,
673            spent_utxos_by_outpoint,
674            spent_utxos_by_out_loc,
675            #[cfg(feature = "indexer")]
676            out_loc_by_outpoint,
677            address_balances,
678            self.finalized_value_pool(),
679            prev_note_commitment_trees,
680        )?;
681        record_phase!(phase_timer, "checkpoint_batch_build");
682
683        // Track batch commit latency for observability
684        let batch_start = std::time::Instant::now();
685        if let Err(error) = self.db.write(batch) {
686            panic!("unexpected rocksdb error while writing block: {error}");
687        }
688        metrics::histogram!("zebra.state.rocksdb.batch_commit.duration_seconds")
689            .record(batch_start.elapsed().as_secs_f64());
690        record_phase!(phase_timer, "checkpoint_db_write");
691
692        tracing::trace!(?source, "committed block from");
693
694        Ok(finalized.hash)
695    }
696
697    /// Writes the given batch to the database.
698    pub fn write_batch(&self, batch: DiskWriteBatch) -> Result<(), rocksdb::Error> {
699        self.db.write(batch)
700    }
701}
702
703/// Lookup the output location for an outpoint.
704///
705/// `tx_hash_indexes` must contain `outpoint.hash` and that transaction's index in its block.
706fn lookup_out_loc(
707    height: Height,
708    outpoint: &transparent::OutPoint,
709    tx_hash_indexes: &HashMap<transaction::Hash, usize>,
710) -> OutputLocation {
711    let tx_index = tx_hash_indexes
712        .get(&outpoint.hash)
713        .expect("already checked UTXO was in state or block");
714
715    let tx_loc = TransactionLocation::from_usize(height, *tx_index);
716
717    OutputLocation::from_outpoint(tx_loc, outpoint)
718}
719
720impl DiskWriteBatch {
721    // Write block methods
722
723    /// Prepare a database batch containing `finalized.block`,
724    /// and return it (without actually writing anything).
725    ///
726    /// If this method returns an error, it will be propagated,
727    /// and the batch should not be written to the database.
728    ///
729    /// # Errors
730    ///
731    /// - Propagates any errors from computing the block's chain value balance change or
732    ///   from applying the change to the chain value balance
733    #[allow(clippy::too_many_arguments)]
734    pub fn prepare_block_batch(
735        &mut self,
736        zebra_db: &ZebraDb,
737        network: &Network,
738        finalized: &FinalizedBlock,
739        new_outputs_by_out_loc: BTreeMap<OutputLocation, transparent::Utxo>,
740        spent_utxos_by_outpoint: HashMap<transparent::OutPoint, transparent::Utxo>,
741        spent_utxos_by_out_loc: BTreeMap<OutputLocation, transparent::Utxo>,
742        #[cfg(feature = "indexer")] out_loc_by_outpoint: HashMap<
743            transparent::OutPoint,
744            OutputLocation,
745        >,
746        address_balances: AddressBalanceLocationUpdates,
747        value_pool: ValueBalance<NonNegative>,
748        prev_note_commitment_trees: Option<NoteCommitmentTrees>,
749    ) -> Result<(), CommitCheckpointVerifiedError> {
750        let db = &zebra_db.db;
751
752        // Commit block, transaction, and note commitment tree data.
753        self.prepare_block_header_and_transaction_data_batch(db, finalized);
754
755        // The consensus rules are silent on shielded transactions in the genesis block,
756        // because there aren't any in the mainnet or testnet genesis blocks.
757        // So this means the genesis anchor is the same as the empty anchor,
758        // which is already present from height 1 to the first shielded transaction.
759        //
760        // In Zebra we include the nullifiers and note commitments in the genesis block because it simplifies our code.
761        self.prepare_shielded_transaction_batch(zebra_db, finalized);
762        self.prepare_trees_batch(zebra_db, finalized, prev_note_commitment_trees);
763
764        // # Consensus
765        //
766        // > A transaction MUST NOT spend an output of the genesis block coinbase transaction.
767        // > (There is one such zero-valued output, on each of Testnet and Mainnet.)
768        //
769        // https://zips.z.cash/protocol/protocol.pdf#txnconsensus
770        //
771        // Ignore genesis UTXOs and the transparent address index. The shared block value-pool
772        // calculation also excludes these unspendable outputs; shielded updates are retained.
773        if !finalized.height.is_min() {
774            // Commit transaction indexes
775            self.prepare_transparent_transaction_batch(
776                zebra_db,
777                network,
778                finalized,
779                &new_outputs_by_out_loc,
780                &spent_utxos_by_outpoint,
781                &spent_utxos_by_out_loc,
782                #[cfg(feature = "indexer")]
783                &out_loc_by_outpoint,
784                address_balances,
785            );
786        }
787
788        // Commit UTXOs and value pools
789        self.prepare_chain_value_pools_batch(
790            zebra_db,
791            finalized,
792            spent_utxos_by_outpoint,
793            value_pool,
794        )?;
795
796        // The block has passed contextual validation, so update the metrics
797        block_precommit_metrics(&finalized.block, finalized.hash, finalized.height);
798
799        Ok(())
800    }
801
802    /// Prepare a database batch containing the block header and transaction data
803    /// from `finalized.block`, and return it (without actually writing anything).
804    #[allow(clippy::unwrap_in_result)]
805    pub fn prepare_block_header_and_transaction_data_batch(
806        &mut self,
807        db: &DiskDb,
808        finalized: &FinalizedBlock,
809    ) {
810        // Blocks
811        let block_header_by_height = db.cf_handle("block_header_by_height").unwrap();
812        let hash_by_height = db.cf_handle("hash_by_height").unwrap();
813        let height_by_hash = db.cf_handle("height_by_hash").unwrap();
814
815        // Transactions
816        let tx_by_loc = db.cf_handle("tx_by_loc").unwrap();
817        let hash_by_tx_loc = db.cf_handle("hash_by_tx_loc").unwrap();
818        let tx_loc_by_hash = db.cf_handle("tx_loc_by_hash").unwrap();
819
820        let FinalizedBlock {
821            block,
822            hash,
823            height,
824            transaction_hashes,
825            ..
826        } = finalized;
827
828        // Commit block header data
829        self.zs_insert(&block_header_by_height, height, &block.header);
830
831        // Index the block hash and height
832        self.zs_insert(&hash_by_height, height, hash);
833        self.zs_insert(&height_by_hash, hash, height);
834
835        for (transaction_index, (transaction, transaction_hash)) in block
836            .transactions
837            .iter()
838            .zip(transaction_hashes.iter())
839            .enumerate()
840        {
841            let transaction_location = TransactionLocation::from_usize(*height, transaction_index);
842
843            // Commit each transaction's data
844            self.zs_insert(&tx_by_loc, transaction_location, transaction);
845
846            // Index each transaction hash and location
847            self.zs_insert(&hash_by_tx_loc, transaction_location, transaction_hash);
848            self.zs_insert(&tx_loc_by_hash, transaction_hash, transaction_location);
849        }
850    }
851}