Skip to main content

zebra_state/service/
finalized_state.rs

1//! The primary implementation of the `zebra_state::Service` built upon rocksdb.
2//!
3//! Zebra's database is implemented in 4 layers:
4//! - [`FinalizedState`]: queues, validates, and commits blocks, using...
5//! - [`ZebraDb`]: reads and writes [`zebra_chain`] types to the state database, using...
6//! - [`DiskDb`]: reads and writes generic types to any column family in the database, using...
7//! - [`disk_format`]: converts types to raw database bytes.
8//!
9//! These layers allow us to split [`zebra_chain`] types for efficient database storage.
10//! They reduce the risk of data corruption bugs, runtime inconsistencies, and panics.
11//!
12//! # Correctness
13//!
14//! [`crate::constants::state_database_format_version_in_code()`] must be incremented
15//! each time the database format (column, serialization, etc) changes.
16
17use std::{
18    io::{stderr, stdout, Write},
19    sync::Arc,
20    time::Instant,
21};
22
23use zebra_chain::{
24    amount::{DeferredPoolBalanceChange, NonNegative},
25    block,
26    parallel::tree::NoteCommitmentTrees,
27    parameters::{
28        subsidy::{block_subsidy_with_parent_pools, SubsidyError},
29        Network,
30    },
31    primitives::zcash_history::BlockCommitmentTreeRoots,
32    value_balance::ValueBalance,
33};
34use zebra_db::{
35    chain::BLOCK_INFO,
36    transparent::{BALANCE_BY_TRANSPARENT_ADDR, TX_LOC_BY_SPENT_OUT_LOC},
37};
38
39use crate::{
40    constants::{state_database_format_version_in_code, STATE_DATABASE_KIND},
41    error::CommitCheckpointVerifiedError,
42    request::{FinalizableBlock, FinalizedBlock, Treestate},
43    service::{check, ChainTipBlock, QueuedCheckpointVerified},
44    Config, StateInitError, ValidateContextError,
45};
46
47/// Records the time since the `Option<Instant>` in `$timer` as the block write task phase
48/// `$phase`, then resets `$timer` to now, so consecutive phases can share one timer.
49///
50/// Does nothing if `$timer` is `None`. `$phase` must be a literal, so the metric key is static.
51macro_rules! record_phase {
52    ($timer:expr, $phase:literal) => {
53        if let Some(start) = $timer.as_mut() {
54            let now = std::time::Instant::now();
55            metrics::histogram!(
56                "state.block_writer.phase.duration_seconds",
57                "phase" => $phase
58            )
59            .record(now.duration_since(*start).as_secs_f64());
60            *start = now;
61        }
62    };
63}
64
65pub mod column_family;
66
67mod disk_db;
68mod disk_format;
69mod zebra_db;
70
71#[cfg(any(test, feature = "proptest-impl"))]
72mod arbitrary;
73
74#[cfg(test)]
75mod tests;
76
77#[allow(unused_imports)]
78pub use column_family::{TypedColumnFamily, WriteTypedBatch};
79#[allow(unused_imports)]
80pub use disk_db::{DiskDb, DiskWriteBatch, ReadDisk, WriteDisk};
81#[allow(unused_imports)]
82pub use disk_format::{
83    FromDisk, IntoDisk, OutputLocation, RawBytes, TransactionIndex, TransactionLocation,
84    MAX_ON_DISK_HEIGHT,
85};
86pub use zebra_db::ZebraDb;
87
88#[cfg(any(test, feature = "proptest-impl"))]
89pub use disk_format::KV;
90
91pub use disk_format::upgrade::restorable_db_versions;
92
93/// The column families supported by the running `zebra-state` database code.
94///
95/// Existing column families that aren't listed here are preserved when the database is opened.
96pub const STATE_COLUMN_FAMILIES_IN_CODE: &[&str] = &[
97    // Blocks
98    "hash_by_height",
99    "height_by_hash",
100    "block_header_by_height",
101    // Transactions
102    "tx_by_loc",
103    "hash_by_tx_loc",
104    "tx_loc_by_hash",
105    // Transparent
106    BALANCE_BY_TRANSPARENT_ADDR,
107    "tx_loc_by_transparent_addr_loc",
108    "utxo_by_out_loc",
109    "utxo_loc_by_transparent_addr_loc",
110    TX_LOC_BY_SPENT_OUT_LOC,
111    // Sprout
112    "sprout_nullifiers",
113    "sprout_anchors",
114    "sprout_note_commitment_tree",
115    // Sapling
116    "sapling_nullifiers",
117    "sapling_anchors",
118    "sapling_note_commitment_tree",
119    "sapling_note_commitment_subtree",
120    // Orchard
121    "orchard_nullifiers",
122    "orchard_anchors",
123    "orchard_note_commitment_tree",
124    "orchard_note_commitment_subtree",
125    // Ironwood (NU6.3). Always registered so the database format is stable across build
126    // flags; these stay empty until NU6.3 transactions appear.
127    "ironwood_nullifiers",
128    "ironwood_anchors",
129    "ironwood_note_commitment_tree",
130    "ironwood_note_commitment_subtree",
131    // Chain
132    "history_tree",
133    "tip_chain_value_pool",
134    BLOCK_INFO,
135];
136
137/// The finalized part of the chain state, stored in the db.
138///
139/// `rocksdb` allows concurrent writes through a shared reference,
140/// so clones of the finalized state represent the same database instance.
141/// When the final clone is dropped, the database is closed.
142///
143/// This is different from `NonFinalizedState::clone()`,
144/// which returns an independent copy of the chains.
145#[derive(Clone, Debug)]
146pub struct FinalizedState {
147    // Configuration
148    //
149    // This configuration cannot be modified after the database is initialized,
150    // because some clones would have different values.
151    //
152    /// The configured stop height.
153    ///
154    /// Commit blocks to the finalized state up to this height, then exit Zebra.
155    debug_stop_at_height: Option<block::Height>,
156
157    // Owned State
158    //
159    // Everything contained in this state must be shared by all clones, or read-only.
160    //
161    /// The underlying database.
162    ///
163    /// `rocksdb` allows reads and writes via a shared reference,
164    /// so this database object can be freely cloned.
165    /// The last instance that is dropped will close the underlying database.
166    pub db: ZebraDb,
167}
168
169impl FinalizedState {
170    /// Returns an on-disk database instance for `config` and `network`.
171    /// If there is no existing database, creates a new database on disk.
172    pub fn new(config: &Config, network: &Network) -> Result<Self, StateInitError> {
173        Self::new_with_debug(config, network, false, false)
174    }
175
176    /// Returns an on-disk database instance with the supplied production and debug settings.
177    /// If there is no existing database, creates a new database on disk.
178    ///
179    /// This method is intended for use in tests.
180    #[allow(clippy::unwrap_in_result)]
181    pub(crate) fn new_with_debug(
182        config: &Config,
183        network: &Network,
184        debug_skip_format_upgrades: bool,
185        read_only: bool,
186    ) -> Result<Self, StateInitError> {
187        let db = ZebraDb::new(
188            config,
189            STATE_DATABASE_KIND,
190            &state_database_format_version_in_code(),
191            network,
192            debug_skip_format_upgrades,
193            STATE_COLUMN_FAMILIES_IN_CODE
194                .iter()
195                .map(ToString::to_string),
196            read_only,
197        )?;
198
199        let new_state = Self {
200            debug_stop_at_height: config.debug_stop_at_height.map(block::Height),
201            db,
202        };
203
204        // TODO: move debug_stop_at_height into a task in the start command (#3442)
205        if let Some(tip_height) = new_state.db.finalized_tip_height() {
206            if new_state.is_at_stop_height(tip_height) {
207                let debug_stop_at_height = new_state
208                    .debug_stop_at_height
209                    .expect("true from `is_at_stop_height` implies `debug_stop_at_height` is Some");
210                let tip_hash = new_state.db.finalized_tip_hash();
211
212                if tip_height > debug_stop_at_height {
213                    tracing::error!(
214                        ?debug_stop_at_height,
215                        ?tip_height,
216                        ?tip_hash,
217                        "previous state height is greater than the stop height",
218                    );
219                }
220
221                tracing::info!(
222                    ?debug_stop_at_height,
223                    ?tip_height,
224                    ?tip_hash,
225                    "state is already at the configured height"
226                );
227
228                // RocksDB can do a cleanup when column families are opened.
229                // So we want to drop it before we exit.
230                std::mem::drop(new_state);
231
232                // Drops tracing log output that's hasn't already been written to stdout
233                // since this exits before calling drop on the WorkerGuard for the logger thread.
234                // This is okay for now because this is test-only code
235                //
236                // TODO: Call ZebradApp.shutdown or drop its Tracing component before calling exit_process to flush logs to stdout
237                Self::exit_process();
238            }
239        }
240
241        Ok(new_state)
242    }
243
244    /// Returns the configured network for this database.
245    pub fn network(&self) -> Network {
246        self.db.network()
247    }
248
249    /// Commit a checkpoint-verified block to the state.
250    ///
251    /// Returns the committed chain-tip data and updated note commitment trees.
252    ///
253    /// It's the caller's responsibility to ensure that blocks are committed in
254    /// order.
255    pub fn commit_finalized(
256        &mut self,
257        ordered_block: QueuedCheckpointVerified,
258        prev_note_commitment_trees: Option<NoteCommitmentTrees>,
259    ) -> Result<(ChainTipBlock, NoteCommitmentTrees), CommitCheckpointVerifiedError> {
260        let (checkpoint_verified, rsp_tx) = ordered_block;
261        let tip_block = ChainTipBlock {
262            hash: checkpoint_verified.hash,
263            height: checkpoint_verified.height,
264            time: checkpoint_verified.block.header.time,
265            transactions: checkpoint_verified.block.transactions.clone(),
266            transaction_hashes: checkpoint_verified.transaction_hashes.clone(),
267            previous_block_hash: checkpoint_verified.block.header.previous_block_hash,
268        };
269        let result = self.commit_finalized_direct(
270            checkpoint_verified.into(),
271            prev_note_commitment_trees,
272            "commit checkpoint-verified request",
273        );
274
275        if result.is_ok() {
276            metrics::counter!("state.checkpoint.finalized.block.count").increment(1);
277            metrics::gauge!("state.checkpoint.finalized.block.height")
278                .set(tip_block.height.0 as f64);
279
280            // This height gauge is updated for both fully verified and checkpoint blocks.
281            // These updates can't conflict, because the state makes sure that blocks
282            // are committed in order.
283            metrics::gauge!("zcash.chain.verified.block.height").set(tip_block.height.0 as f64);
284            metrics::counter!("zcash.chain.verified.block.total").increment(1);
285        } else {
286            metrics::counter!("state.checkpoint.error.block.count").increment(1);
287            metrics::gauge!("state.checkpoint.error.block.height").set(tip_block.height.0 as f64);
288        };
289
290        let _ = rsp_tx.send(result.clone().map(|(hash, _)| hash));
291
292        result.map(|(_hash, note_commitment_trees)| (tip_block, note_commitment_trees))
293    }
294
295    /// Immediately commit a `finalized` block to the finalized state.
296    ///
297    /// This can be called either by the non-finalized state (when finalizing
298    /// a block) or by the checkpoint verifier.
299    ///
300    /// Use `source` as the source of the block in log messages.
301    ///
302    /// # Errors
303    ///
304    /// - Propagates any errors from writing to the DB
305    /// - Propagates any errors from updating history and note commitment trees
306    /// - If `hashFinalSaplingRoot` / `hashLightClientRoot` / `hashBlockCommitments`
307    ///   does not match the expected value
308    #[allow(clippy::unwrap_in_result)]
309    pub fn commit_finalized_direct(
310        &mut self,
311        finalizable_block: FinalizableBlock,
312        prev_note_commitment_trees: Option<NoteCommitmentTrees>,
313        source: &str,
314    ) -> Result<(block::Hash, NoteCommitmentTrees), CommitCheckpointVerifiedError> {
315        // Only checkpoint commits are timed, so the `checkpoint_*` phases don't mix in blocks
316        // finalized from the non-finalized state.
317        let mut phase_timer =
318            matches!(finalizable_block, FinalizableBlock::Checkpoint { .. }).then(Instant::now);
319
320        let (height, hash, finalized, prev_note_commitment_trees) = match finalizable_block {
321            FinalizableBlock::Checkpoint {
322                checkpoint_verified,
323            } => {
324                // Checkpoint-verified blocks don't have an associated treestate, so we retrieve the
325                // treestate of the finalized tip from the database and update it for the block
326                // being committed, assuming the retrieved treestate is the parent block's
327                // treestate. Later on, this function proves this assumption by asserting that the
328                // finalized tip is the parent block of the block being committed.
329
330                let block = checkpoint_verified.block.clone();
331                let mut history_tree = self.db.history_tree();
332                let prev_note_commitment_trees = prev_note_commitment_trees
333                    .unwrap_or_else(|| self.db.note_commitment_trees_for_tip());
334                record_phase!(phase_timer, "checkpoint_history_tree_load");
335
336                // Update the note commitment trees.
337                let mut note_commitment_trees = prev_note_commitment_trees.clone();
338                note_commitment_trees
339                    .update_trees_parallel(&block)
340                    .map_err(ValidateContextError::from)?;
341
342                // Check the block commitment if the history tree was not
343                // supplied by the non-finalized state. Note that we don't do
344                // this check for history trees supplied by the non-finalized
345                // state because the non-finalized state checks the block
346                // commitment.
347                //
348                // For Nu5-onward, the block hash commits only to
349                // non-authorizing data (see ZIP-244). This checks the
350                // authorizing data commitment, making sure the entire block
351                // contents were committed to. The test is done here (and not
352                // during semantic validation) because it needs the history tree
353                // root. While it _is_ checked during contextual validation,
354                // that is not called by the checkpoint verifier, and keeping a
355                // history tree there would be harder to implement.
356                //
357                // TODO: run this CPU-intensive cryptography in a parallel rayon
358                // thread, if it shows up in profiles
359                check::block_commitment_is_valid_for_chain_history(
360                    block.clone(),
361                    &self.network(),
362                    &history_tree,
363                )?;
364                record_phase!(phase_timer, "checkpoint_trees_and_commitment");
365
366                // Update the history tree.
367                //
368                // TODO: run this CPU-intensive cryptography in a parallel rayon
369                // thread, if it shows up in profiles
370                let history_tree_mut = Arc::make_mut(&mut history_tree);
371                let sapling_root = note_commitment_trees.sapling.root();
372                let orchard_root = note_commitment_trees.orchard.root();
373                let ironwood_root = note_commitment_trees.ironwood.root();
374                history_tree_mut
375                    .push(
376                        &self.network(),
377                        block.clone(),
378                        BlockCommitmentTreeRoots {
379                            sapling: &sapling_root,
380                            orchard: &orchard_root,
381                            ironwood: &ironwood_root,
382                        },
383                    )
384                    .map_err(Arc::new)
385                    .map_err(ValidateContextError::from)?;
386                record_phase!(phase_timer, "checkpoint_history_tree_push");
387
388                let treestate = Treestate {
389                    note_commitment_trees,
390                    history_tree,
391                };
392
393                let height = checkpoint_verified.height;
394                let deferred_pool_balance_change = calculate_deferred_pool_balance_change(
395                    height,
396                    &self.network(),
397                    self.db.finalized_value_pool(),
398                )
399                .map_err(|subsidy_error| ValidateContextError::InvalidSubsidy {
400                    subsidy_error: subsidy_error.into(),
401                    height,
402                    block_hash: checkpoint_verified.hash,
403                })?;
404                record_phase!(phase_timer, "checkpoint_value_pool");
405
406                (
407                    height,
408                    checkpoint_verified.hash,
409                    FinalizedBlock::from_checkpoint_verified(
410                        checkpoint_verified,
411                        treestate,
412                        deferred_pool_balance_change,
413                    ),
414                    Some(prev_note_commitment_trees),
415                )
416            }
417            FinalizableBlock::Contextual {
418                contextually_verified,
419                treestate,
420            } => {
421                let height = contextually_verified.height;
422                let deferred_pool_balance_change = calculate_deferred_pool_balance_change(
423                    height,
424                    &self.network(),
425                    self.db.finalized_value_pool(),
426                )
427                .map_err(|subsidy_error| ValidateContextError::InvalidSubsidy {
428                    subsidy_error: subsidy_error.into(),
429                    height,
430                    block_hash: contextually_verified.hash,
431                })?;
432
433                (
434                    height,
435                    contextually_verified.hash,
436                    FinalizedBlock::from_contextually_verified(
437                        contextually_verified,
438                        treestate,
439                        deferred_pool_balance_change,
440                    ),
441                    prev_note_commitment_trees,
442                )
443            }
444        };
445
446        let committed_tip_hash = self.db.finalized_tip_hash();
447        let committed_tip_height = self.db.finalized_tip_height();
448
449        // Assert that callers (including unit tests) get the chain order correct
450        if self.db.is_empty() {
451            assert_eq!(
452                committed_tip_hash, finalized.block.header.previous_block_hash,
453                "the first block added to an empty state must be a genesis block, source: {source}",
454            );
455            assert_eq!(
456                block::Height(0),
457                height,
458                "cannot commit genesis: invalid height, source: {source}",
459            );
460        } else {
461            assert_eq!(
462                committed_tip_height.expect("state must have a genesis block committed") + 1,
463                Some(height),
464                "committed block height must be 1 more than the finalized tip height, source: {source}",
465            );
466
467            assert_eq!(
468                committed_tip_hash, finalized.block.header.previous_block_hash,
469                "committed block must be a child of the finalized tip, source: {source}",
470            );
471        }
472
473        let note_commitment_trees = finalized.treestate.note_commitment_trees.clone();
474        record_phase!(phase_timer, "checkpoint_tip_checks");
475
476        let result = self.db.write_block(
477            finalized,
478            prev_note_commitment_trees,
479            &self.network(),
480            source,
481            &mut phase_timer,
482        );
483
484        if result.is_ok() {
485            // TODO: move the stop height check to the syncer (#3442)
486            if self.is_at_stop_height(height) {
487                tracing::info!(
488                    ?height,
489                    ?hash,
490                    block_source = ?source,
491                    "stopping at configured height, flushing database to disk"
492                );
493
494                // We're just about to do a forced exit, so it's ok to do a forced db shutdown
495                self.db.shutdown(true);
496
497                // Drops tracing log output that's hasn't already been written to stdout
498                // since this exits before calling drop on the WorkerGuard for the logger thread.
499                // This is okay for now because this is test-only code
500                //
501                // TODO: Call ZebradApp.shutdown or drop its Tracing component before calling exit_process to flush logs to stdout
502                Self::exit_process();
503            }
504        }
505
506        result.map(|hash| (hash, note_commitment_trees))
507    }
508
509    /// Stop the process if `block_height` is greater than or equal to the
510    /// configured stop height.
511    fn is_at_stop_height(&self, block_height: block::Height) -> bool {
512        let debug_stop_at_height = match self.debug_stop_at_height {
513            Some(debug_stop_at_height) => debug_stop_at_height,
514            None => return false,
515        };
516
517        block_height >= debug_stop_at_height
518    }
519
520    /// Exit the host process.
521    ///
522    /// Designed for debugging and tests.
523    ///
524    /// TODO: move the stop height check to the syncer (#3442)
525    fn exit_process() -> ! {
526        tracing::info!("exiting Zebra");
527
528        // Some OSes require a flush to send all output to the terminal.
529        // Zebra's logging doesn't depend on `tokio`, so we flush the stdlib sync streams.
530        //
531        // TODO: if this doesn't work, send an empty line as well.
532        let _ = stdout().lock().flush();
533        let _ = stderr().lock().flush();
534
535        // Give some time to logger thread to flush out any remaining lines to stdout
536        // and yield so that tests pass on MacOS
537        std::thread::sleep(std::time::Duration::from_secs(3));
538
539        // Exits before calling drop on the WorkerGuard for the logger thread,
540        // dropping any lines that haven't already been written to stdout.
541        // This is okay for now because this is test-only code
542        std::process::exit(0);
543    }
544}
545
546/// Calculates deferred issuance and fixed lockbox disbursements using the exact parent's pools.
547pub(crate) fn calculate_deferred_pool_balance_change(
548    height: block::Height,
549    network: &Network,
550    parent_chain_value_pools: ValueBalance<NonNegative>,
551) -> Result<DeferredPoolBalanceChange, SubsidyError> {
552    zebra_chain::parameters::subsidy::funding_stream_values(
553        height,
554        network,
555        block_subsidy_with_parent_pools(height, network, parent_chain_value_pools)?,
556    )?
557    .remove(&zebra_chain::parameters::subsidy::FundingStreamReceiver::Deferred)
558    .unwrap_or_default()
559    .checked_sub(network.lockbox_disbursement_total_amount(height))
560    .map(DeferredPoolBalanceChange::new)
561    .ok_or(SubsidyError::Underflow)
562}