zebra_state/request.rs
1//! State [`tower::Service`] request types.
2
3use std::{
4 collections::{HashMap, HashSet},
5 mem::{size_of, size_of_val},
6 ops::{Add, Deref, DerefMut, RangeInclusive},
7 pin::Pin,
8 sync::Arc,
9 time::Instant,
10};
11
12use tower::{BoxError, Service, ServiceExt};
13use zebra_chain::{
14 amount::{Amount, DeferredPoolBalanceChange, NegativeAllowed, NonNegative},
15 block::{self, Block, HeightDiff},
16 diagnostic::{task::WaitForPanics, CodeTimer},
17 history_tree::HistoryTree,
18 parallel::tree::NoteCommitmentTrees,
19 parameters::Network,
20 serialization::{SerializationError, ZcashSerialize},
21 subtree::NoteCommitmentSubtreeIndex,
22 transaction::{self, UnminedTx},
23 transparent,
24 value_balance::{ValueBalance, ValueBalanceError},
25};
26
27/// Allow *only* these unused imports, so that rustdoc link resolution
28/// will work with inline links.
29#[allow(unused_imports)]
30use crate::{
31 constants::{MAX_FIND_BLOCK_HASHES_RESULTS, MAX_FIND_BLOCK_HEADERS_RESULTS},
32 CommitBlockError, ReadResponse, Response,
33};
34use crate::{
35 error::{InvalidateError, LayeredStateError, ReconsiderError},
36 AwaitUtxoError, CommitCheckpointVerifiedError, CommitSemanticallyVerifiedError,
37};
38
39/// The per-pool nullifier types used by the indexer-only [`Spend`] enum, imported here rather than
40/// in the shared import block because they are only referenced under the `indexer` feature.
41#[cfg(feature = "indexer")]
42use zebra_chain::{ironwood, orchard, sapling, sprout};
43
44/// Identify a spend by a transparent outpoint or revealed nullifier.
45///
46/// This enum implements `From` for [`transparent::OutPoint`], [`sprout::Nullifier`],
47/// [`sapling::Nullifier`], [`orchard::Nullifier`], and [`ironwood::Nullifier`].
48#[derive(Copy, Clone, Debug, PartialEq, Eq)]
49#[cfg(feature = "indexer")]
50pub enum Spend {
51 /// A spend identified by a [`transparent::OutPoint`].
52 OutPoint(transparent::OutPoint),
53 /// A spend identified by a [`sprout::Nullifier`].
54 Sprout(sprout::Nullifier),
55 /// A spend identified by a [`sapling::Nullifier`].
56 Sapling(sapling::Nullifier),
57 /// A spend identified by a [`orchard::Nullifier`].
58 Orchard(orchard::Nullifier),
59 /// A spend identified by an [`ironwood::Nullifier`].
60 Ironwood(ironwood::Nullifier),
61}
62
63#[cfg(feature = "indexer")]
64impl From<transparent::OutPoint> for Spend {
65 fn from(outpoint: transparent::OutPoint) -> Self {
66 Self::OutPoint(outpoint)
67 }
68}
69
70#[cfg(feature = "indexer")]
71impl From<sprout::Nullifier> for Spend {
72 fn from(sprout_nullifier: sprout::Nullifier) -> Self {
73 Self::Sprout(sprout_nullifier)
74 }
75}
76
77#[cfg(feature = "indexer")]
78impl From<sapling::Nullifier> for Spend {
79 fn from(sapling_nullifier: sapling::Nullifier) -> Self {
80 Self::Sapling(sapling_nullifier)
81 }
82}
83
84#[cfg(feature = "indexer")]
85impl From<orchard::Nullifier> for Spend {
86 fn from(orchard_nullifier: orchard::Nullifier) -> Self {
87 Self::Orchard(orchard_nullifier)
88 }
89}
90
91#[cfg(feature = "indexer")]
92impl From<ironwood::Nullifier> for Spend {
93 fn from(ironwood_nullifier: ironwood::Nullifier) -> Self {
94 Self::Ironwood(ironwood_nullifier)
95 }
96}
97
98/// Identify a block by hash or height.
99///
100/// This enum implements `From` for [`block::Hash`] and [`block::Height`],
101/// so it can be created using `hash.into()` or `height.into()`.
102#[derive(Copy, Clone, Debug, PartialEq, Eq)]
103pub enum HashOrHeight {
104 /// A block identified by hash.
105 Hash(block::Hash),
106 /// A block identified by height.
107 Height(block::Height),
108}
109
110impl HashOrHeight {
111 /// Unwrap the inner height or attempt to retrieve the height for a given
112 /// hash if one exists.
113 pub fn height_or_else<F>(self, op: F) -> Option<block::Height>
114 where
115 F: FnOnce(block::Hash) -> Option<block::Height>,
116 {
117 match self {
118 HashOrHeight::Hash(hash) => op(hash),
119 HashOrHeight::Height(height) => Some(height),
120 }
121 }
122
123 /// Unwrap the inner hash or attempt to retrieve the hash for a given
124 /// height if one exists.
125 ///
126 /// # Consensus
127 ///
128 /// In the non-finalized state, a height can have multiple valid hashes.
129 /// We typically use the hash that is currently on the best chain.
130 pub fn hash_or_else<F>(self, op: F) -> Option<block::Hash>
131 where
132 F: FnOnce(block::Height) -> Option<block::Hash>,
133 {
134 match self {
135 HashOrHeight::Hash(hash) => Some(hash),
136 HashOrHeight::Height(height) => op(height),
137 }
138 }
139
140 /// Returns the hash if this is a [`HashOrHeight::Hash`].
141 pub fn hash(&self) -> Option<block::Hash> {
142 if let HashOrHeight::Hash(hash) = self {
143 Some(*hash)
144 } else {
145 None
146 }
147 }
148
149 /// Returns the height if this is a [`HashOrHeight::Height`].
150 pub fn height(&self) -> Option<block::Height> {
151 if let HashOrHeight::Height(height) = self {
152 Some(*height)
153 } else {
154 None
155 }
156 }
157
158 /// Constructs a new [`HashOrHeight`] from a string containing a hash or a positive or negative
159 /// height.
160 ///
161 /// When the provided `hash_or_height` contains a negative height, the `tip_height` parameter
162 /// needs to be `Some` since height `-1` points to the tip.
163 pub fn new(hash_or_height: &str, tip_height: Option<block::Height>) -> Result<Self, String> {
164 hash_or_height
165 .parse()
166 .map(Self::Hash)
167 .or_else(|_| hash_or_height.parse().map(Self::Height))
168 .or_else(|_| {
169 hash_or_height
170 .parse()
171 .map_err(|_| "could not parse negative height")
172 .and_then(|d: HeightDiff| {
173 if d.is_negative() {
174 {
175 Ok(HashOrHeight::Height(
176 tip_height
177 .ok_or("missing tip height")?
178 .add(d)
179 .ok_or("underflow when adding negative height to tip")?
180 .next()
181 .map_err(|_| "height -1 needs to point to tip")?,
182 ))
183 }
184 } else {
185 Err("height was not negative")
186 }
187 })
188 })
189 .map_err(|_| {
190 "parse error: could not convert the input string to a hash or height".to_string()
191 })
192 }
193}
194
195impl std::fmt::Display for HashOrHeight {
196 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197 match self {
198 HashOrHeight::Hash(hash) => write!(f, "{hash}"),
199 HashOrHeight::Height(height) => write!(f, "{}", height.0),
200 }
201 }
202}
203
204impl From<block::Hash> for HashOrHeight {
205 fn from(hash: block::Hash) -> Self {
206 Self::Hash(hash)
207 }
208}
209
210impl From<block::Height> for HashOrHeight {
211 fn from(height: block::Height) -> Self {
212 Self::Height(height)
213 }
214}
215
216impl From<(block::Height, block::Hash)> for HashOrHeight {
217 fn from((_height, hash): (block::Height, block::Hash)) -> Self {
218 // Hash is more specific than height for the non-finalized state
219 hash.into()
220 }
221}
222
223impl From<(block::Hash, block::Height)> for HashOrHeight {
224 fn from((hash, _height): (block::Hash, block::Height)) -> Self {
225 hash.into()
226 }
227}
228
229impl std::str::FromStr for HashOrHeight {
230 type Err = SerializationError;
231
232 fn from_str(s: &str) -> Result<Self, Self::Err> {
233 s.parse()
234 .map(Self::Hash)
235 .or_else(|_| s.parse().map(Self::Height))
236 .map_err(|_| {
237 SerializationError::Parse("could not convert the input string to a hash or height")
238 })
239 }
240}
241
242/// A block which has undergone semantic validation and has been prepared for
243/// contextual validation.
244///
245/// It is the constructor's responsibility to perform semantic validation and to
246/// ensure that all fields are consistent.
247///
248/// This structure contains data from contextual validation, which is computed in
249/// the *service caller*'s task, not inside the service call itself. This allows
250/// moving work out of the single-threaded state service.
251#[derive(Clone, Debug, PartialEq, Eq)]
252pub struct SemanticallyVerifiedBlock {
253 /// The block to commit to the state.
254 pub block: Arc<Block>,
255 /// The hash of the block.
256 pub hash: block::Hash,
257 /// The height of the block.
258 pub height: block::Height,
259 /// New transparent outputs created in this block, indexed by
260 /// [`OutPoint`](transparent::OutPoint).
261 ///
262 /// Each output is tagged with its transaction index in the block.
263 /// (The outputs of earlier transactions in a block can be spent by later
264 /// transactions.)
265 ///
266 /// Note: although these transparent outputs are newly created, they may not
267 /// be unspent, since a later transaction in a block can spend outputs of an
268 /// earlier transaction.
269 ///
270 /// This field can also contain unrelated outputs, which are ignored.
271 pub new_outputs: HashMap<transparent::OutPoint, transparent::OrderedUtxo>,
272 /// A precomputed list of the hashes of the transactions in this block,
273 /// in the same order as `block.transactions`.
274 pub transaction_hashes: Arc<[transaction::Hash]>,
275
276 /// The local time at which the block verifier received this block, if it passed
277 /// through the block verifier.
278 ///
279 /// Used by `Chain::cmp` to prefer the first-received chain when cumulative works
280 /// are equal, per the protocol specification:
281 ///
282 /// > To break ties between leaf blocks, a node will prefer the block that it received first.
283 ///
284 /// <https://zips.z.cash/protocol/protocol.pdf#blockchain>
285 ///
286 /// This is node-local, in-memory metadata, not consensus data. It is `None` for
287 /// blocks constructed outside the block verifier (checkpoint sync, backup restore,
288 /// tests); `Chain::cmp` treats unstamped blocks as received before any stamped
289 /// block, like `zcashd`'s disk-loaded blocks, which all share `nSequenceId` 0.
290 pub received_time: Option<Instant>,
291}
292
293/// A block ready to be committed directly to the finalized state with
294/// a small number of checks if compared with a `ContextuallyVerifiedBlock`.
295///
296/// This is exposed for use in checkpointing.
297///
298/// Note: The difference between a `CheckpointVerifiedBlock` and a `ContextuallyVerifiedBlock` is
299/// that the `CheckpointVerifier` doesn't bind the transaction authorizing data to the
300/// `ChainHistoryBlockTxAuthCommitmentHash`, but the `NonFinalizedState` and `FinalizedState` do.
301#[derive(Clone, Debug, PartialEq, Eq)]
302pub struct CheckpointVerifiedBlock(pub(crate) SemanticallyVerifiedBlock);
303
304// Some fields are pub(crate), so we can add whatever db-format-dependent
305// precomputation we want here without leaking internal details.
306
307/// A contextually verified block, ready to be committed directly to the finalized state with no
308/// checks, if it becomes the root of the best non-finalized chain.
309///
310/// Used by the state service and non-finalized `Chain`.
311///
312/// Note: The difference between a `CheckpointVerifiedBlock` and a `ContextuallyVerifiedBlock` is
313/// that the `CheckpointVerifier` doesn't bind the transaction authorizing data to the
314/// `ChainHistoryBlockTxAuthCommitmentHash`, but the `NonFinalizedState` and `FinalizedState` do.
315#[derive(Clone, Debug, PartialEq, Eq)]
316pub struct ContextuallyVerifiedBlock {
317 /// The block to commit to the state.
318 pub(crate) block: Arc<Block>,
319
320 /// The hash of the block.
321 pub(crate) hash: block::Hash,
322
323 /// The height of the block.
324 pub(crate) height: block::Height,
325
326 /// New transparent outputs created in this block, indexed by
327 /// [`OutPoint`](transparent::OutPoint).
328 ///
329 /// Note: although these transparent outputs are newly created, they may not
330 /// be unspent, since a later transaction in a block can spend outputs of an
331 /// earlier transaction.
332 ///
333 /// This field can also contain unrelated outputs, which are ignored.
334 ///
335 /// The non-finalized chain indexes share these outputs, instead of copying them.
336 pub(crate) new_outputs: Arc<HashMap<transparent::OutPoint, Arc<transparent::OrderedUtxo>>>,
337
338 /// The outputs spent by this block, indexed by the [`transparent::Input`]'s
339 /// [`OutPoint`](transparent::OutPoint).
340 ///
341 /// Note: these inputs can come from earlier transactions in this block,
342 /// or earlier blocks in the chain.
343 ///
344 /// This field can also contain unrelated outputs, which are ignored.
345 pub(crate) spent_outputs: Arc<HashMap<transparent::OutPoint, transparent::OrderedUtxo>>,
346
347 /// A precomputed list of the hashes of the transactions in this block,
348 /// in the same order as `block.transactions`.
349 pub(crate) transaction_hashes: Arc<[transaction::Hash]>,
350
351 /// The sum of the chain value pool changes of all transactions in this block.
352 pub(crate) chain_value_pool_change: ValueBalance<NegativeAllowed>,
353
354 /// The local time at which the block verifier received this block, if it passed
355 /// through the block verifier, copied from the [`SemanticallyVerifiedBlock`] it was
356 /// built from. See that type's `received_time` field for details.
357 pub(crate) received_time: Option<Instant>,
358}
359
360/// Wraps note commitment trees and the history tree together.
361///
362/// The default instance represents the treestate that corresponds to the genesis block.
363#[derive(Clone, Debug, Default, Eq, PartialEq)]
364pub struct Treestate {
365 /// Note commitment trees.
366 pub note_commitment_trees: NoteCommitmentTrees,
367 /// History tree.
368 pub history_tree: Arc<HistoryTree>,
369}
370
371impl Treestate {
372 #[allow(missing_docs)]
373 pub(crate) fn new(
374 note_commitment_trees: NoteCommitmentTrees,
375 history_tree: Arc<HistoryTree>,
376 ) -> Self {
377 Self {
378 note_commitment_trees,
379 history_tree,
380 }
381 }
382}
383
384/// Contains a block ready to be committed.
385///
386/// Zebra's state service passes this `enum` over to the finalized state
387/// when committing a block.
388#[allow(missing_docs, clippy::large_enum_variant)]
389pub enum FinalizableBlock {
390 Checkpoint {
391 checkpoint_verified: CheckpointVerifiedBlock,
392 },
393 Contextual {
394 contextually_verified: ContextuallyVerifiedBlock,
395 treestate: Treestate,
396 },
397}
398
399/// Contains a block with all its associated data that the finalized state can commit to its
400/// database.
401///
402/// Note that it's the constructor's responsibility to ensure that all data is valid and verified.
403pub struct FinalizedBlock {
404 /// The block to commit to the state.
405 pub(super) block: Arc<Block>,
406 /// The hash of the block.
407 pub(super) hash: block::Hash,
408 /// The height of the block.
409 pub(super) height: block::Height,
410 /// New transparent outputs created in this block, indexed by
411 /// [`OutPoint`](transparent::OutPoint).
412 pub(super) new_outputs: HashMap<transparent::OutPoint, transparent::OrderedUtxo>,
413 /// A precomputed list of the hashes of the transactions in this block, in the same order as
414 /// `block.transactions`.
415 pub(super) transaction_hashes: Arc<[transaction::Hash]>,
416 /// The tresstate associated with the block.
417 pub(super) treestate: Treestate,
418 /// This block's deferred pool value balance change.
419 pub(super) deferred_pool_balance_change: DeferredPoolBalanceChange,
420}
421
422impl FinalizedBlock {
423 /// Constructs [`FinalizedBlock`] from [`CheckpointVerifiedBlock`] and its [`Treestate`].
424 pub fn from_checkpoint_verified(
425 block: CheckpointVerifiedBlock,
426 treestate: Treestate,
427 deferred_pool_balance_change: DeferredPoolBalanceChange,
428 ) -> Self {
429 Self::from_semantically_verified(
430 SemanticallyVerifiedBlock::from(block),
431 treestate,
432 deferred_pool_balance_change,
433 )
434 }
435
436 /// Constructs [`FinalizedBlock`] from [`ContextuallyVerifiedBlock`] and its [`Treestate`].
437 pub fn from_contextually_verified(
438 block: ContextuallyVerifiedBlock,
439 treestate: Treestate,
440 deferred_pool_balance_change: DeferredPoolBalanceChange,
441 ) -> Self {
442 Self::from_semantically_verified(
443 SemanticallyVerifiedBlock::from(block),
444 treestate,
445 deferred_pool_balance_change,
446 )
447 }
448
449 /// Constructs [`FinalizedBlock`] from [`SemanticallyVerifiedBlock`] and its [`Treestate`].
450 fn from_semantically_verified(
451 block: SemanticallyVerifiedBlock,
452 treestate: Treestate,
453 deferred_pool_balance_change: DeferredPoolBalanceChange,
454 ) -> Self {
455 Self {
456 block: block.block,
457 hash: block.hash,
458 height: block.height,
459 new_outputs: block.new_outputs,
460 transaction_hashes: block.transaction_hashes,
461 treestate,
462 deferred_pool_balance_change,
463 }
464 }
465}
466
467impl FinalizableBlock {
468 /// Create a new [`FinalizableBlock`] given a [`ContextuallyVerifiedBlock`].
469 pub fn new(contextually_verified: ContextuallyVerifiedBlock, treestate: Treestate) -> Self {
470 Self::Contextual {
471 contextually_verified,
472 treestate,
473 }
474 }
475
476 #[cfg(test)]
477 /// Extract a [`Block`] from a [`FinalizableBlock`] variant.
478 pub fn inner_block(&self) -> Arc<Block> {
479 match self {
480 FinalizableBlock::Checkpoint {
481 checkpoint_verified,
482 } => checkpoint_verified.block.clone(),
483 FinalizableBlock::Contextual {
484 contextually_verified,
485 ..
486 } => contextually_verified.block.clone(),
487 }
488 }
489}
490
491impl From<CheckpointVerifiedBlock> for FinalizableBlock {
492 fn from(checkpoint_verified: CheckpointVerifiedBlock) -> Self {
493 Self::Checkpoint {
494 checkpoint_verified,
495 }
496 }
497}
498
499impl From<Arc<Block>> for FinalizableBlock {
500 fn from(block: Arc<Block>) -> Self {
501 Self::from(CheckpointVerifiedBlock::from(block))
502 }
503}
504
505impl From<&SemanticallyVerifiedBlock> for SemanticallyVerifiedBlock {
506 fn from(semantically_verified: &SemanticallyVerifiedBlock) -> Self {
507 semantically_verified.clone()
508 }
509}
510
511// Doing precomputation in these impls means that it will be done in
512// the *service caller*'s task, not inside the service call itself.
513// This allows moving work out of the single-threaded state service.
514
515impl ContextuallyVerifiedBlock {
516 /// Rebinds the result of validating a block proposal to `block`, the solved proposal.
517 ///
518 /// The caller must check `block`'s proof of work, and that `block` is the same as the
519 /// proposal apart from its nonce and Equihash solution. That includes the authorizing data
520 /// of its transactions, which transaction and block equality don't compare. The receipt
521 /// time is the solved block's, not the proposal's.
522 ///
523 /// # Correctness
524 ///
525 /// Nothing checks the result after this, so a mismatched block would be committed with a
526 /// validation result that isn't its own. This is only for the block verifier's solved
527 /// proposal path; see [`Request::CommitContextuallyVerifiedBlock`].
528 pub fn rebind(&mut self, block: Arc<Block>, received_time: Instant) {
529 self.hash = block.hash();
530 self.block = block;
531 self.received_time = Some(received_time);
532 }
533
534 /// Create a block that's ready for non-finalized `Chain` contextual validation,
535 /// using a [`SemanticallyVerifiedBlock`] and the UTXOs it spends.
536 ///
537 /// `spent_outputs` must contain the [`Utxo`](transparent::Utxo)s spent by every transparent
538 /// input in this block, including UTXOs created by earlier transactions in this block.
539 ///
540 /// `previous_value_pools` and `deferred_pool_balance_change` must use the exact parent.
541 /// This constructor calculates ledger changes, but does not validate coinbase payouts or
542 /// funding outputs. The state service checks parent-dependent subsidy and miner fees before
543 /// pushing the block onto the non-finalized chain.
544 ///
545 /// A [`ContextuallyVerifiedBlock`] is only contextually valid after all state service
546 /// validation succeeds; construction or
547 /// [`Chain::push()`](crate::service::non_finalized_state::Chain::push) alone is not sufficient.
548 ///
549 /// # Panics
550 ///
551 /// If `spent_outputs` is missing the UTXO of a transparent input.
552 pub fn with_block_and_spent_utxos(
553 semantically_verified: SemanticallyVerifiedBlock,
554 spent_outputs: HashMap<transparent::OutPoint, transparent::OrderedUtxo>,
555 deferred_pool_balance_change: DeferredPoolBalanceChange,
556 network: &Network,
557 previous_value_pools: ValueBalance<NonNegative>,
558 ) -> Result<Self, ValueBalanceError> {
559 Self::with_block_spent_utxos_and_fees(
560 semantically_verified,
561 spent_outputs,
562 deferred_pool_balance_change,
563 network,
564 previous_value_pools,
565 )
566 .map(|(contextually_verified, _transaction_fees)| contextually_verified)
567 }
568
569 /// Like [`Self::with_block_and_spent_utxos`], and also returns the block's gross transaction
570 /// fees, as returned by [`Block::chain_value_pool_change_and_fees`].
571 pub(crate) fn with_block_spent_utxos_and_fees(
572 semantically_verified: SemanticallyVerifiedBlock,
573 spent_outputs: HashMap<transparent::OutPoint, transparent::OrderedUtxo>,
574 deferred_pool_balance_change: DeferredPoolBalanceChange,
575 network: &Network,
576 previous_value_pools: ValueBalance<NonNegative>,
577 ) -> Result<(Self, Option<Amount<NonNegative>>), ValueBalanceError> {
578 let SemanticallyVerifiedBlock {
579 block,
580 hash,
581 height,
582 new_outputs,
583 transaction_hashes,
584 received_time,
585 } = semantically_verified;
586
587 let (chain_value_pool_change, transaction_fees) = block.chain_value_pool_change_and_fees(
588 &spent_outputs,
589 deferred_pool_balance_change,
590 network,
591 previous_value_pools,
592 )?;
593
594 Ok((
595 Self {
596 block,
597 hash,
598 height,
599 new_outputs: Arc::new(
600 new_outputs
601 .into_iter()
602 .map(|(outpoint, utxo)| (outpoint, Arc::new(utxo)))
603 .collect(),
604 ),
605 spent_outputs: Arc::new(spent_outputs),
606 transaction_hashes,
607 chain_value_pool_change,
608 received_time,
609 },
610 transaction_fees,
611 ))
612 }
613}
614
615impl CheckpointVerifiedBlock {
616 /// Creates a [`CheckpointVerifiedBlock`] from [`Block`] with optional deferred balance and
617 /// optional pre-computed hash.
618 pub fn new(block: Arc<Block>, hash: Option<block::Hash>) -> Self {
619 Self::with_hash(block.clone(), hash.unwrap_or(block.hash()))
620 }
621 /// Creates a block that's ready to be committed to the finalized state,
622 /// using a precalculated [`block::Hash`].
623 ///
624 /// Note: a [`CheckpointVerifiedBlock`] isn't actually finalized
625 /// until [`Request::CommitCheckpointVerifiedBlock`] returns success.
626 pub fn with_hash(block: Arc<Block>, hash: block::Hash) -> Self {
627 Self(SemanticallyVerifiedBlock::with_hash(block, hash))
628 }
629}
630
631impl SemanticallyVerifiedBlock {
632 /// Creates [`SemanticallyVerifiedBlock`] from [`Block`] and [`block::Hash`].
633 pub fn with_hash(block: Arc<Block>, hash: block::Hash) -> Self {
634 let height = block
635 .coinbase_height()
636 .expect("semantically verified block should have a coinbase height");
637 let transaction_hashes: Arc<[_]> = block.transactions.iter().map(|tx| tx.hash()).collect();
638 let new_outputs = transparent::new_ordered_outputs(&block, &transaction_hashes);
639
640 Self {
641 block,
642 hash,
643 height,
644 new_outputs,
645 transaction_hashes,
646 received_time: None,
647 }
648 }
649
650 /// Returns an estimate of the memory this block keeps alive, in bytes.
651 ///
652 /// Queues of blocks that can't be verified or committed yet use it to limit their memory. A
653 /// decoded block can be many times larger than its serialized size, for example when it has
654 /// many small transactions or transparent outputs, so this also counts its decoded transactions
655 /// and [`Self::new_outputs`].
656 pub fn retained_bytes(&self) -> usize {
657 let transactions = &self.block.transactions;
658 let mut bytes = self.block.zcash_serialized_size()
659 + transactions.capacity() * size_of::<Arc<transaction::Transaction>>()
660 + size_of_val(&*self.transaction_hashes)
661 + new_outputs_retained_bytes(&self.new_outputs);
662
663 for transaction in transactions {
664 bytes += size_of_val(transaction.as_ref());
665 if let Some(bundle) = transaction.transparent_bundle() {
666 bytes += size_of_val(bundle.vin.as_slice()) + size_of_val(bundle.vout.as_slice());
667 }
668 }
669
670 bytes
671 }
672}
673
674/// Returns the memory used by `new_outputs`, including their scripts, in bytes.
675pub(crate) fn new_outputs_retained_bytes(
676 new_outputs: &HashMap<transparent::OutPoint, transparent::OrderedUtxo>,
677) -> usize {
678 new_outputs.capacity() * size_of::<(transparent::OutPoint, transparent::OrderedUtxo)>()
679 + new_outputs
680 .values()
681 .map(|output| output.utxo.output.lock_script.as_raw_bytes().len())
682 .sum::<usize>()
683}
684
685impl From<Arc<Block>> for CheckpointVerifiedBlock {
686 fn from(block: Arc<Block>) -> Self {
687 CheckpointVerifiedBlock(SemanticallyVerifiedBlock::from(block))
688 }
689}
690
691impl From<Arc<Block>> for SemanticallyVerifiedBlock {
692 fn from(block: Arc<Block>) -> Self {
693 let hash = block.hash();
694 let height = block
695 .coinbase_height()
696 .expect("semantically verified block should have a coinbase height");
697 let transaction_hashes: Arc<[_]> = block.transactions.iter().map(|tx| tx.hash()).collect();
698 let new_outputs = transparent::new_ordered_outputs(&block, &transaction_hashes);
699
700 Self {
701 block,
702 hash,
703 height,
704 new_outputs,
705 transaction_hashes,
706 received_time: None,
707 }
708 }
709}
710
711impl From<ContextuallyVerifiedBlock> for SemanticallyVerifiedBlock {
712 fn from(valid: ContextuallyVerifiedBlock) -> Self {
713 Self {
714 block: valid.block,
715 hash: valid.hash,
716 height: valid.height,
717 new_outputs: Arc::unwrap_or_clone(valid.new_outputs)
718 .into_iter()
719 .map(|(outpoint, utxo)| (outpoint, Arc::unwrap_or_clone(utxo)))
720 .collect(),
721 transaction_hashes: valid.transaction_hashes,
722 received_time: valid.received_time,
723 }
724 }
725}
726
727impl From<FinalizedBlock> for SemanticallyVerifiedBlock {
728 fn from(finalized: FinalizedBlock) -> Self {
729 Self {
730 block: finalized.block,
731 hash: finalized.hash,
732 height: finalized.height,
733 new_outputs: finalized.new_outputs,
734 transaction_hashes: finalized.transaction_hashes,
735 // The finalized state does not track receipt times, so there is no stamp.
736 received_time: None,
737 }
738 }
739}
740
741impl From<CheckpointVerifiedBlock> for SemanticallyVerifiedBlock {
742 fn from(checkpoint_verified: CheckpointVerifiedBlock) -> Self {
743 checkpoint_verified.0
744 }
745}
746
747impl Deref for CheckpointVerifiedBlock {
748 type Target = SemanticallyVerifiedBlock;
749
750 fn deref(&self) -> &Self::Target {
751 &self.0
752 }
753}
754impl DerefMut for CheckpointVerifiedBlock {
755 fn deref_mut(&mut self) -> &mut Self::Target {
756 &mut self.0
757 }
758}
759
760/// Helper trait for convenient access to expected response and error types.
761pub trait MappedRequest: Sized + Send + 'static {
762 /// Expected response type for this state request.
763 type MappedResponse;
764 /// Expected error type for this state request.
765 type Error: std::error::Error + std::fmt::Display + 'static;
766
767 /// Maps the request type to a [`Request`].
768 fn map_request(self) -> Request;
769
770 /// Maps the expected [`Response`] variant for this request to the mapped response type.
771 fn map_response(response: Response) -> Self::MappedResponse;
772
773 /// Accepts a state service to call, maps this request to a [`Request`], waits for the state to be ready,
774 /// calls the state with the mapped request, then maps the success or error response to the expected response
775 /// or error type for this request.
776 ///
777 /// Returns a [`Result<MappedResponse, LayeredServicesError<RequestError>>`].
778 #[allow(async_fn_in_trait)]
779 async fn mapped_oneshot<State>(
780 self,
781 state: &mut State,
782 ) -> Result<Self::MappedResponse, LayeredStateError<Self::Error>>
783 where
784 State: Service<Request, Response = Response, Error = BoxError>,
785 State::Future: Send,
786 {
787 let response = state.ready().await?.call(self.map_request()).await?;
788 Ok(Self::map_response(response))
789 }
790}
791
792/// Performs contextual validation of the given semantically verified block,
793/// committing it to the state if successful.
794///
795/// See the [`crate`] documentation and [`Request::CommitSemanticallyVerifiedBlock`] for details.
796pub struct CommitSemanticallyVerifiedBlockRequest(pub SemanticallyVerifiedBlock);
797
798impl MappedRequest for CommitSemanticallyVerifiedBlockRequest {
799 type MappedResponse = block::Hash;
800 type Error = CommitSemanticallyVerifiedError;
801
802 fn map_request(self) -> Request {
803 Request::CommitSemanticallyVerifiedBlock(self.0)
804 }
805
806 fn map_response(response: Response) -> Self::MappedResponse {
807 match response {
808 Response::Committed(hash) => hash,
809 _ => unreachable!("wrong response variant for request"),
810 }
811 }
812}
813
814/// Commit a checkpointed block to the state
815///
816/// See the [`crate`] documentation and [`Request::CommitCheckpointVerifiedBlock`] for details.
817#[allow(dead_code)]
818pub struct CommitCheckpointVerifiedBlockRequest(pub CheckpointVerifiedBlock);
819
820impl MappedRequest for CommitCheckpointVerifiedBlockRequest {
821 type MappedResponse = block::Hash;
822 type Error = CommitCheckpointVerifiedError;
823
824 fn map_request(self) -> Request {
825 Request::CommitCheckpointVerifiedBlock(self.0)
826 }
827
828 fn map_response(response: Response) -> Self::MappedResponse {
829 match response {
830 Response::Committed(hash) => hash,
831 _ => unreachable!("wrong response variant for request"),
832 }
833 }
834}
835
836/// Request to invalidate a block in the state.
837///
838/// See the [`crate`] documentation and [`Request::InvalidateBlock`] for details.
839#[allow(dead_code)]
840pub struct InvalidateBlockRequest(pub block::Hash);
841
842impl MappedRequest for InvalidateBlockRequest {
843 type MappedResponse = block::Hash;
844 type Error = InvalidateError;
845
846 fn map_request(self) -> Request {
847 Request::InvalidateBlock(self.0)
848 }
849
850 fn map_response(response: Response) -> Self::MappedResponse {
851 match response {
852 Response::Invalidated(hash) => hash,
853 _ => unreachable!("wrong response variant for request"),
854 }
855 }
856}
857
858/// Request to reconsider a previously invalidated block and re-commit it to the state.
859///
860/// See the [`crate`] documentation and [`Request::ReconsiderBlock`] for details.
861#[allow(dead_code)]
862pub struct ReconsiderBlockRequest(pub block::Hash);
863
864impl MappedRequest for ReconsiderBlockRequest {
865 type MappedResponse = Vec<block::Hash>;
866 type Error = ReconsiderError;
867
868 fn map_request(self) -> Request {
869 Request::ReconsiderBlock(self.0)
870 }
871
872 fn map_response(response: Response) -> Self::MappedResponse {
873 match response {
874 Response::Reconsidered(hashes) => hashes,
875 _ => unreachable!("wrong response variant for request"),
876 }
877 }
878}
879
880/// Request a UTXO, waiting for it to arrive if it is not yet available.
881///
882/// See the [`crate`] documentation and [`Request::AwaitUtxo`] for details.
883#[allow(dead_code)]
884pub struct AwaitUtxoRequest(pub transparent::OutPoint);
885
886impl MappedRequest for AwaitUtxoRequest {
887 type MappedResponse = transparent::Utxo;
888 type Error = AwaitUtxoError;
889
890 fn map_request(self) -> Request {
891 Request::AwaitUtxo(self.0)
892 }
893
894 fn map_response(response: Response) -> Self::MappedResponse {
895 match response {
896 Response::Utxo(utxo) => utxo,
897 _ => unreachable!("wrong response variant for request"),
898 }
899 }
900}
901
902#[derive(Clone, Debug, PartialEq, Eq)]
903/// A query about or modification to the chain state, via the
904/// [`StateService`](crate::service::StateService).
905pub enum Request {
906 /// Performs contextual validation of the given semantically verified block,
907 /// committing it to the state if successful.
908 ///
909 /// This request can be made out-of-order; the state service will queue it
910 /// until its parent is ready. The queue has a size limit: when it is full, the state fails the
911 /// highest queued blocks with [`CommitBlockError::OrphanQueueFull`].
912 ///
913 /// Returns [`Response::Committed`] with the hash of the block when it is
914 /// committed to the state, or a [`CommitSemanticallyVerifiedError`][0] if
915 /// the block fails contextual validation or otherwise could not be committed.
916 ///
917 /// This request cannot be cancelled once submitted; dropping the response
918 /// future will have no effect on whether it is eventually processed. A
919 /// request to commit a block which has been queued internally but not yet
920 /// committed will fail the older request and replace it with the newer request.
921 ///
922 /// # Correctness
923 ///
924 /// Block commit requests should be wrapped in a timeout, so that
925 /// out-of-order and invalid requests do not hang indefinitely. See the [`crate`]
926 /// documentation for details.
927 ///
928 /// [0]: (crate::error::CommitSemanticallyVerifiedError)
929 CommitSemanticallyVerifiedBlock(SemanticallyVerifiedBlock),
930
931 /// Commit a checkpointed block to the state, skipping most but not all
932 /// contextual validation.
933 ///
934 /// This is exposed for use in checkpointing, which produces checkpoint vefified
935 /// blocks. This request can be made out-of-order; the state service will queue
936 /// it until its parent is ready.
937 ///
938 /// Returns [`Response::Committed`] with the hash of the newly committed
939 /// block, or a [`CommitCheckpointVerifiedError`][0] if the block could not be
940 /// committed to the state.
941 ///
942 /// This request cannot be cancelled once submitted; dropping the response
943 /// future will have no effect on whether it is eventually processed.
944 /// Duplicate requests will replace the older duplicate, and return an error
945 /// in its response future.
946 ///
947 /// # Note
948 ///
949 /// [`SemanticallyVerifiedBlock`], [`ContextuallyVerifiedBlock`] and
950 /// [`CheckpointVerifiedBlock`] are an internal Zebra implementation detail.
951 /// There is no difference between these blocks on the Zcash network, or in Zebra's
952 /// network or syncer implementations.
953 ///
954 /// # Consensus
955 ///
956 /// Checkpointing is allowed under the Zcash "social consensus" rules.
957 /// Zebra checkpoints both settled network upgrades, and blocks past the rollback limit.
958 /// (By the time Zebra release is tagged, its final checkpoint is typically hours or days old.)
959 ///
960 /// > A network upgrade is settled on a given network when there is a social consensus
961 /// > that it has activated with a given activation block hash. A full validator that
962 /// > potentially risks Mainnet funds or displays Mainnet transaction information to a user
963 /// > MUST do so only for a block chain that includes the activation block of the most
964 /// > recent settled network upgrade, with the corresponding activation block hash.
965 /// > ...
966 /// > A full validator MAY impose a limit on the number of blocks it will “roll back”
967 /// > when switching from one best valid block chain to another that is not a descendent.
968 /// > For `zcashd` and `zebra` this limit is 100 blocks.
969 ///
970 /// <https://zips.z.cash/protocol/protocol.pdf#blockchain>
971 ///
972 /// Note: Zebra's local rollback window
973 /// ([`MAX_BLOCK_REORG_HEIGHT`](crate::MAX_BLOCK_REORG_HEIGHT)) is now 1000 blocks, larger
974 /// than the 100 quoted from the protocol specification above.
975 ///
976 /// # Correctness
977 ///
978 /// Block commit requests should be wrapped in a timeout, so that
979 /// out-of-order and invalid requests do not hang indefinitely. See the [`crate`]
980 /// documentation for details.
981 ///
982 /// [0]: (crate::error::CommitCheckpointVerifiedError)
983 CommitCheckpointVerifiedBlock(CheckpointVerifiedBlock),
984
985 /// Computes the depth in the current best chain of the block identified by the given hash.
986 ///
987 /// Returns
988 ///
989 /// * [`Response::Depth(Some(depth))`](Response::Depth) if the block is in the best chain;
990 /// * [`Response::Depth(None)`](Response::Depth) otherwise.
991 Depth(block::Hash),
992
993 /// Returns [`Response::Tip(Option<(Height, block::Hash)>)`](Response::Tip)
994 /// with the current best chain tip.
995 Tip,
996
997 /// Computes a block locator object based on the current best chain.
998 ///
999 /// Returns [`Response::BlockLocator`] with hashes starting
1000 /// from the best chain tip, and following the chain of previous
1001 /// hashes. The first hash is the best chain tip. The last hash is
1002 /// the tip of the finalized portion of the state. Block locators
1003 /// are not continuous - some intermediate hashes might be skipped.
1004 ///
1005 /// If the state is empty, the block locator is also empty.
1006 BlockLocator,
1007
1008 /// Looks up a transaction by hash in the current best chain.
1009 ///
1010 /// Returns
1011 ///
1012 /// * [`Response::Transaction(Some(Arc<Transaction>))`](Response::Transaction) if the transaction is in the best chain;
1013 /// * [`Response::Transaction(None)`](Response::Transaction) otherwise.
1014 Transaction(transaction::Hash),
1015
1016 /// Looks up a transaction by hash in any chain.
1017 ///
1018 /// Returns
1019 ///
1020 /// * [`Response::AnyChainTransaction(Some(AnyTx))`](Response::AnyChainTransaction)
1021 /// if the transaction is in any chain;
1022 /// * [`Response::AnyChainTransaction(None)`](Response::AnyChainTransaction)
1023 /// otherwise.
1024 AnyChainTransaction(transaction::Hash),
1025
1026 /// Looks up a UTXO identified by the given [`OutPoint`](transparent::OutPoint),
1027 /// returning `None` immediately if it is unknown.
1028 ///
1029 /// Checks verified blocks in the finalized chain and the _best_ non-finalized chain.
1030 UnspentBestChainUtxo(transparent::OutPoint),
1031
1032 /// Looks up a block by hash or height in the current best chain.
1033 ///
1034 /// Returns
1035 ///
1036 /// * [`Response::Block(Some(Arc<Block>))`](Response::Block) if the block is in the best chain;
1037 /// * [`Response::Block(None)`](Response::Block) otherwise.
1038 ///
1039 /// Returns [`crate::BlockReadError`] for incomplete primary data.
1040 /// Returns `None` for incomplete secondary views.
1041 ///
1042 /// Note: the [`HashOrHeight`] can be constructed from a [`block::Hash`] or
1043 /// [`block::Height`] using `.into()`.
1044 Block(HashOrHeight),
1045
1046 /// Looks up a block by hash in any current chain or by height in the current best chain.
1047 ///
1048 /// Returns
1049 ///
1050 /// * [`Response::Block(Some(Arc<Block>))`](Response::Block) if the block hash is in any chain, or,
1051 /// if the block height is in the best chain;
1052 /// * [`Response::Block(None)`](Response::Block) otherwise.
1053 ///
1054 /// Returns [`crate::BlockReadError`] for incomplete primary data.
1055 /// Returns `None` for incomplete secondary views.
1056 ///
1057 /// Note: the [`HashOrHeight`] can be constructed from a [`block::Hash`] or
1058 /// [`block::Height`] using `.into()`.
1059 AnyChainBlock(HashOrHeight),
1060
1061 //// Same as Block, but also returns serialized block size.
1062 ////
1063 /// Returns
1064 ///
1065 /// * [`ReadResponse::BlockAndSize(Some((Arc<Block>, usize)))`](ReadResponse::BlockAndSize) if the block is in the best chain;
1066 /// * [`ReadResponse::BlockAndSize(None)`](ReadResponse::BlockAndSize) otherwise.
1067 ///
1068 /// Returns [`crate::BlockReadError`] for incomplete primary data.
1069 /// Returns `None` for incomplete secondary views.
1070 BlockAndSize(HashOrHeight),
1071
1072 /// Looks up a block header by hash or height in the current best chain.
1073 ///
1074 /// Returns
1075 ///
1076 /// [`Response::BlockHeader(block::Header)`](Response::BlockHeader).
1077 ///
1078 /// Note: the [`HashOrHeight`] can be constructed from a [`block::Hash`] or
1079 /// [`block::Height`] using `.into()`.
1080 BlockHeader(HashOrHeight),
1081
1082 /// Request a UTXO identified by the given [`OutPoint`](transparent::OutPoint),
1083 /// waiting until it becomes available if it is unknown.
1084 ///
1085 /// Checks the finalized chain, all non-finalized chains, queued unverified blocks,
1086 /// and any blocks that arrive at the state after the request future has been created.
1087 ///
1088 /// This request is purely informational, and there are no guarantees about
1089 /// whether the UTXO remains unspent or is on the best chain, or any chain.
1090 /// Its purpose is to allow asynchronous script verification or to wait until
1091 /// the UTXO arrives in the state before validating dependent transactions.
1092 ///
1093 /// Returns [`Response::Utxo`] with the UTXO, or an [`AwaitUtxoError`] if
1094 /// the state stopped responding before the UTXO arrived.
1095 ///
1096 /// # Correctness
1097 ///
1098 /// UTXO requests should be wrapped in a timeout, so that
1099 /// out-of-order and invalid requests do not hang indefinitely. See the [`crate`]
1100 /// documentation for details.
1101 ///
1102 /// Outdated requests are pruned on a regular basis.
1103 AwaitUtxo(transparent::OutPoint),
1104
1105 /// Finds the first hash that's in the peer's `known_blocks` and the local best chain.
1106 /// Returns a list of hashes that follow that intersection, from the best chain.
1107 ///
1108 /// If there is no matching hash in the best chain, starts from the genesis hash.
1109 ///
1110 /// Stops the list of hashes after:
1111 /// * adding the best tip,
1112 /// * adding the `stop` hash to the list, if it is in the best chain, or
1113 /// * adding 500 hashes to the list.
1114 ///
1115 /// Returns an empty list if the state is empty.
1116 ///
1117 /// Returns
1118 ///
1119 /// [`Response::BlockHashes(Vec<block::Hash>)`](Response::BlockHashes).
1120 /// See <https://en.bitcoin.it/wiki/Protocol_documentation#getblocks>
1121 FindBlockHashes {
1122 /// Hashes of known blocks, ordered from highest height to lowest height.
1123 known_blocks: Vec<block::Hash>,
1124 /// Optionally, the last block hash to request.
1125 stop: Option<block::Hash>,
1126 },
1127
1128 /// Finds the first hash that's in the peer's `known_blocks` and the local best chain.
1129 /// Returns a list of headers that follow that intersection, from the best chain.
1130 ///
1131 /// If there is no matching hash in the best chain, starts from the genesis header.
1132 ///
1133 /// Stops the list of headers after:
1134 /// * adding the best tip,
1135 /// * adding the header matching the `stop` hash to the list, if it is in the best chain, or
1136 /// * adding [`MAX_FIND_BLOCK_HEADERS_RESULTS`] headers to the list.
1137 ///
1138 /// Returns an empty list if the state is empty.
1139 ///
1140 /// Returns
1141 ///
1142 /// [`Response::BlockHeaders(Vec<block::Header>)`](Response::BlockHeaders).
1143 /// See <https://en.bitcoin.it/wiki/Protocol_documentation#getheaders>
1144 FindBlockHeaders {
1145 /// Hashes of known blocks, ordered from highest height to lowest height.
1146 known_blocks: Vec<block::Hash>,
1147 /// Optionally, the hash of the last header to request.
1148 stop: Option<block::Hash>,
1149 },
1150
1151 /// Contextually validates anchors and nullifiers of a transaction on the best chain
1152 ///
1153 /// Returns [`Response::ValidBestChainTipNullifiersAndAnchors`]
1154 CheckBestChainTipNullifiersAndAnchors(UnminedTx),
1155
1156 /// Calculates the median-time-past for the *next* block on the best chain.
1157 ///
1158 /// Returns [`Response::BestChainNextMedianTimePast`] when successful.
1159 BestChainNextMedianTimePast,
1160
1161 /// Looks up a block hash by height in the current best chain.
1162 ///
1163 /// Returns
1164 ///
1165 /// * [`Response::BlockHash(Some(hash))`](Response::BlockHash) if the block is in the best chain;
1166 /// * [`Response::BlockHash(None)`](Response::BlockHash) otherwise.
1167 BestChainBlockHash(block::Height),
1168
1169 /// Checks if a block is present anywhere in the state service.
1170 /// Looks up `hash` in block queues as well as the finalized chain and all non-finalized chains.
1171 ///
1172 /// Returns [`Response::KnownBlock(Some(Location))`](Response::KnownBlock) if the block is in the best state service.
1173 /// Returns [`Response::KnownBlock(None)`](Response::KnownBlock) otherwise.
1174 KnownBlock(block::Hash),
1175
1176 /// Invalidates a block in the non-finalized state with the provided hash if one is present, removing it and
1177 /// its child blocks, and rejecting it during contextual validation if it's resubmitted to the state.
1178 ///
1179 /// Returns [`Response::Invalidated`] with the hash of the invalidated block,
1180 /// or a [`InvalidateError`][0] if the block was not found, the state is still
1181 /// committing checkpointed blocks, or the request could not be processed.
1182 ///
1183 /// [0]: (crate::error::InvalidateError)
1184 InvalidateBlock(block::Hash),
1185
1186 /// Reconsiders a previously invalidated block in the non-finalized state with the provided hash if one is present.
1187 ///
1188 /// Returns [`Response::Reconsidered`] with the hash of the reconsidered block,
1189 /// or a [`ReconsiderError`][0] if the block was not previously invalidated,
1190 /// its parent chain is missing, or the state is not ready to process the request.
1191 ///
1192 /// [0]: (crate::error::ReconsiderError)
1193 ReconsiderBlock(block::Hash),
1194
1195 /// Performs contextual validation of the given block, but does not commit it to the state.
1196 ///
1197 /// Returns [`Response::ValidBlockProposal`] when successful.
1198 /// See `[ReadRequest::CheckBlockProposalValidity]` for details.
1199 CheckBlockProposalValidity(SemanticallyVerifiedBlock),
1200
1201 /// Commits a block that was validated as a block proposal, and then solved, without
1202 /// repeating its contextual validation.
1203 ///
1204 /// The block is the result of a successful [`Request::CheckBlockProposalValidity`], rebound
1205 /// to the solved block with [`ContextuallyVerifiedBlock::rebind`]. The caller must check the
1206 /// solved block's proof of work, and that it is the same as the proposal apart from its
1207 /// nonce and Equihash solution, including the authorizing data of its transactions.
1208 ///
1209 /// # Correctness
1210 ///
1211 /// The state trusts the caller: it doesn't validate the block's transactions, and it doesn't
1212 /// check that the result belongs to the block. It only compares the block with the last
1213 /// proposal to decide whether it can reuse the chain that validating that proposal built.
1214 /// Only send this request with a result that the block verifier has matched to the solved
1215 /// block.
1216 ///
1217 /// The proposal was validated on a snapshot of the state, and the block is committed later.
1218 /// That is still valid, because a block's parent hash fixes every block below it, and the
1219 /// result's contextual checks only depend on those blocks.
1220 ///
1221 /// Returns [`Response::Committed`], and is queued like
1222 /// [`Request::CommitSemanticallyVerifiedBlock`].
1223 CommitContextuallyVerifiedBlock(Box<ContextuallyVerifiedBlock>),
1224
1225 /// Starts computing early mining work on a block that is still being verified, so miners
1226 /// can build on it before its transactions are verified.
1227 ///
1228 /// The caller must have checked the block's proof of work and transaction Merkle root, and
1229 /// that its shielded data is within the block limits. The state checks the block's header
1230 /// against the best tip.
1231 ///
1232 /// Returns [`Response::MiningCandidate`] straight away. The work is published once it is
1233 /// computed. It is withdrawn when the guard is dropped, which the caller does when the block
1234 /// is committed or rejected, and after a timeout.
1235 MiningCandidate(Arc<Block>),
1236}
1237
1238impl Request {
1239 /// Returns a [`&'static str`](str) name of the variant representing this value.
1240 pub fn variant_name(&self) -> &'static str {
1241 match self {
1242 Request::CommitSemanticallyVerifiedBlock(_) => "commit_semantically_verified_block",
1243 Request::CommitContextuallyVerifiedBlock(_) => "commit_contextually_verified_block",
1244 Request::CommitCheckpointVerifiedBlock(_) => "commit_checkpoint_verified_block",
1245 Request::AwaitUtxo(_) => "await_utxo",
1246 Request::Depth(_) => "depth",
1247 Request::Tip => "tip",
1248 Request::BlockLocator => "block_locator",
1249 Request::Transaction(_) => "transaction",
1250 Request::AnyChainTransaction(_) => "any_chain_transaction",
1251 Request::UnspentBestChainUtxo { .. } => "unspent_best_chain_utxo",
1252 Request::Block(_) => "block",
1253 Request::AnyChainBlock(_) => "any_chain_block",
1254 Request::BlockAndSize(_) => "block_and_size",
1255 Request::BlockHeader(_) => "block_header",
1256 Request::FindBlockHashes { .. } => "find_block_hashes",
1257 Request::FindBlockHeaders { .. } => "find_block_headers",
1258 Request::CheckBestChainTipNullifiersAndAnchors(_) => {
1259 "best_chain_tip_nullifiers_anchors"
1260 }
1261 Request::BestChainNextMedianTimePast => "best_chain_next_median_time_past",
1262 Request::BestChainBlockHash(_) => "best_chain_block_hash",
1263 Request::KnownBlock(_) => "known_block",
1264 Request::InvalidateBlock(_) => "invalidate_block",
1265 Request::ReconsiderBlock(_) => "reconsider_block",
1266 Request::CheckBlockProposalValidity(_) => "check_block_proposal_validity",
1267 Request::MiningCandidate(_) => "mining_candidate",
1268 }
1269 }
1270
1271 /// Counts metric for StateService call
1272 pub fn count_metric(&self) {
1273 metrics::counter!(
1274 "state.requests",
1275 "service" => "state",
1276 "type" => self.variant_name()
1277 )
1278 .increment(1);
1279 }
1280}
1281
1282#[derive(Clone, Debug, PartialEq, Eq)]
1283/// A read-only query about the chain state, via the
1284/// [`ReadStateService`](crate::service::ReadStateService).
1285pub enum ReadRequest {
1286 /// Returns [`ReadResponse::UsageInfo(num_bytes: u64)`](ReadResponse::UsageInfo)
1287 /// with the current disk space usage in bytes.
1288 UsageInfo,
1289
1290 /// Returns [`ReadResponse::Tip(Option<(Height, block::Hash)>)`](ReadResponse::Tip)
1291 /// with the current best chain tip.
1292 Tip,
1293
1294 /// Returns [`ReadResponse::TipPoolValues(Option<(Height, block::Hash, ValueBalance)>)`](ReadResponse::TipPoolValues)
1295 /// with the pool values of the current best chain tip.
1296 TipPoolValues,
1297
1298 /// Looks up the block info after a block by hash or height in the current best chain.
1299 ///
1300 /// * [`ReadResponse::BlockInfo(Some(pool_values))`](ReadResponse::BlockInfo) if the block is in the best chain;
1301 /// * [`ReadResponse::BlockInfo(None)`](ReadResponse::BlockInfo) otherwise.
1302 BlockInfo(HashOrHeight),
1303
1304 /// Computes the depth in the current best chain of the block identified by the given hash.
1305 ///
1306 /// Returns
1307 ///
1308 /// * [`ReadResponse::Depth(Some(depth))`](ReadResponse::Depth) if the block is in the best chain;
1309 /// * [`ReadResponse::Depth(None)`](ReadResponse::Depth) otherwise.
1310 Depth(block::Hash),
1311
1312 /// Looks up a block by hash or height in the current best chain.
1313 ///
1314 /// Returns
1315 ///
1316 /// * [`ReadResponse::Block(Some(Arc<Block>))`](ReadResponse::Block) if the block is in the best chain;
1317 /// * [`ReadResponse::Block(None)`](ReadResponse::Block) otherwise.
1318 ///
1319 /// Returns [`crate::BlockReadError`] for incomplete primary data.
1320 /// Returns `None` for incomplete secondary views.
1321 ///
1322 /// Note: the [`HashOrHeight`] can be constructed from a [`block::Hash`] or
1323 /// [`block::Height`] using `.into()`.
1324 Block(HashOrHeight),
1325
1326 /// Looks up a block by hash in any current chain or by height in the current best chain.
1327 ///
1328 /// Returns
1329 ///
1330 /// * [`ReadResponse::Block(Some(Arc<Block>))`](ReadResponse::Block) if the block hash is in any chain, or
1331 /// if the block height is in any chain, checking the best chain first
1332 /// followed by side chains in order from most to least work.
1333 /// * [`ReadResponse::Block(None)`](ReadResponse::Block) otherwise.
1334 ///
1335 /// Returns [`crate::BlockReadError`] for incomplete primary data.
1336 /// Returns `None` for incomplete secondary views.
1337 ///
1338 /// Note: the [`HashOrHeight`] can be constructed from a [`block::Hash`] or
1339 /// [`block::Height`] using `.into()`.
1340 AnyChainBlock(HashOrHeight),
1341
1342 //// Same as Block, but also returns serialized block size.
1343 ////
1344 /// Returns
1345 ///
1346 /// * [`ReadResponse::BlockAndSize(Some((Arc<Block>, usize)))`](ReadResponse::BlockAndSize) if the block is in the best chain;
1347 /// * [`ReadResponse::BlockAndSize(None)`](ReadResponse::BlockAndSize) otherwise.
1348 ///
1349 /// Returns [`crate::BlockReadError`] for incomplete primary data.
1350 /// Returns `None` for incomplete secondary views.
1351 BlockAndSize(HashOrHeight),
1352
1353 /// Looks up a block header by hash or height in the current best chain.
1354 ///
1355 /// Returns
1356 ///
1357 /// [`Response::BlockHeader(block::Header)`](Response::BlockHeader).
1358 ///
1359 /// Note: the [`HashOrHeight`] can be constructed from a [`block::Hash`] or
1360 /// [`block::Height`] using `.into()`.
1361 BlockHeader(HashOrHeight),
1362
1363 /// Looks up the transparent outputs spent by the non-coinbase inputs of a
1364 /// block, using a block hash or height, in the current best chain.
1365 ///
1366 /// Returns
1367 ///
1368 /// * [`ReadResponse::SpentOutputs(Some(_))`](ReadResponse::SpentOutputs) with the spent
1369 /// outputs keyed by the spending [`OutPoint`](transparent::OutPoint) if the block is in
1370 /// the best chain;
1371 /// * [`ReadResponse::SpentOutputs(None)`](ReadResponse::SpentOutputs) otherwise.
1372 ///
1373 /// An outpoint whose spent output cannot be found in the best chain is omitted from the
1374 /// map, so callers must treat a missing outpoint as "prevout unknown", not an error.
1375 ///
1376 /// Used by the `getblock` RPC at verbosity 3.
1377 ///
1378 /// Returns [`crate::BlockReadError`] for incomplete primary data.
1379 /// Returns `None` for incomplete secondary views.
1380 SpentOutputs(HashOrHeight),
1381
1382 /// Looks up a transaction by hash in the current best chain.
1383 ///
1384 /// Returns
1385 ///
1386 /// * [`ReadResponse::Transaction(Some(Arc<Transaction>))`](ReadResponse::Transaction) if the transaction is in the best chain;
1387 /// * [`ReadResponse::Transaction(None)`](ReadResponse::Transaction) otherwise.
1388 Transaction(transaction::Hash),
1389
1390 /// Looks up a transaction by hash in any chain.
1391 ///
1392 /// Returns
1393 ///
1394 /// * [`ReadResponse::AnyChainTransaction(Some(AnyTx))`](ReadResponse::AnyChainTransaction)
1395 /// if the transaction is in any chain;
1396 /// * [`ReadResponse::AnyChainTransaction(None)`](ReadResponse::AnyChainTransaction)
1397 /// otherwise.
1398 AnyChainTransaction(transaction::Hash),
1399
1400 /// Looks up the transaction IDs for a block, using a block hash or height.
1401 ///
1402 /// Returns
1403 ///
1404 /// * An ordered list of transaction hashes, or
1405 /// * `None` if the block was not found.
1406 ///
1407 /// Note: Each block has at least one transaction: the coinbase transaction.
1408 ///
1409 /// Returned txids are in the order they appear in the block.
1410 TransactionIdsForBlock(HashOrHeight),
1411
1412 /// Looks up the transaction IDs for a block, using a block hash or height,
1413 /// for any chain.
1414 ///
1415 /// Returns
1416 ///
1417 /// * An ordered list of transaction hashes and a flag indicating whether
1418 /// the block is in the best chain, or
1419 /// * `None` if the block was not found.
1420 ///
1421 /// Note: Each block has at least one transaction: the coinbase transaction.
1422 ///
1423 /// Returned txids are in the order they appear in the block.
1424 AnyChainTransactionIdsForBlock(HashOrHeight),
1425
1426 /// Looks up a UTXO identified by the given [`OutPoint`](transparent::OutPoint),
1427 /// returning `None` immediately if it is unknown.
1428 ///
1429 /// Checks verified blocks in the finalized chain and the _best_ non-finalized chain.
1430 UnspentBestChainUtxo(transparent::OutPoint),
1431
1432 /// Looks up a UTXO identified by the given [`OutPoint`](transparent::OutPoint),
1433 /// returning `None` immediately if it is unknown.
1434 ///
1435 /// Checks verified blocks in the finalized chain and _all_ non-finalized chains.
1436 ///
1437 /// This request is purely informational, there is no guarantee that
1438 /// the UTXO remains unspent in the best chain.
1439 AnyChainUtxo(transparent::OutPoint),
1440
1441 /// Computes a block locator object based on the current best chain.
1442 ///
1443 /// Returns [`ReadResponse::BlockLocator`] with hashes starting
1444 /// from the best chain tip, and following the chain of previous
1445 /// hashes. The first hash is the best chain tip. The last hash is
1446 /// the tip of the finalized portion of the state. Block locators
1447 /// are not continuous - some intermediate hashes might be skipped.
1448 ///
1449 /// If the state is empty, the block locator is also empty.
1450 BlockLocator,
1451
1452 /// Finds the first hash that's in the peer's `known_blocks` and the local best chain.
1453 /// Returns a list of hashes that follow that intersection, from the best chain.
1454 ///
1455 /// If there is no matching hash in the best chain, starts from the genesis hash.
1456 ///
1457 /// Stops the list of hashes after:
1458 /// * adding the best tip,
1459 /// * adding the `stop` hash to the list, if it is in the best chain, or
1460 /// * adding [`MAX_FIND_BLOCK_HASHES_RESULTS`] hashes to the list.
1461 ///
1462 /// Returns an empty list if the state is empty.
1463 ///
1464 /// Returns
1465 ///
1466 /// [`ReadResponse::BlockHashes(Vec<block::Hash>)`](ReadResponse::BlockHashes).
1467 /// See <https://en.bitcoin.it/wiki/Protocol_documentation#getblocks>
1468 FindBlockHashes {
1469 /// Hashes of known blocks, ordered from highest height to lowest height.
1470 known_blocks: Vec<block::Hash>,
1471 /// Optionally, the last block hash to request.
1472 stop: Option<block::Hash>,
1473 },
1474
1475 /// Finds the first hash that's in the peer's `known_blocks` and the local best chain.
1476 /// Returns a list of headers that follow that intersection, from the best chain.
1477 ///
1478 /// If there is no matching hash in the best chain, starts from the genesis header.
1479 ///
1480 /// Stops the list of headers after:
1481 /// * adding the best tip,
1482 /// * adding the header matching the `stop` hash to the list, if it is in the best chain, or
1483 /// * adding [`MAX_FIND_BLOCK_HEADERS_RESULTS`] headers to the list.
1484 ///
1485 /// Returns an empty list if the state is empty.
1486 ///
1487 /// Returns
1488 ///
1489 /// [`ReadResponse::BlockHeaders(Vec<block::Header>)`](ReadResponse::BlockHeaders).
1490 /// See <https://en.bitcoin.it/wiki/Protocol_documentation#getheaders>
1491 FindBlockHeaders {
1492 /// Hashes of known blocks, ordered from highest height to lowest height.
1493 known_blocks: Vec<block::Hash>,
1494 /// Optionally, the hash of the last header to request.
1495 stop: Option<block::Hash>,
1496 },
1497
1498 /// Finds the fork point between the locator `known_blocks` and the best chain.
1499 ///
1500 /// `known_blocks` is a block locator. Returns the most recent locator entry that is
1501 /// on the best chain (the fork point), or `None` if no entry is on the best chain.
1502 /// Returns `None` if the state is empty.
1503 ///
1504 /// This is intentionally a narrow, best-chain-only query: it reports a single
1505 /// locator intersection against the best chain. It does not enumerate side-chain
1506 /// tips, branch lengths, or per-tip statuses, so it is not a general
1507 /// fork-monitoring API in the style of `getchaintips`. Callers that need to
1508 /// observe side chains should use a dedicated request rather than building on this
1509 /// one.
1510 ///
1511 /// The read state service rejects this request with an error if `known_blocks`
1512 /// is longer than [`MAX_BLOCK_LOCATOR_LENGTH`](zebra_chain::block::MAX_BLOCK_LOCATOR_LENGTH),
1513 /// so an untrusted caller cannot force an unbounded number of lookups. A locator
1514 /// built the usual way (one hash per standard block-locator height) is always
1515 /// within that bound.
1516 ///
1517 /// Returns
1518 ///
1519 /// [`ReadResponse::ForkPoint(Option<(block::Height, block::Hash)>)`](ReadResponse::ForkPoint).
1520 FindForkPoint {
1521 /// Hashes of known blocks, ordered from highest height to lowest height.
1522 known_blocks: Vec<block::Hash>,
1523 },
1524
1525 /// Looks up a Sapling note commitment tree either by a hash or height.
1526 ///
1527 /// Returns
1528 ///
1529 /// * [`ReadResponse::SaplingTree(Some(Arc<NoteCommitmentTree>))`](crate::ReadResponse::SaplingTree)
1530 /// if the corresponding block contains a Sapling note commitment tree.
1531 /// * [`ReadResponse::SaplingTree(None)`](crate::ReadResponse::SaplingTree) otherwise.
1532 SaplingTree(HashOrHeight),
1533
1534 /// Looks up an Orchard note commitment tree either by a hash or height.
1535 ///
1536 /// Returns
1537 ///
1538 /// * [`ReadResponse::OrchardTree(Some(Arc<NoteCommitmentTree>))`](crate::ReadResponse::OrchardTree)
1539 /// if the corresponding block contains a Sapling note commitment tree.
1540 /// * [`ReadResponse::OrchardTree(None)`](crate::ReadResponse::OrchardTree) otherwise.
1541 OrchardTree(HashOrHeight),
1542
1543 /// Looks up a Sapling note commitment tree by block hash in any current chain.
1544 ///
1545 /// Unlike [`SaplingTree`](Self::SaplingTree), this checks every non-finalized chain
1546 /// (and the finalized state), so it is immune to reorgs that move a block from the
1547 /// best chain onto a still-retained side chain.
1548 ///
1549 /// Only lookups by hash are supported, because the same height can have different
1550 /// treestates in different chain forks.
1551 ///
1552 /// Returns
1553 ///
1554 /// * [`ReadResponse::SaplingTree(Some(Arc<NoteCommitmentTree>))`](crate::ReadResponse::SaplingTree)
1555 /// if the corresponding block contains a Sapling note commitment tree.
1556 /// * [`ReadResponse::SaplingTree(None)`](crate::ReadResponse::SaplingTree) otherwise.
1557 AnyChainSaplingTree(block::Hash),
1558
1559 /// Looks up an Orchard note commitment tree by block hash in any current chain.
1560 ///
1561 /// Unlike [`OrchardTree`](Self::OrchardTree), this checks every non-finalized chain
1562 /// (and the finalized state), so it is immune to reorgs that move a block from the
1563 /// best chain onto a still-retained side chain.
1564 ///
1565 /// Only lookups by hash are supported, because the same height can have different
1566 /// treestates in different chain forks.
1567 ///
1568 /// Returns
1569 ///
1570 /// * [`ReadResponse::OrchardTree(Some(Arc<NoteCommitmentTree>))`](crate::ReadResponse::OrchardTree)
1571 /// if the corresponding block contains an Orchard note commitment tree.
1572 /// * [`ReadResponse::OrchardTree(None)`](crate::ReadResponse::OrchardTree) otherwise.
1573 AnyChainOrchardTree(block::Hash),
1574
1575 /// Looks up an Ironwood note commitment tree either by a hash or height.
1576 ///
1577 /// Returns
1578 ///
1579 /// * [`ReadResponse::IronwoodTree(Some(Arc<NoteCommitmentTree>))`](crate::ReadResponse::IronwoodTree)
1580 /// if the corresponding block contains an Ironwood note commitment tree.
1581 /// * [`ReadResponse::IronwoodTree(None)`](crate::ReadResponse::IronwoodTree) otherwise.
1582 IronwoodTree(HashOrHeight),
1583
1584 /// Looks up an Ironwood note commitment tree by block hash in any current chain.
1585 ///
1586 /// Unlike [`IronwoodTree`](Self::IronwoodTree), this checks every non-finalized chain
1587 /// (and the finalized state), so it is immune to reorgs that move a block from the
1588 /// best chain onto a still-retained side chain.
1589 ///
1590 /// Only lookups by hash are supported, because the same height can have different
1591 /// treestates in different chain forks.
1592 ///
1593 /// Returns
1594 ///
1595 /// * [`ReadResponse::IronwoodTree(Some(Arc<NoteCommitmentTree>))`](crate::ReadResponse::IronwoodTree)
1596 /// if the corresponding block contains an Ironwood note commitment tree.
1597 /// * [`ReadResponse::IronwoodTree(None)`](crate::ReadResponse::IronwoodTree) otherwise.
1598 AnyChainIronwoodTree(block::Hash),
1599
1600 /// Returns a list of Sapling note commitment subtrees by their indexes, starting at
1601 /// `start_index`, and returning up to `limit` subtrees.
1602 ///
1603 /// Returns
1604 ///
1605 /// * [`ReadResponse::SaplingSubtree(BTreeMap<_, NoteCommitmentSubtreeData<_>>))`](crate::ReadResponse::SaplingSubtrees)
1606 /// * An empty list if there is no subtree at `start_index`.
1607 SaplingSubtrees {
1608 /// The index of the first 2^16-leaf subtree to return.
1609 start_index: NoteCommitmentSubtreeIndex,
1610 /// The maximum number of subtree values to return.
1611 limit: Option<NoteCommitmentSubtreeIndex>,
1612 },
1613
1614 /// Returns a list of Orchard note commitment subtrees by their indexes, starting at
1615 /// `start_index`, and returning up to `limit` subtrees.
1616 ///
1617 /// Returns
1618 ///
1619 /// * [`ReadResponse::OrchardSubtree(BTreeMap<_, NoteCommitmentSubtreeData<_>>))`](crate::ReadResponse::OrchardSubtrees)
1620 /// * An empty list if there is no subtree at `start_index`.
1621 OrchardSubtrees {
1622 /// The index of the first 2^16-leaf subtree to return.
1623 start_index: NoteCommitmentSubtreeIndex,
1624 /// The maximum number of subtree values to return.
1625 limit: Option<NoteCommitmentSubtreeIndex>,
1626 },
1627
1628 /// Returns a list of Ironwood note commitment subtrees by their indexes, starting at
1629 /// `start_index`, and returning up to `limit` subtrees.
1630 ///
1631 /// Returns
1632 ///
1633 /// * [`ReadResponse::IronwoodSubtree(BTreeMap<_, NoteCommitmentSubtreeData<_>>))`](crate::ReadResponse::IronwoodSubtrees)
1634 /// * An empty list if there is no subtree at `start_index`.
1635 IronwoodSubtrees {
1636 /// The index of the first 2^16-leaf subtree to return.
1637 start_index: NoteCommitmentSubtreeIndex,
1638 /// The maximum number of subtree values to return.
1639 limit: Option<NoteCommitmentSubtreeIndex>,
1640 },
1641
1642 /// Looks up the balance of a set of transparent addresses.
1643 ///
1644 /// Returns an [`Amount`] with the total
1645 /// balance of the set of addresses.
1646 AddressBalance(HashSet<transparent::Address>),
1647
1648 /// Looks up transaction hashes that were sent or received from addresses,
1649 /// in an inclusive blockchain height range, returning at most `max_entries` of them.
1650 ///
1651 /// Returns
1652 ///
1653 /// * An ordered, unique map of transaction locations and hashes.
1654 /// * An empty map if no transactions were found for the given arguments.
1655 ///
1656 /// Returned txids are in the order they appear in blocks,
1657 /// which ensures that they are topologically sorted
1658 /// (i.e. parent txids will appear before child txids).
1659 TransactionIdsByAddresses {
1660 /// The requested addresses.
1661 addresses: HashSet<transparent::Address>,
1662
1663 /// The blocks to be queried for transactions.
1664 height_range: RangeInclusive<block::Height>,
1665
1666 /// The maximum number of transaction IDs to return, the first ones in chain order,
1667 /// or `None` for no limit. The limit bounds the finalized index scan, not just the response.
1668 max_entries: Option<usize>,
1669 },
1670
1671 /// Looks up a spending transaction id by its spent transparent input.
1672 ///
1673 /// Returns [`ReadResponse::TransactionId`] with the hash of the transaction
1674 /// that spent the output at the provided [`transparent::OutPoint`].
1675 #[cfg(feature = "indexer")]
1676 SpendingTransactionId(Spend),
1677
1678 /// Looks up utxos for the provided addresses, in the provided height range,
1679 /// returning at most `max_entries` of them.
1680 ///
1681 /// Returns a type with found utxos and transaction information.
1682 UtxosByAddresses {
1683 /// The addresses to look up utxos for.
1684 addresses: HashSet<transparent::Address>,
1685
1686 /// The blocks to be queried for utxos.
1687 height_range: RangeInclusive<block::Height>,
1688
1689 /// The maximum number of utxos to return, or `None` for no limit.
1690 ///
1691 /// The limit bounds the finalized index scan, not just the response.
1692 max_entries: Option<usize>,
1693 },
1694
1695 /// Contextually validates anchors and nullifiers of a transaction on the best chain
1696 ///
1697 /// Returns [`ReadResponse::ValidBestChainTipNullifiersAndAnchors`].
1698 CheckBestChainTipNullifiersAndAnchors(UnminedTx),
1699
1700 /// Calculates the median-time-past for the *next* block on the best chain.
1701 ///
1702 /// Returns [`ReadResponse::BestChainNextMedianTimePast`] when successful.
1703 BestChainNextMedianTimePast,
1704
1705 /// Looks up a block hash by height in the current best chain.
1706 ///
1707 /// Returns
1708 ///
1709 /// * [`ReadResponse::BlockHash(Some(hash))`](ReadResponse::BlockHash) if the block is in the best chain;
1710 /// * [`ReadResponse::BlockHash(None)`](ReadResponse::BlockHash) otherwise.
1711 BestChainBlockHash(block::Height),
1712
1713 /// Get state information from the best block chain.
1714 ///
1715 /// Returns [`ReadResponse::ChainInfo(info)`](ReadResponse::ChainInfo) where `info` is a
1716 /// [`zebra-state::GetBlockTemplateChainInfo`](zebra-state::GetBlockTemplateChainInfo)` structure containing
1717 /// best chain state information.
1718 ChainInfo,
1719
1720 /// Get the state information for mining on top of a block that is still being verified,
1721 /// if there is one whose parent is still the best tip.
1722 ///
1723 /// Returns [`ReadResponse::MiningCandidate`].
1724 MiningCandidate,
1725
1726 /// Subscribe to publications and withdrawals of early mining work.
1727 ///
1728 /// The state only computes early mining work while there is a subscription.
1729 ///
1730 /// Returns [`ReadResponse::MiningCandidateChanges`].
1731 MiningCandidateChanges,
1732
1733 /// Get the average solution rate in the best chain.
1734 ///
1735 /// Returns [`ReadResponse::SolutionRate`]
1736 SolutionRate {
1737 /// The number of blocks to calculate the average difficulty for, or `None`
1738 /// to use the averaging window at the effective (tip-clamped) height.
1739 num_blocks: Option<usize>,
1740 /// Optionally estimate the network solution rate at the time when this height was mined.
1741 /// Otherwise, estimate at the current tip height.
1742 height: Option<block::Height>,
1743 },
1744
1745 /// Performs contextual validation of the given block, but does not commit it to the state.
1746 ///
1747 /// It is the caller's responsibility to perform semantic validation.
1748 /// (The caller does not need to check proof of work for block proposals.)
1749 ///
1750 /// Returns [`ReadResponse::ValidBlockProposal`] when successful, or an error if
1751 /// the block fails contextual validation.
1752 CheckBlockProposalValidity(SemanticallyVerifiedBlock),
1753
1754 /// Returns [`ReadResponse::TipBlockSize(usize)`](ReadResponse::TipBlockSize)
1755 /// with the current best chain tip block size in bytes.
1756 TipBlockSize,
1757
1758 /// Checks the height and the contextual difficulty and time of a header that is a direct child
1759 /// of the committed best tip.
1760 ///
1761 /// Returns [`ReadResponse::ValidBestTipHeader`] or an error, without caching a verdict.
1762 /// Callers must independently check proof of work and bound compact block resources.
1763 CheckBestTipHeader {
1764 /// The candidate header.
1765 header: Arc<block::Header>,
1766 /// The height from the candidate's coinbase transaction.
1767 height: block::Height,
1768 },
1769
1770 /// Checks the history and authorizing data commitments of an NU5 or later block that is a
1771 /// direct child of the committed best tip.
1772 ///
1773 /// Callers must first bound the block and check its transaction Merkle root.
1774 /// Returns [`ReadResponse::ValidBestTipBlockCommitments`] or an error, without caching a
1775 /// verdict. Success does not imply the block or its transactions are valid.
1776 CheckBestTipBlockCommitments(Arc<Block>),
1777
1778 /// Returns [`ReadResponse::NonFinalizedBlocksListener`] with a channel receiver
1779 /// allowing the caller to listen for new blocks in the non-finalized state.
1780 NonFinalizedBlocksListener {
1781 /// The hashes of the chain tips the caller already has.
1782 ///
1783 /// Only blocks that come after these tips are streamed: walking each
1784 /// non-finalized chain from its tip downwards, blocks are sent until a
1785 /// hash in this set is reached. If empty, every block currently in the
1786 /// non-finalized state is sent.
1787 known_chain_tips: HashSet<block::Hash>,
1788 },
1789
1790 /// Returns `true` if the transparent output is spent in the best chain,
1791 /// or `false` if it is unspent.
1792 IsTransparentOutputSpent(transparent::OutPoint),
1793}
1794
1795impl ReadRequest {
1796 /// Returns a [`&'static str`](str) name of the variant representing this value.
1797 pub fn variant_name(&self) -> &'static str {
1798 match self {
1799 ReadRequest::UsageInfo => "usage_info",
1800 ReadRequest::Tip => "tip",
1801 ReadRequest::TipPoolValues => "tip_pool_values",
1802 ReadRequest::BlockInfo(_) => "block_info",
1803 ReadRequest::Depth(_) => "depth",
1804 ReadRequest::Block(_) => "block",
1805 ReadRequest::AnyChainBlock(_) => "any_chain_block",
1806 ReadRequest::BlockAndSize(_) => "block_and_size",
1807 ReadRequest::SpentOutputs(_) => "spent_outputs",
1808 ReadRequest::BlockHeader(_) => "block_header",
1809 ReadRequest::Transaction(_) => "transaction",
1810 ReadRequest::AnyChainTransaction(_) => "any_chain_transaction",
1811 ReadRequest::TransactionIdsForBlock(_) => "transaction_ids_for_block",
1812 ReadRequest::AnyChainTransactionIdsForBlock(_) => "any_chain_transaction_ids_for_block",
1813 ReadRequest::UnspentBestChainUtxo { .. } => "unspent_best_chain_utxo",
1814 ReadRequest::AnyChainUtxo { .. } => "any_chain_utxo",
1815 ReadRequest::BlockLocator => "block_locator",
1816 ReadRequest::FindBlockHashes { .. } => "find_block_hashes",
1817 ReadRequest::FindBlockHeaders { .. } => "find_block_headers",
1818 ReadRequest::FindForkPoint { .. } => "find_fork_point",
1819 ReadRequest::SaplingTree { .. } => "sapling_tree",
1820 ReadRequest::OrchardTree { .. } => "orchard_tree",
1821 ReadRequest::AnyChainSaplingTree { .. } => "any_chain_sapling_tree",
1822 ReadRequest::AnyChainOrchardTree { .. } => "any_chain_orchard_tree",
1823 ReadRequest::IronwoodTree { .. } => "ironwood_tree",
1824 ReadRequest::AnyChainIronwoodTree { .. } => "any_chain_ironwood_tree",
1825 ReadRequest::SaplingSubtrees { .. } => "sapling_subtrees",
1826 ReadRequest::OrchardSubtrees { .. } => "orchard_subtrees",
1827 ReadRequest::IronwoodSubtrees { .. } => "ironwood_subtrees",
1828 ReadRequest::AddressBalance { .. } => "address_balance",
1829 ReadRequest::TransactionIdsByAddresses { .. } => "transaction_ids_by_addresses",
1830 ReadRequest::UtxosByAddresses { .. } => "utxos_by_addresses",
1831 ReadRequest::CheckBestChainTipNullifiersAndAnchors(_) => {
1832 "best_chain_tip_nullifiers_anchors"
1833 }
1834 ReadRequest::BestChainNextMedianTimePast => "best_chain_next_median_time_past",
1835 ReadRequest::BestChainBlockHash(_) => "best_chain_block_hash",
1836 #[cfg(feature = "indexer")]
1837 ReadRequest::SpendingTransactionId(_) => "spending_transaction_id",
1838 ReadRequest::ChainInfo => "chain_info",
1839 ReadRequest::MiningCandidate => "mining_candidate",
1840 ReadRequest::MiningCandidateChanges => "mining_candidate_changes",
1841 ReadRequest::SolutionRate { .. } => "solution_rate",
1842 ReadRequest::CheckBlockProposalValidity(_) => "check_block_proposal_validity",
1843 ReadRequest::TipBlockSize => "tip_block_size",
1844 ReadRequest::CheckBestTipHeader { .. } => "check_best_tip_header",
1845 ReadRequest::CheckBestTipBlockCommitments(_) => "check_best_tip_block_commitments",
1846 ReadRequest::NonFinalizedBlocksListener { .. } => "non_finalized_blocks_listener",
1847 ReadRequest::IsTransparentOutputSpent(_) => "is_transparent_output_spent",
1848 }
1849 }
1850
1851 /// Counts metric for ReadStateService call
1852 pub fn count_metric(&self) {
1853 metrics::counter!(
1854 "state.requests",
1855 "service" => "read_state",
1856 "type" => self.variant_name()
1857 )
1858 .increment(1);
1859 }
1860}
1861
1862/// Conversion from read-write [`Request`]s to read-only [`ReadRequest`]s.
1863///
1864/// Used to dispatch read requests concurrently from the [`StateService`](crate::service::StateService).
1865impl TryFrom<Request> for ReadRequest {
1866 type Error = &'static str;
1867
1868 fn try_from(request: Request) -> Result<ReadRequest, Self::Error> {
1869 match request {
1870 Request::Tip => Ok(ReadRequest::Tip),
1871 Request::Depth(hash) => Ok(ReadRequest::Depth(hash)),
1872 Request::BestChainNextMedianTimePast => Ok(ReadRequest::BestChainNextMedianTimePast),
1873 Request::BestChainBlockHash(hash) => Ok(ReadRequest::BestChainBlockHash(hash)),
1874
1875 Request::Block(hash_or_height) => Ok(ReadRequest::Block(hash_or_height)),
1876 Request::AnyChainBlock(hash_or_height) => {
1877 Ok(ReadRequest::AnyChainBlock(hash_or_height))
1878 }
1879 Request::BlockAndSize(hash_or_height) => Ok(ReadRequest::BlockAndSize(hash_or_height)),
1880 Request::BlockHeader(hash_or_height) => Ok(ReadRequest::BlockHeader(hash_or_height)),
1881 Request::Transaction(tx_hash) => Ok(ReadRequest::Transaction(tx_hash)),
1882 Request::AnyChainTransaction(tx_hash) => Ok(ReadRequest::AnyChainTransaction(tx_hash)),
1883 Request::UnspentBestChainUtxo(outpoint) => {
1884 Ok(ReadRequest::UnspentBestChainUtxo(outpoint))
1885 }
1886
1887 Request::BlockLocator => Ok(ReadRequest::BlockLocator),
1888 Request::FindBlockHashes { known_blocks, stop } => {
1889 Ok(ReadRequest::FindBlockHashes { known_blocks, stop })
1890 }
1891 Request::FindBlockHeaders { known_blocks, stop } => {
1892 Ok(ReadRequest::FindBlockHeaders { known_blocks, stop })
1893 }
1894
1895 Request::CheckBestChainTipNullifiersAndAnchors(tx) => {
1896 Ok(ReadRequest::CheckBestChainTipNullifiersAndAnchors(tx))
1897 }
1898
1899 Request::CommitSemanticallyVerifiedBlock(_)
1900 | Request::CommitContextuallyVerifiedBlock(_)
1901 | Request::CommitCheckpointVerifiedBlock(_)
1902 | Request::InvalidateBlock(_)
1903 | Request::ReconsiderBlock(_)
1904 | Request::MiningCandidate(_) => Err("ReadService does not write blocks"),
1905
1906 Request::AwaitUtxo(_) => Err("ReadService does not track pending UTXOs. \
1907 Manually convert the request to ReadRequest::AnyChainUtxo, \
1908 and handle pending UTXOs"),
1909
1910 Request::KnownBlock(_) => Err("ReadService does not track queued blocks"),
1911
1912 Request::CheckBlockProposalValidity(semantically_verified) => Ok(
1913 ReadRequest::CheckBlockProposalValidity(semantically_verified),
1914 ),
1915 }
1916 }
1917}
1918
1919#[derive(Debug)]
1920/// A convenience type for spawning blocking tokio tasks with
1921/// a timer in the scope of a provided span.
1922pub struct TimedSpan {
1923 timer: CodeTimer,
1924 span: tracing::Span,
1925}
1926
1927impl TimedSpan {
1928 /// Creates a new [`TimedSpan`].
1929 pub fn new(timer: CodeTimer, span: tracing::Span) -> Self {
1930 Self { timer, span }
1931 }
1932
1933 /// Spawns a blocking tokio task in scope of the `span` field.
1934 #[track_caller]
1935 pub fn spawn_blocking<T: Send + 'static>(
1936 mut self,
1937 f: impl FnOnce() -> Result<T, BoxError> + Send + 'static,
1938 ) -> Pin<Box<dyn futures::Future<Output = Result<T, BoxError>> + Send>> {
1939 let location = std::panic::Location::caller();
1940 // # Performance
1941 //
1942 // Allow other async tasks to make progress while concurrently reading blocks from disk.
1943
1944 // The work is done in the future.
1945 tokio::task::spawn_blocking(move || {
1946 self.span.in_scope(move || {
1947 let result = f();
1948 self.timer
1949 .finish_inner(Some(location.file()), Some(location.line()), "");
1950 result
1951 })
1952 })
1953 .wait_for_panics()
1954 }
1955}