zebra_state/request.rs
1//! State [`tower::Service`] request types.
2
3use std::{
4 collections::{HashMap, HashSet},
5 ops::{Add, Deref, DerefMut, RangeInclusive},
6 sync::Arc,
7};
8
9use zebra_chain::{
10 amount::{Amount, NegativeAllowed, NonNegative},
11 block::{self, Block, HeightDiff},
12 history_tree::HistoryTree,
13 orchard,
14 parallel::tree::NoteCommitmentTrees,
15 sapling,
16 serialization::SerializationError,
17 sprout,
18 subtree::{NoteCommitmentSubtree, NoteCommitmentSubtreeIndex},
19 transaction::{self, UnminedTx},
20 transparent::{self, utxos_from_ordered_utxos},
21 value_balance::{ValueBalance, ValueBalanceError},
22};
23
24/// Allow *only* these unused imports, so that rustdoc link resolution
25/// will work with inline links.
26#[allow(unused_imports)]
27use crate::{
28 constants::{MAX_FIND_BLOCK_HASHES_RESULTS, MAX_FIND_BLOCK_HEADERS_RESULTS},
29 ReadResponse, Response,
30};
31
32/// Identify a spend by a transparent outpoint or revealed nullifier.
33///
34/// This enum implements `From` for [`transparent::OutPoint`], [`sprout::Nullifier`],
35/// [`sapling::Nullifier`], and [`orchard::Nullifier`].
36#[derive(Copy, Clone, Debug, PartialEq, Eq)]
37#[cfg(feature = "indexer")]
38pub enum Spend {
39 /// A spend identified by a [`transparent::OutPoint`].
40 OutPoint(transparent::OutPoint),
41 /// A spend identified by a [`sprout::Nullifier`].
42 Sprout(sprout::Nullifier),
43 /// A spend identified by a [`sapling::Nullifier`].
44 Sapling(sapling::Nullifier),
45 /// A spend identified by a [`orchard::Nullifier`].
46 Orchard(orchard::Nullifier),
47}
48
49#[cfg(feature = "indexer")]
50impl From<transparent::OutPoint> for Spend {
51 fn from(outpoint: transparent::OutPoint) -> Self {
52 Self::OutPoint(outpoint)
53 }
54}
55
56#[cfg(feature = "indexer")]
57impl From<sprout::Nullifier> for Spend {
58 fn from(sprout_nullifier: sprout::Nullifier) -> Self {
59 Self::Sprout(sprout_nullifier)
60 }
61}
62
63#[cfg(feature = "indexer")]
64impl From<sapling::Nullifier> for Spend {
65 fn from(sapling_nullifier: sapling::Nullifier) -> Self {
66 Self::Sapling(sapling_nullifier)
67 }
68}
69
70#[cfg(feature = "indexer")]
71impl From<orchard::Nullifier> for Spend {
72 fn from(orchard_nullifier: orchard::Nullifier) -> Self {
73 Self::Orchard(orchard_nullifier)
74 }
75}
76
77/// Identify a block by hash or height.
78///
79/// This enum implements `From` for [`block::Hash`] and [`block::Height`],
80/// so it can be created using `hash.into()` or `height.into()`.
81#[derive(Copy, Clone, Debug, PartialEq, Eq)]
82pub enum HashOrHeight {
83 /// A block identified by hash.
84 Hash(block::Hash),
85 /// A block identified by height.
86 Height(block::Height),
87}
88
89impl HashOrHeight {
90 /// Unwrap the inner height or attempt to retrieve the height for a given
91 /// hash if one exists.
92 pub fn height_or_else<F>(self, op: F) -> Option<block::Height>
93 where
94 F: FnOnce(block::Hash) -> Option<block::Height>,
95 {
96 match self {
97 HashOrHeight::Hash(hash) => op(hash),
98 HashOrHeight::Height(height) => Some(height),
99 }
100 }
101
102 /// Unwrap the inner hash or attempt to retrieve the hash for a given
103 /// height if one exists.
104 ///
105 /// # Consensus
106 ///
107 /// In the non-finalized state, a height can have multiple valid hashes.
108 /// We typically use the hash that is currently on the best chain.
109 pub fn hash_or_else<F>(self, op: F) -> Option<block::Hash>
110 where
111 F: FnOnce(block::Height) -> Option<block::Hash>,
112 {
113 match self {
114 HashOrHeight::Hash(hash) => Some(hash),
115 HashOrHeight::Height(height) => op(height),
116 }
117 }
118
119 /// Returns the hash if this is a [`HashOrHeight::Hash`].
120 pub fn hash(&self) -> Option<block::Hash> {
121 if let HashOrHeight::Hash(hash) = self {
122 Some(*hash)
123 } else {
124 None
125 }
126 }
127
128 /// Returns the height if this is a [`HashOrHeight::Height`].
129 pub fn height(&self) -> Option<block::Height> {
130 if let HashOrHeight::Height(height) = self {
131 Some(*height)
132 } else {
133 None
134 }
135 }
136
137 /// Constructs a new [`HashOrHeight`] from a string containing a hash or a positive or negative
138 /// height.
139 ///
140 /// When the provided `hash_or_height` contains a negative height, the `tip_height` parameter
141 /// needs to be `Some` since height `-1` points to the tip.
142 pub fn new(hash_or_height: &str, tip_height: Option<block::Height>) -> Result<Self, String> {
143 hash_or_height
144 .parse()
145 .map(Self::Hash)
146 .or_else(|_| hash_or_height.parse().map(Self::Height))
147 .or_else(|_| {
148 hash_or_height
149 .parse()
150 .map_err(|_| "could not parse negative height")
151 .and_then(|d: HeightDiff| {
152 if d.is_negative() {
153 {
154 Ok(HashOrHeight::Height(
155 tip_height
156 .ok_or("missing tip height")?
157 .add(d)
158 .ok_or("underflow when adding negative height to tip")?
159 .next()
160 .map_err(|_| "height -1 needs to point to tip")?,
161 ))
162 }
163 } else {
164 Err("height was not negative")
165 }
166 })
167 })
168 .map_err(|_| {
169 "parse error: could not convert the input string to a hash or height".to_string()
170 })
171 }
172}
173
174impl std::fmt::Display for HashOrHeight {
175 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176 match self {
177 HashOrHeight::Hash(hash) => write!(f, "{hash}"),
178 HashOrHeight::Height(height) => write!(f, "{}", height.0),
179 }
180 }
181}
182
183impl From<block::Hash> for HashOrHeight {
184 fn from(hash: block::Hash) -> Self {
185 Self::Hash(hash)
186 }
187}
188
189impl From<block::Height> for HashOrHeight {
190 fn from(height: block::Height) -> Self {
191 Self::Height(height)
192 }
193}
194
195impl From<(block::Height, block::Hash)> for HashOrHeight {
196 fn from((_height, hash): (block::Height, block::Hash)) -> Self {
197 // Hash is more specific than height for the non-finalized state
198 hash.into()
199 }
200}
201
202impl From<(block::Hash, block::Height)> for HashOrHeight {
203 fn from((hash, _height): (block::Hash, block::Height)) -> Self {
204 hash.into()
205 }
206}
207
208impl std::str::FromStr for HashOrHeight {
209 type Err = SerializationError;
210
211 fn from_str(s: &str) -> Result<Self, Self::Err> {
212 s.parse()
213 .map(Self::Hash)
214 .or_else(|_| s.parse().map(Self::Height))
215 .map_err(|_| {
216 SerializationError::Parse("could not convert the input string to a hash or height")
217 })
218 }
219}
220
221/// A block which has undergone semantic validation and has been prepared for
222/// contextual validation.
223///
224/// It is the constructor's responsibility to perform semantic validation and to
225/// ensure that all fields are consistent.
226///
227/// This structure contains data from contextual validation, which is computed in
228/// the *service caller*'s task, not inside the service call itself. This allows
229/// moving work out of the single-threaded state service.
230#[derive(Clone, Debug, PartialEq, Eq)]
231pub struct SemanticallyVerifiedBlock {
232 /// The block to commit to the state.
233 pub block: Arc<Block>,
234 /// The hash of the block.
235 pub hash: block::Hash,
236 /// The height of the block.
237 pub height: block::Height,
238 /// New transparent outputs created in this block, indexed by
239 /// [`OutPoint`](transparent::OutPoint).
240 ///
241 /// Each output is tagged with its transaction index in the block.
242 /// (The outputs of earlier transactions in a block can be spent by later
243 /// transactions.)
244 ///
245 /// Note: although these transparent outputs are newly created, they may not
246 /// be unspent, since a later transaction in a block can spend outputs of an
247 /// earlier transaction.
248 ///
249 /// This field can also contain unrelated outputs, which are ignored.
250 pub new_outputs: HashMap<transparent::OutPoint, transparent::OrderedUtxo>,
251 /// A precomputed list of the hashes of the transactions in this block,
252 /// in the same order as `block.transactions`.
253 pub transaction_hashes: Arc<[transaction::Hash]>,
254 /// This block's contribution to the deferred pool.
255 pub deferred_balance: Option<Amount<NonNegative>>,
256}
257
258/// A block ready to be committed directly to the finalized state with
259/// a small number of checks if compared with a `ContextuallyVerifiedBlock`.
260///
261/// This is exposed for use in checkpointing.
262///
263/// Note: The difference between a `CheckpointVerifiedBlock` and a `ContextuallyVerifiedBlock` is
264/// that the `CheckpointVerifier` doesn't bind the transaction authorizing data to the
265/// `ChainHistoryBlockTxAuthCommitmentHash`, but the `NonFinalizedState` and `FinalizedState` do.
266#[derive(Clone, Debug, PartialEq, Eq)]
267pub struct CheckpointVerifiedBlock(pub(crate) SemanticallyVerifiedBlock);
268
269// Some fields are pub(crate), so we can add whatever db-format-dependent
270// precomputation we want here without leaking internal details.
271
272/// A contextually verified block, ready to be committed directly to the finalized state with no
273/// checks, if it becomes the root of the best non-finalized chain.
274///
275/// Used by the state service and non-finalized `Chain`.
276///
277/// Note: The difference between a `CheckpointVerifiedBlock` and a `ContextuallyVerifiedBlock` is
278/// that the `CheckpointVerifier` doesn't bind the transaction authorizing data to the
279/// `ChainHistoryBlockTxAuthCommitmentHash`, but the `NonFinalizedState` and `FinalizedState` do.
280#[derive(Clone, Debug, PartialEq, Eq)]
281pub struct ContextuallyVerifiedBlock {
282 /// The block to commit to the state.
283 pub(crate) block: Arc<Block>,
284
285 /// The hash of the block.
286 pub(crate) hash: block::Hash,
287
288 /// The height of the block.
289 pub(crate) height: block::Height,
290
291 /// New transparent outputs created in this block, indexed by
292 /// [`OutPoint`](transparent::OutPoint).
293 ///
294 /// Note: although these transparent outputs are newly created, they may not
295 /// be unspent, since a later transaction in a block can spend outputs of an
296 /// earlier transaction.
297 ///
298 /// This field can also contain unrelated outputs, which are ignored.
299 pub(crate) new_outputs: HashMap<transparent::OutPoint, transparent::OrderedUtxo>,
300
301 /// The outputs spent by this block, indexed by the [`transparent::Input`]'s
302 /// [`OutPoint`](transparent::OutPoint).
303 ///
304 /// Note: these inputs can come from earlier transactions in this block,
305 /// or earlier blocks in the chain.
306 ///
307 /// This field can also contain unrelated outputs, which are ignored.
308 pub(crate) spent_outputs: HashMap<transparent::OutPoint, transparent::OrderedUtxo>,
309
310 /// A precomputed list of the hashes of the transactions in this block,
311 /// in the same order as `block.transactions`.
312 pub(crate) transaction_hashes: Arc<[transaction::Hash]>,
313
314 /// The sum of the chain value pool changes of all transactions in this block.
315 pub(crate) chain_value_pool_change: ValueBalance<NegativeAllowed>,
316}
317
318/// Wraps note commitment trees and the history tree together.
319///
320/// The default instance represents the treestate that corresponds to the genesis block.
321#[derive(Clone, Debug, Default, Eq, PartialEq)]
322pub struct Treestate {
323 /// Note commitment trees.
324 pub note_commitment_trees: NoteCommitmentTrees,
325 /// History tree.
326 pub history_tree: Arc<HistoryTree>,
327}
328
329impl Treestate {
330 pub fn new(
331 sprout: Arc<sprout::tree::NoteCommitmentTree>,
332 sapling: Arc<sapling::tree::NoteCommitmentTree>,
333 orchard: Arc<orchard::tree::NoteCommitmentTree>,
334 sapling_subtree: Option<NoteCommitmentSubtree<sapling::tree::Node>>,
335 orchard_subtree: Option<NoteCommitmentSubtree<orchard::tree::Node>>,
336 history_tree: Arc<HistoryTree>,
337 ) -> Self {
338 Self {
339 note_commitment_trees: NoteCommitmentTrees {
340 sprout,
341 sapling,
342 sapling_subtree,
343 orchard,
344 orchard_subtree,
345 },
346 history_tree,
347 }
348 }
349}
350
351/// Contains a block ready to be committed.
352///
353/// Zebra's state service passes this `enum` over to the finalized state
354/// when committing a block.
355pub enum FinalizableBlock {
356 Checkpoint {
357 checkpoint_verified: CheckpointVerifiedBlock,
358 },
359 Contextual {
360 contextually_verified: ContextuallyVerifiedBlock,
361 treestate: Treestate,
362 },
363}
364
365/// Contains a block with all its associated data that the finalized state can commit to its
366/// database.
367///
368/// Note that it's the constructor's responsibility to ensure that all data is valid and verified.
369pub struct FinalizedBlock {
370 /// The block to commit to the state.
371 pub(super) block: Arc<Block>,
372 /// The hash of the block.
373 pub(super) hash: block::Hash,
374 /// The height of the block.
375 pub(super) height: block::Height,
376 /// New transparent outputs created in this block, indexed by
377 /// [`OutPoint`](transparent::OutPoint).
378 pub(super) new_outputs: HashMap<transparent::OutPoint, transparent::OrderedUtxo>,
379 /// A precomputed list of the hashes of the transactions in this block, in the same order as
380 /// `block.transactions`.
381 pub(super) transaction_hashes: Arc<[transaction::Hash]>,
382 /// The tresstate associated with the block.
383 pub(super) treestate: Treestate,
384 /// This block's contribution to the deferred pool.
385 pub(super) deferred_balance: Option<Amount<NonNegative>>,
386}
387
388impl FinalizedBlock {
389 /// Constructs [`FinalizedBlock`] from [`CheckpointVerifiedBlock`] and its [`Treestate`].
390 pub fn from_checkpoint_verified(block: CheckpointVerifiedBlock, treestate: Treestate) -> Self {
391 Self::from_semantically_verified(SemanticallyVerifiedBlock::from(block), treestate)
392 }
393
394 /// Constructs [`FinalizedBlock`] from [`ContextuallyVerifiedBlock`] and its [`Treestate`].
395 pub fn from_contextually_verified(
396 block: ContextuallyVerifiedBlock,
397 treestate: Treestate,
398 ) -> Self {
399 Self::from_semantically_verified(SemanticallyVerifiedBlock::from(block), treestate)
400 }
401
402 /// Constructs [`FinalizedBlock`] from [`SemanticallyVerifiedBlock`] and its [`Treestate`].
403 fn from_semantically_verified(block: SemanticallyVerifiedBlock, treestate: Treestate) -> Self {
404 Self {
405 block: block.block,
406 hash: block.hash,
407 height: block.height,
408 new_outputs: block.new_outputs,
409 transaction_hashes: block.transaction_hashes,
410 treestate,
411 deferred_balance: block.deferred_balance,
412 }
413 }
414}
415
416impl FinalizableBlock {
417 /// Create a new [`FinalizableBlock`] given a [`ContextuallyVerifiedBlock`].
418 pub fn new(contextually_verified: ContextuallyVerifiedBlock, treestate: Treestate) -> Self {
419 Self::Contextual {
420 contextually_verified,
421 treestate,
422 }
423 }
424
425 #[cfg(test)]
426 /// Extract a [`Block`] from a [`FinalizableBlock`] variant.
427 pub fn inner_block(&self) -> Arc<Block> {
428 match self {
429 FinalizableBlock::Checkpoint {
430 checkpoint_verified,
431 } => checkpoint_verified.block.clone(),
432 FinalizableBlock::Contextual {
433 contextually_verified,
434 ..
435 } => contextually_verified.block.clone(),
436 }
437 }
438}
439
440impl From<CheckpointVerifiedBlock> for FinalizableBlock {
441 fn from(checkpoint_verified: CheckpointVerifiedBlock) -> Self {
442 Self::Checkpoint {
443 checkpoint_verified,
444 }
445 }
446}
447
448impl From<Arc<Block>> for FinalizableBlock {
449 fn from(block: Arc<Block>) -> Self {
450 Self::from(CheckpointVerifiedBlock::from(block))
451 }
452}
453
454impl From<&SemanticallyVerifiedBlock> for SemanticallyVerifiedBlock {
455 fn from(semantically_verified: &SemanticallyVerifiedBlock) -> Self {
456 semantically_verified.clone()
457 }
458}
459
460// Doing precomputation in these impls means that it will be done in
461// the *service caller*'s task, not inside the service call itself.
462// This allows moving work out of the single-threaded state service.
463
464impl ContextuallyVerifiedBlock {
465 /// Create a block that's ready for non-finalized `Chain` contextual validation,
466 /// using a [`SemanticallyVerifiedBlock`] and the UTXOs it spends.
467 ///
468 /// When combined, `semantically_verified.new_outputs` and `spent_utxos` must contain
469 /// the [`Utxo`](transparent::Utxo)s spent by every transparent input in this block,
470 /// including UTXOs created by earlier transactions in this block.
471 ///
472 /// Note: a [`ContextuallyVerifiedBlock`] isn't actually contextually valid until
473 /// [`Chain::push()`](crate::service::non_finalized_state::Chain::push) returns success.
474 pub fn with_block_and_spent_utxos(
475 semantically_verified: SemanticallyVerifiedBlock,
476 mut spent_outputs: HashMap<transparent::OutPoint, transparent::OrderedUtxo>,
477 ) -> Result<Self, ValueBalanceError> {
478 let SemanticallyVerifiedBlock {
479 block,
480 hash,
481 height,
482 new_outputs,
483 transaction_hashes,
484 deferred_balance,
485 } = semantically_verified;
486
487 // This is redundant for the non-finalized state,
488 // but useful to make some tests pass more easily.
489 //
490 // TODO: fix the tests, and stop adding unrelated outputs.
491 spent_outputs.extend(new_outputs.clone());
492
493 Ok(Self {
494 block: block.clone(),
495 hash,
496 height,
497 new_outputs,
498 spent_outputs: spent_outputs.clone(),
499 transaction_hashes,
500 chain_value_pool_change: block.chain_value_pool_change(
501 &utxos_from_ordered_utxos(spent_outputs),
502 deferred_balance,
503 )?,
504 })
505 }
506}
507
508impl CheckpointVerifiedBlock {
509 /// Creates a [`CheckpointVerifiedBlock`] from [`Block`] with optional deferred balance and
510 /// optional pre-computed hash.
511 pub fn new(
512 block: Arc<Block>,
513 hash: Option<block::Hash>,
514 deferred_balance: Option<Amount<NonNegative>>,
515 ) -> Self {
516 let mut block = Self::with_hash(block.clone(), hash.unwrap_or(block.hash()));
517 block.deferred_balance = deferred_balance;
518 block
519 }
520 /// Creates a block that's ready to be committed to the finalized state,
521 /// using a precalculated [`block::Hash`].
522 ///
523 /// Note: a [`CheckpointVerifiedBlock`] isn't actually finalized
524 /// until [`Request::CommitCheckpointVerifiedBlock`] returns success.
525 pub fn with_hash(block: Arc<Block>, hash: block::Hash) -> Self {
526 Self(SemanticallyVerifiedBlock::with_hash(block, hash))
527 }
528}
529
530impl SemanticallyVerifiedBlock {
531 /// Creates [`SemanticallyVerifiedBlock`] from [`Block`] and [`block::Hash`].
532 pub fn with_hash(block: Arc<Block>, hash: block::Hash) -> Self {
533 let height = block
534 .coinbase_height()
535 .expect("semantically verified block should have a coinbase height");
536 let transaction_hashes: Arc<[_]> = block.transactions.iter().map(|tx| tx.hash()).collect();
537 let new_outputs = transparent::new_ordered_outputs(&block, &transaction_hashes);
538
539 Self {
540 block,
541 hash,
542 height,
543 new_outputs,
544 transaction_hashes,
545 deferred_balance: None,
546 }
547 }
548
549 /// Sets the deferred balance in the block.
550 pub fn with_deferred_balance(mut self, deferred_balance: Option<Amount<NonNegative>>) -> Self {
551 self.deferred_balance = deferred_balance;
552 self
553 }
554}
555
556impl From<Arc<Block>> for CheckpointVerifiedBlock {
557 fn from(block: Arc<Block>) -> Self {
558 CheckpointVerifiedBlock(SemanticallyVerifiedBlock::from(block))
559 }
560}
561
562impl From<Arc<Block>> for SemanticallyVerifiedBlock {
563 fn from(block: Arc<Block>) -> Self {
564 let hash = block.hash();
565 let height = block
566 .coinbase_height()
567 .expect("semantically verified block should have a coinbase height");
568 let transaction_hashes: Arc<[_]> = block.transactions.iter().map(|tx| tx.hash()).collect();
569 let new_outputs = transparent::new_ordered_outputs(&block, &transaction_hashes);
570
571 Self {
572 block,
573 hash,
574 height,
575 new_outputs,
576 transaction_hashes,
577 deferred_balance: None,
578 }
579 }
580}
581
582impl From<ContextuallyVerifiedBlock> for SemanticallyVerifiedBlock {
583 fn from(valid: ContextuallyVerifiedBlock) -> Self {
584 Self {
585 block: valid.block,
586 hash: valid.hash,
587 height: valid.height,
588 new_outputs: valid.new_outputs,
589 transaction_hashes: valid.transaction_hashes,
590 deferred_balance: Some(
591 valid
592 .chain_value_pool_change
593 .deferred_amount()
594 .constrain::<NonNegative>()
595 .expect("deferred balance in a block must me non-negative"),
596 ),
597 }
598 }
599}
600
601impl From<FinalizedBlock> for SemanticallyVerifiedBlock {
602 fn from(finalized: FinalizedBlock) -> Self {
603 Self {
604 block: finalized.block,
605 hash: finalized.hash,
606 height: finalized.height,
607 new_outputs: finalized.new_outputs,
608 transaction_hashes: finalized.transaction_hashes,
609 deferred_balance: finalized.deferred_balance,
610 }
611 }
612}
613
614impl From<CheckpointVerifiedBlock> for SemanticallyVerifiedBlock {
615 fn from(checkpoint_verified: CheckpointVerifiedBlock) -> Self {
616 checkpoint_verified.0
617 }
618}
619
620impl Deref for CheckpointVerifiedBlock {
621 type Target = SemanticallyVerifiedBlock;
622
623 fn deref(&self) -> &Self::Target {
624 &self.0
625 }
626}
627impl DerefMut for CheckpointVerifiedBlock {
628 fn deref_mut(&mut self) -> &mut Self::Target {
629 &mut self.0
630 }
631}
632
633#[derive(Clone, Debug, PartialEq, Eq)]
634/// A query about or modification to the chain state, via the
635/// [`StateService`](crate::service::StateService).
636pub enum Request {
637 /// Performs contextual validation of the given semantically verified block,
638 /// committing it to the state if successful.
639 ///
640 /// This request can be made out-of-order; the state service will queue it
641 /// until its parent is ready.
642 ///
643 /// Returns [`Response::Committed`] with the hash of the block when it is
644 /// committed to the state, or an error if the block fails contextual
645 /// validation or has already been committed to the state.
646 ///
647 /// This request cannot be cancelled once submitted; dropping the response
648 /// future will have no effect on whether it is eventually processed. A
649 /// request to commit a block which has been queued internally but not yet
650 /// committed will fail the older request and replace it with the newer request.
651 ///
652 /// # Correctness
653 ///
654 /// Block commit requests should be wrapped in a timeout, so that
655 /// out-of-order and invalid requests do not hang indefinitely. See the [`crate`]
656 /// documentation for details.
657 CommitSemanticallyVerifiedBlock(SemanticallyVerifiedBlock),
658
659 /// Commit a checkpointed block to the state, skipping most but not all
660 /// contextual validation.
661 ///
662 /// This is exposed for use in checkpointing, which produces checkpoint vefified
663 /// blocks. This request can be made out-of-order; the state service will queue
664 /// it until its parent is ready.
665 ///
666 /// Returns [`Response::Committed`] with the hash of the newly committed
667 /// block, or an error.
668 ///
669 /// This request cannot be cancelled once submitted; dropping the response
670 /// future will have no effect on whether it is eventually processed.
671 /// Duplicate requests will replace the older duplicate, and return an error
672 /// in its response future.
673 ///
674 /// # Note
675 ///
676 /// [`SemanticallyVerifiedBlock`], [`ContextuallyVerifiedBlock`] and
677 /// [`CheckpointVerifiedBlock`] are an internal Zebra implementation detail.
678 /// There is no difference between these blocks on the Zcash network, or in Zebra's
679 /// network or syncer implementations.
680 ///
681 /// # Consensus
682 ///
683 /// Checkpointing is allowed under the Zcash "social consensus" rules.
684 /// Zebra checkpoints both settled network upgrades, and blocks past the rollback limit.
685 /// (By the time Zebra release is tagged, its final checkpoint is typically hours or days old.)
686 ///
687 /// > A network upgrade is settled on a given network when there is a social consensus
688 /// > that it has activated with a given activation block hash. A full validator that
689 /// > potentially risks Mainnet funds or displays Mainnet transaction information to a user
690 /// > MUST do so only for a block chain that includes the activation block of the most
691 /// > recent settled network upgrade, with the corresponding activation block hash.
692 /// > ...
693 /// > A full validator MAY impose a limit on the number of blocks it will “roll back”
694 /// > when switching from one best valid block chain to another that is not a descendent.
695 /// > For `zcashd` and `zebra` this limit is 100 blocks.
696 ///
697 /// <https://zips.z.cash/protocol/protocol.pdf#blockchain>
698 ///
699 /// # Correctness
700 ///
701 /// Block commit requests should be wrapped in a timeout, so that
702 /// out-of-order and invalid requests do not hang indefinitely. See the [`crate`]
703 /// documentation for details.
704 CommitCheckpointVerifiedBlock(CheckpointVerifiedBlock),
705
706 /// Computes the depth in the current best chain of the block identified by the given hash.
707 ///
708 /// Returns
709 ///
710 /// * [`Response::Depth(Some(depth))`](Response::Depth) if the block is in the best chain;
711 /// * [`Response::Depth(None)`](Response::Depth) otherwise.
712 Depth(block::Hash),
713
714 /// Returns [`Response::Tip(Option<(Height, block::Hash)>)`](Response::Tip)
715 /// with the current best chain tip.
716 Tip,
717
718 /// Computes a block locator object based on the current best chain.
719 ///
720 /// Returns [`Response::BlockLocator`] with hashes starting
721 /// from the best chain tip, and following the chain of previous
722 /// hashes. The first hash is the best chain tip. The last hash is
723 /// the tip of the finalized portion of the state. Block locators
724 /// are not continuous - some intermediate hashes might be skipped.
725 ///
726 /// If the state is empty, the block locator is also empty.
727 BlockLocator,
728
729 /// Looks up a transaction by hash in the current best chain.
730 ///
731 /// Returns
732 ///
733 /// * [`Response::Transaction(Some(Arc<Transaction>))`](Response::Transaction) if the transaction is in the best chain;
734 /// * [`Response::Transaction(None)`](Response::Transaction) otherwise.
735 Transaction(transaction::Hash),
736
737 /// Looks up a UTXO identified by the given [`OutPoint`](transparent::OutPoint),
738 /// returning `None` immediately if it is unknown.
739 ///
740 /// Checks verified blocks in the finalized chain and the _best_ non-finalized chain.
741 UnspentBestChainUtxo(transparent::OutPoint),
742
743 /// Looks up a block by hash or height in the current best chain.
744 ///
745 /// Returns
746 ///
747 /// * [`Response::Block(Some(Arc<Block>))`](Response::Block) if the block is in the best chain;
748 /// * [`Response::Block(None)`](Response::Block) otherwise.
749 ///
750 /// Note: the [`HashOrHeight`] can be constructed from a [`block::Hash`] or
751 /// [`block::Height`] using `.into()`.
752 Block(HashOrHeight),
753
754 //// Same as Block, but also returns serialized block size.
755 ////
756 /// Returns
757 ///
758 /// * [`ReadResponse::BlockAndSize(Some((Arc<Block>, usize)))`](ReadResponse::BlockAndSize) if the block is in the best chain;
759 /// * [`ReadResponse::BlockAndSize(None)`](ReadResponse::BlockAndSize) otherwise.
760 BlockAndSize(HashOrHeight),
761
762 /// Looks up a block header by hash or height in the current best chain.
763 ///
764 /// Returns
765 ///
766 /// [`Response::BlockHeader(block::Header)`](Response::BlockHeader).
767 ///
768 /// Note: the [`HashOrHeight`] can be constructed from a [`block::Hash`] or
769 /// [`block::Height`] using `.into()`.
770 BlockHeader(HashOrHeight),
771
772 /// Request a UTXO identified by the given [`OutPoint`](transparent::OutPoint),
773 /// waiting until it becomes available if it is unknown.
774 ///
775 /// Checks the finalized chain, all non-finalized chains, queued unverified blocks,
776 /// and any blocks that arrive at the state after the request future has been created.
777 ///
778 /// This request is purely informational, and there are no guarantees about
779 /// whether the UTXO remains unspent or is on the best chain, or any chain.
780 /// Its purpose is to allow asynchronous script verification or to wait until
781 /// the UTXO arrives in the state before validating dependent transactions.
782 ///
783 /// # Correctness
784 ///
785 /// UTXO requests should be wrapped in a timeout, so that
786 /// out-of-order and invalid requests do not hang indefinitely. See the [`crate`]
787 /// documentation for details.
788 ///
789 /// Outdated requests are pruned on a regular basis.
790 AwaitUtxo(transparent::OutPoint),
791
792 /// Finds the first hash that's in the peer's `known_blocks` and the local best chain.
793 /// Returns a list of hashes that follow that intersection, from the best chain.
794 ///
795 /// If there is no matching hash in the best chain, starts from the genesis hash.
796 ///
797 /// Stops the list of hashes after:
798 /// * adding the best tip,
799 /// * adding the `stop` hash to the list, if it is in the best chain, or
800 /// * adding 500 hashes to the list.
801 ///
802 /// Returns an empty list if the state is empty.
803 ///
804 /// Returns
805 ///
806 /// [`Response::BlockHashes(Vec<block::Hash>)`](Response::BlockHashes).
807 /// See <https://en.bitcoin.it/wiki/Protocol_documentation#getblocks>
808 FindBlockHashes {
809 /// Hashes of known blocks, ordered from highest height to lowest height.
810 known_blocks: Vec<block::Hash>,
811 /// Optionally, the last block hash to request.
812 stop: Option<block::Hash>,
813 },
814
815 /// Finds the first hash that's in the peer's `known_blocks` and the local best chain.
816 /// Returns a list of headers that follow that intersection, from the best chain.
817 ///
818 /// If there is no matching hash in the best chain, starts from the genesis header.
819 ///
820 /// Stops the list of headers after:
821 /// * adding the best tip,
822 /// * adding the header matching the `stop` hash to the list, if it is in the best chain, or
823 /// * adding [`MAX_FIND_BLOCK_HEADERS_RESULTS`] headers to the list.
824 ///
825 /// Returns an empty list if the state is empty.
826 ///
827 /// Returns
828 ///
829 /// [`Response::BlockHeaders(Vec<block::Header>)`](Response::BlockHeaders).
830 /// See <https://en.bitcoin.it/wiki/Protocol_documentation#getheaders>
831 FindBlockHeaders {
832 /// Hashes of known blocks, ordered from highest height to lowest height.
833 known_blocks: Vec<block::Hash>,
834 /// Optionally, the hash of the last header to request.
835 stop: Option<block::Hash>,
836 },
837
838 /// Contextually validates anchors and nullifiers of a transaction on the best chain
839 ///
840 /// Returns [`Response::ValidBestChainTipNullifiersAndAnchors`]
841 CheckBestChainTipNullifiersAndAnchors(UnminedTx),
842
843 /// Calculates the median-time-past for the *next* block on the best chain.
844 ///
845 /// Returns [`Response::BestChainNextMedianTimePast`] when successful.
846 BestChainNextMedianTimePast,
847
848 /// Looks up a block hash by height in the current best chain.
849 ///
850 /// Returns
851 ///
852 /// * [`Response::BlockHash(Some(hash))`](Response::BlockHash) if the block is in the best chain;
853 /// * [`Response::BlockHash(None)`](Response::BlockHash) otherwise.
854 BestChainBlockHash(block::Height),
855
856 /// Checks if a block is present anywhere in the state service.
857 /// Looks up `hash` in block queues as well as the finalized chain and all non-finalized chains.
858 ///
859 /// Returns [`Response::KnownBlock(Some(Location))`](Response::KnownBlock) if the block is in the best state service.
860 /// Returns [`Response::KnownBlock(None)`](Response::KnownBlock) otherwise.
861 KnownBlock(block::Hash),
862
863 /// Performs contextual validation of the given block, but does not commit it to the state.
864 ///
865 /// Returns [`Response::ValidBlockProposal`] when successful.
866 /// See `[ReadRequest::CheckBlockProposalValidity]` for details.
867 CheckBlockProposalValidity(SemanticallyVerifiedBlock),
868}
869
870impl Request {
871 fn variant_name(&self) -> &'static str {
872 match self {
873 Request::CommitSemanticallyVerifiedBlock(_) => "commit_semantically_verified_block",
874 Request::CommitCheckpointVerifiedBlock(_) => "commit_checkpoint_verified_block",
875
876 Request::AwaitUtxo(_) => "await_utxo",
877 Request::Depth(_) => "depth",
878 Request::Tip => "tip",
879 Request::BlockLocator => "block_locator",
880 Request::Transaction(_) => "transaction",
881 Request::UnspentBestChainUtxo { .. } => "unspent_best_chain_utxo",
882 Request::Block(_) => "block",
883 Request::BlockAndSize(_) => "block_and_size",
884 Request::BlockHeader(_) => "block_header",
885 Request::FindBlockHashes { .. } => "find_block_hashes",
886 Request::FindBlockHeaders { .. } => "find_block_headers",
887 Request::CheckBestChainTipNullifiersAndAnchors(_) => {
888 "best_chain_tip_nullifiers_anchors"
889 }
890 Request::BestChainNextMedianTimePast => "best_chain_next_median_time_past",
891 Request::BestChainBlockHash(_) => "best_chain_block_hash",
892 Request::KnownBlock(_) => "known_block",
893 Request::CheckBlockProposalValidity(_) => "check_block_proposal_validity",
894 }
895 }
896
897 /// Counts metric for StateService call
898 pub fn count_metric(&self) {
899 metrics::counter!(
900 "state.requests",
901 "service" => "state",
902 "type" => self.variant_name()
903 )
904 .increment(1);
905 }
906}
907
908#[derive(Clone, Debug, PartialEq, Eq)]
909/// A read-only query about the chain state, via the
910/// [`ReadStateService`](crate::service::ReadStateService).
911pub enum ReadRequest {
912 /// Returns [`ReadResponse::UsageInfo(num_bytes: u64)`](ReadResponse::UsageInfo)
913 /// with the current disk space usage in bytes.
914 UsageInfo,
915
916 /// Returns [`ReadResponse::Tip(Option<(Height, block::Hash)>)`](ReadResponse::Tip)
917 /// with the current best chain tip.
918 Tip,
919
920 /// Returns [`ReadResponse::TipPoolValues(Option<(Height, block::Hash, ValueBalance)>)`](ReadResponse::TipPoolValues)
921 /// with the current best chain tip.
922 TipPoolValues,
923
924 /// Computes the depth in the current best chain of the block identified by the given hash.
925 ///
926 /// Returns
927 ///
928 /// * [`ReadResponse::Depth(Some(depth))`](ReadResponse::Depth) if the block is in the best chain;
929 /// * [`ReadResponse::Depth(None)`](ReadResponse::Depth) otherwise.
930 Depth(block::Hash),
931
932 /// Looks up a block by hash or height in the current best chain.
933 ///
934 /// Returns
935 ///
936 /// * [`ReadResponse::Block(Some(Arc<Block>))`](ReadResponse::Block) if the block is in the best chain;
937 /// * [`ReadResponse::Block(None)`](ReadResponse::Block) otherwise.
938 ///
939 /// Note: the [`HashOrHeight`] can be constructed from a [`block::Hash`] or
940 /// [`block::Height`] using `.into()`.
941 Block(HashOrHeight),
942
943 //// Same as Block, but also returns serialized block size.
944 ////
945 /// Returns
946 ///
947 /// * [`ReadResponse::BlockAndSize(Some((Arc<Block>, usize)))`](ReadResponse::BlockAndSize) if the block is in the best chain;
948 /// * [`ReadResponse::BlockAndSize(None)`](ReadResponse::BlockAndSize) otherwise.
949 BlockAndSize(HashOrHeight),
950
951 /// Looks up a block header by hash or height in the current best chain.
952 ///
953 /// Returns
954 ///
955 /// [`Response::BlockHeader(block::Header)`](Response::BlockHeader).
956 ///
957 /// Note: the [`HashOrHeight`] can be constructed from a [`block::Hash`] or
958 /// [`block::Height`] using `.into()`.
959 BlockHeader(HashOrHeight),
960
961 /// Looks up a transaction by hash in the current best chain.
962 ///
963 /// Returns
964 ///
965 /// * [`ReadResponse::Transaction(Some(Arc<Transaction>))`](ReadResponse::Transaction) if the transaction is in the best chain;
966 /// * [`ReadResponse::Transaction(None)`](ReadResponse::Transaction) otherwise.
967 Transaction(transaction::Hash),
968
969 /// Looks up the transaction IDs for a block, using a block hash or height.
970 ///
971 /// Returns
972 ///
973 /// * An ordered list of transaction hashes, or
974 /// * `None` if the block was not found.
975 ///
976 /// Note: Each block has at least one transaction: the coinbase transaction.
977 ///
978 /// Returned txids are in the order they appear in the block.
979 TransactionIdsForBlock(HashOrHeight),
980
981 /// Looks up a UTXO identified by the given [`OutPoint`](transparent::OutPoint),
982 /// returning `None` immediately if it is unknown.
983 ///
984 /// Checks verified blocks in the finalized chain and the _best_ non-finalized chain.
985 UnspentBestChainUtxo(transparent::OutPoint),
986
987 /// Looks up a UTXO identified by the given [`OutPoint`](transparent::OutPoint),
988 /// returning `None` immediately if it is unknown.
989 ///
990 /// Checks verified blocks in the finalized chain and _all_ non-finalized chains.
991 ///
992 /// This request is purely informational, there is no guarantee that
993 /// the UTXO remains unspent in the best chain.
994 AnyChainUtxo(transparent::OutPoint),
995
996 /// Computes a block locator object based on the current best chain.
997 ///
998 /// Returns [`ReadResponse::BlockLocator`] with hashes starting
999 /// from the best chain tip, and following the chain of previous
1000 /// hashes. The first hash is the best chain tip. The last hash is
1001 /// the tip of the finalized portion of the state. Block locators
1002 /// are not continuous - some intermediate hashes might be skipped.
1003 ///
1004 /// If the state is empty, the block locator is also empty.
1005 BlockLocator,
1006
1007 /// Finds the first hash that's in the peer's `known_blocks` and the local best chain.
1008 /// Returns a list of hashes that follow that intersection, from the best chain.
1009 ///
1010 /// If there is no matching hash in the best chain, starts from the genesis hash.
1011 ///
1012 /// Stops the list of hashes after:
1013 /// * adding the best tip,
1014 /// * adding the `stop` hash to the list, if it is in the best chain, or
1015 /// * adding [`MAX_FIND_BLOCK_HASHES_RESULTS`] hashes to the list.
1016 ///
1017 /// Returns an empty list if the state is empty.
1018 ///
1019 /// Returns
1020 ///
1021 /// [`ReadResponse::BlockHashes(Vec<block::Hash>)`](ReadResponse::BlockHashes).
1022 /// See <https://en.bitcoin.it/wiki/Protocol_documentation#getblocks>
1023 FindBlockHashes {
1024 /// Hashes of known blocks, ordered from highest height to lowest height.
1025 known_blocks: Vec<block::Hash>,
1026 /// Optionally, the last block hash to request.
1027 stop: Option<block::Hash>,
1028 },
1029
1030 /// Finds the first hash that's in the peer's `known_blocks` and the local best chain.
1031 /// Returns a list of headers that follow that intersection, from the best chain.
1032 ///
1033 /// If there is no matching hash in the best chain, starts from the genesis header.
1034 ///
1035 /// Stops the list of headers after:
1036 /// * adding the best tip,
1037 /// * adding the header matching the `stop` hash to the list, if it is in the best chain, or
1038 /// * adding [`MAX_FIND_BLOCK_HEADERS_RESULTS`] headers to the list.
1039 ///
1040 /// Returns an empty list if the state is empty.
1041 ///
1042 /// Returns
1043 ///
1044 /// [`ReadResponse::BlockHeaders(Vec<block::Header>)`](ReadResponse::BlockHeaders).
1045 /// See <https://en.bitcoin.it/wiki/Protocol_documentation#getheaders>
1046 FindBlockHeaders {
1047 /// Hashes of known blocks, ordered from highest height to lowest height.
1048 known_blocks: Vec<block::Hash>,
1049 /// Optionally, the hash of the last header to request.
1050 stop: Option<block::Hash>,
1051 },
1052
1053 /// Looks up a Sapling note commitment tree either by a hash or height.
1054 ///
1055 /// Returns
1056 ///
1057 /// * [`ReadResponse::SaplingTree(Some(Arc<NoteCommitmentTree>))`](crate::ReadResponse::SaplingTree)
1058 /// if the corresponding block contains a Sapling note commitment tree.
1059 /// * [`ReadResponse::SaplingTree(None)`](crate::ReadResponse::SaplingTree) otherwise.
1060 SaplingTree(HashOrHeight),
1061
1062 /// Looks up an Orchard note commitment tree either by a hash or height.
1063 ///
1064 /// Returns
1065 ///
1066 /// * [`ReadResponse::OrchardTree(Some(Arc<NoteCommitmentTree>))`](crate::ReadResponse::OrchardTree)
1067 /// if the corresponding block contains a Sapling note commitment tree.
1068 /// * [`ReadResponse::OrchardTree(None)`](crate::ReadResponse::OrchardTree) otherwise.
1069 OrchardTree(HashOrHeight),
1070
1071 /// Returns a list of Sapling note commitment subtrees by their indexes, starting at
1072 /// `start_index`, and returning up to `limit` subtrees.
1073 ///
1074 /// Returns
1075 ///
1076 /// * [`ReadResponse::SaplingSubtree(BTreeMap<_, NoteCommitmentSubtreeData<_>>))`](crate::ReadResponse::SaplingSubtrees)
1077 /// * An empty list if there is no subtree at `start_index`.
1078 SaplingSubtrees {
1079 /// The index of the first 2^16-leaf subtree to return.
1080 start_index: NoteCommitmentSubtreeIndex,
1081 /// The maximum number of subtree values to return.
1082 limit: Option<NoteCommitmentSubtreeIndex>,
1083 },
1084
1085 /// Returns a list of Orchard note commitment subtrees by their indexes, starting at
1086 /// `start_index`, and returning up to `limit` subtrees.
1087 ///
1088 /// Returns
1089 ///
1090 /// * [`ReadResponse::OrchardSubtree(BTreeMap<_, NoteCommitmentSubtreeData<_>>))`](crate::ReadResponse::OrchardSubtrees)
1091 /// * An empty list if there is no subtree at `start_index`.
1092 OrchardSubtrees {
1093 /// The index of the first 2^16-leaf subtree to return.
1094 start_index: NoteCommitmentSubtreeIndex,
1095 /// The maximum number of subtree values to return.
1096 limit: Option<NoteCommitmentSubtreeIndex>,
1097 },
1098
1099 /// Looks up the balance of a set of transparent addresses.
1100 ///
1101 /// Returns an [`Amount`] with the total
1102 /// balance of the set of addresses.
1103 AddressBalance(HashSet<transparent::Address>),
1104
1105 /// Looks up transaction hashes that were sent or received from addresses,
1106 /// in an inclusive blockchain height range.
1107 ///
1108 /// Returns
1109 ///
1110 /// * An ordered, unique map of transaction locations and hashes.
1111 /// * An empty map if no transactions were found for the given arguments.
1112 ///
1113 /// Returned txids are in the order they appear in blocks,
1114 /// which ensures that they are topologically sorted
1115 /// (i.e. parent txids will appear before child txids).
1116 TransactionIdsByAddresses {
1117 /// The requested addresses.
1118 addresses: HashSet<transparent::Address>,
1119
1120 /// The blocks to be queried for transactions.
1121 height_range: RangeInclusive<block::Height>,
1122 },
1123
1124 /// Looks up a spending transaction id by its spent transparent input.
1125 ///
1126 /// Returns [`ReadResponse::TransactionId`] with the hash of the transaction
1127 /// that spent the output at the provided [`transparent::OutPoint`].
1128 #[cfg(feature = "indexer")]
1129 SpendingTransactionId(Spend),
1130
1131 /// Looks up utxos for the provided addresses.
1132 ///
1133 /// Returns a type with found utxos and transaction information.
1134 UtxosByAddresses(HashSet<transparent::Address>),
1135
1136 /// Contextually validates anchors and nullifiers of a transaction on the best chain
1137 ///
1138 /// Returns [`ReadResponse::ValidBestChainTipNullifiersAndAnchors`].
1139 CheckBestChainTipNullifiersAndAnchors(UnminedTx),
1140
1141 /// Calculates the median-time-past for the *next* block on the best chain.
1142 ///
1143 /// Returns [`ReadResponse::BestChainNextMedianTimePast`] when successful.
1144 BestChainNextMedianTimePast,
1145
1146 /// Looks up a block hash by height in the current best chain.
1147 ///
1148 /// Returns
1149 ///
1150 /// * [`ReadResponse::BlockHash(Some(hash))`](ReadResponse::BlockHash) if the block is in the best chain;
1151 /// * [`ReadResponse::BlockHash(None)`](ReadResponse::BlockHash) otherwise.
1152 BestChainBlockHash(block::Height),
1153
1154 /// Get state information from the best block chain.
1155 ///
1156 /// Returns [`ReadResponse::ChainInfo(info)`](ReadResponse::ChainInfo) where `info` is a
1157 /// [`zebra-state::GetBlockTemplateChainInfo`](zebra-state::GetBlockTemplateChainInfo)` structure containing
1158 /// best chain state information.
1159 ChainInfo,
1160
1161 /// Get the average solution rate in the best chain.
1162 ///
1163 /// Returns [`ReadResponse::SolutionRate`]
1164 SolutionRate {
1165 /// The number of blocks to calculate the average difficulty for.
1166 num_blocks: usize,
1167 /// Optionally estimate the network solution rate at the time when this height was mined.
1168 /// Otherwise, estimate at the current tip height.
1169 height: Option<block::Height>,
1170 },
1171
1172 /// Performs contextual validation of the given block, but does not commit it to the state.
1173 ///
1174 /// It is the caller's responsibility to perform semantic validation.
1175 /// (The caller does not need to check proof of work for block proposals.)
1176 ///
1177 /// Returns [`ReadResponse::ValidBlockProposal`] when successful, or an error if
1178 /// the block fails contextual validation.
1179 CheckBlockProposalValidity(SemanticallyVerifiedBlock),
1180
1181 /// Returns [`ReadResponse::TipBlockSize(usize)`](ReadResponse::TipBlockSize)
1182 /// with the current best chain tip block size in bytes.
1183 TipBlockSize,
1184}
1185
1186impl ReadRequest {
1187 fn variant_name(&self) -> &'static str {
1188 match self {
1189 ReadRequest::UsageInfo => "usage_info",
1190 ReadRequest::Tip => "tip",
1191 ReadRequest::TipPoolValues => "tip_pool_values",
1192 ReadRequest::Depth(_) => "depth",
1193 ReadRequest::Block(_) => "block",
1194 ReadRequest::BlockAndSize(_) => "block_and_size",
1195 ReadRequest::BlockHeader(_) => "block_header",
1196 ReadRequest::Transaction(_) => "transaction",
1197 ReadRequest::TransactionIdsForBlock(_) => "transaction_ids_for_block",
1198 ReadRequest::UnspentBestChainUtxo { .. } => "unspent_best_chain_utxo",
1199 ReadRequest::AnyChainUtxo { .. } => "any_chain_utxo",
1200 ReadRequest::BlockLocator => "block_locator",
1201 ReadRequest::FindBlockHashes { .. } => "find_block_hashes",
1202 ReadRequest::FindBlockHeaders { .. } => "find_block_headers",
1203 ReadRequest::SaplingTree { .. } => "sapling_tree",
1204 ReadRequest::OrchardTree { .. } => "orchard_tree",
1205 ReadRequest::SaplingSubtrees { .. } => "sapling_subtrees",
1206 ReadRequest::OrchardSubtrees { .. } => "orchard_subtrees",
1207 ReadRequest::AddressBalance { .. } => "address_balance",
1208 ReadRequest::TransactionIdsByAddresses { .. } => "transaction_ids_by_addresses",
1209 ReadRequest::UtxosByAddresses(_) => "utxos_by_addresses",
1210 ReadRequest::CheckBestChainTipNullifiersAndAnchors(_) => {
1211 "best_chain_tip_nullifiers_anchors"
1212 }
1213 ReadRequest::BestChainNextMedianTimePast => "best_chain_next_median_time_past",
1214 ReadRequest::BestChainBlockHash(_) => "best_chain_block_hash",
1215 #[cfg(feature = "indexer")]
1216 ReadRequest::SpendingTransactionId(_) => "spending_transaction_id",
1217 ReadRequest::ChainInfo => "chain_info",
1218 ReadRequest::SolutionRate { .. } => "solution_rate",
1219 ReadRequest::CheckBlockProposalValidity(_) => "check_block_proposal_validity",
1220 ReadRequest::TipBlockSize => "tip_block_size",
1221 }
1222 }
1223
1224 /// Counts metric for ReadStateService call
1225 pub fn count_metric(&self) {
1226 metrics::counter!(
1227 "state.requests",
1228 "service" => "read_state",
1229 "type" => self.variant_name()
1230 )
1231 .increment(1);
1232 }
1233}
1234
1235/// Conversion from read-write [`Request`]s to read-only [`ReadRequest`]s.
1236///
1237/// Used to dispatch read requests concurrently from the [`StateService`](crate::service::StateService).
1238impl TryFrom<Request> for ReadRequest {
1239 type Error = &'static str;
1240
1241 fn try_from(request: Request) -> Result<ReadRequest, Self::Error> {
1242 match request {
1243 Request::Tip => Ok(ReadRequest::Tip),
1244 Request::Depth(hash) => Ok(ReadRequest::Depth(hash)),
1245 Request::BestChainNextMedianTimePast => Ok(ReadRequest::BestChainNextMedianTimePast),
1246 Request::BestChainBlockHash(hash) => Ok(ReadRequest::BestChainBlockHash(hash)),
1247
1248 Request::Block(hash_or_height) => Ok(ReadRequest::Block(hash_or_height)),
1249 Request::BlockAndSize(hash_or_height) => Ok(ReadRequest::BlockAndSize(hash_or_height)),
1250 Request::BlockHeader(hash_or_height) => Ok(ReadRequest::BlockHeader(hash_or_height)),
1251 Request::Transaction(tx_hash) => Ok(ReadRequest::Transaction(tx_hash)),
1252 Request::UnspentBestChainUtxo(outpoint) => {
1253 Ok(ReadRequest::UnspentBestChainUtxo(outpoint))
1254 }
1255
1256 Request::BlockLocator => Ok(ReadRequest::BlockLocator),
1257 Request::FindBlockHashes { known_blocks, stop } => {
1258 Ok(ReadRequest::FindBlockHashes { known_blocks, stop })
1259 }
1260 Request::FindBlockHeaders { known_blocks, stop } => {
1261 Ok(ReadRequest::FindBlockHeaders { known_blocks, stop })
1262 }
1263
1264 Request::CheckBestChainTipNullifiersAndAnchors(tx) => {
1265 Ok(ReadRequest::CheckBestChainTipNullifiersAndAnchors(tx))
1266 }
1267
1268 Request::CommitSemanticallyVerifiedBlock(_)
1269 | Request::CommitCheckpointVerifiedBlock(_) => Err("ReadService does not write blocks"),
1270
1271 Request::AwaitUtxo(_) => Err("ReadService does not track pending UTXOs. \
1272 Manually convert the request to ReadRequest::AnyChainUtxo, \
1273 and handle pending UTXOs"),
1274
1275 Request::KnownBlock(_) => Err("ReadService does not track queued blocks"),
1276
1277 Request::CheckBlockProposalValidity(semantically_verified) => Ok(
1278 ReadRequest::CheckBlockProposalValidity(semantically_verified),
1279 ),
1280 }
1281 }
1282}