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 /// Invalidates a block in the non-finalized state with the provided hash if one is present, removing it and
864 /// its child blocks, and rejecting it during contextual validation if it's resubmitted to the state.
865 InvalidateBlock(block::Hash),
866
867 /// Reconsiders a previously invalidated block in the non-finalized state with the provided hash if one is present.
868 ReconsiderBlock(block::Hash),
869
870 /// Performs contextual validation of the given block, but does not commit it to the state.
871 ///
872 /// Returns [`Response::ValidBlockProposal`] when successful.
873 /// See `[ReadRequest::CheckBlockProposalValidity]` for details.
874 CheckBlockProposalValidity(SemanticallyVerifiedBlock),
875}
876
877impl Request {
878 fn variant_name(&self) -> &'static str {
879 match self {
880 Request::CommitSemanticallyVerifiedBlock(_) => "commit_semantically_verified_block",
881 Request::CommitCheckpointVerifiedBlock(_) => "commit_checkpoint_verified_block",
882
883 Request::AwaitUtxo(_) => "await_utxo",
884 Request::Depth(_) => "depth",
885 Request::Tip => "tip",
886 Request::BlockLocator => "block_locator",
887 Request::Transaction(_) => "transaction",
888 Request::UnspentBestChainUtxo { .. } => "unspent_best_chain_utxo",
889 Request::Block(_) => "block",
890 Request::BlockAndSize(_) => "block_and_size",
891 Request::BlockHeader(_) => "block_header",
892 Request::FindBlockHashes { .. } => "find_block_hashes",
893 Request::FindBlockHeaders { .. } => "find_block_headers",
894 Request::CheckBestChainTipNullifiersAndAnchors(_) => {
895 "best_chain_tip_nullifiers_anchors"
896 }
897 Request::BestChainNextMedianTimePast => "best_chain_next_median_time_past",
898 Request::BestChainBlockHash(_) => "best_chain_block_hash",
899 Request::KnownBlock(_) => "known_block",
900 Request::InvalidateBlock(_) => "invalidate_block",
901 Request::ReconsiderBlock(_) => "reconsider_block",
902 Request::CheckBlockProposalValidity(_) => "check_block_proposal_validity",
903 }
904 }
905
906 /// Counts metric for StateService call
907 pub fn count_metric(&self) {
908 metrics::counter!(
909 "state.requests",
910 "service" => "state",
911 "type" => self.variant_name()
912 )
913 .increment(1);
914 }
915}
916
917#[derive(Clone, Debug, PartialEq, Eq)]
918/// A read-only query about the chain state, via the
919/// [`ReadStateService`](crate::service::ReadStateService).
920pub enum ReadRequest {
921 /// Returns [`ReadResponse::UsageInfo(num_bytes: u64)`](ReadResponse::UsageInfo)
922 /// with the current disk space usage in bytes.
923 UsageInfo,
924
925 /// Returns [`ReadResponse::Tip(Option<(Height, block::Hash)>)`](ReadResponse::Tip)
926 /// with the current best chain tip.
927 Tip,
928
929 /// Returns [`ReadResponse::TipPoolValues(Option<(Height, block::Hash, ValueBalance)>)`](ReadResponse::TipPoolValues)
930 /// with the pool values of the current best chain tip.
931 TipPoolValues,
932
933 /// Looks up the block info after a block by hash or height in the current best chain.
934 ///
935 /// * [`ReadResponse::BlockInfo(Some(pool_values))`](ReadResponse::BlockInfo) if the block is in the best chain;
936 /// * [`ReadResponse::BlockInfo(None)`](ReadResponse::BlockInfo) otherwise.
937 BlockInfo(HashOrHeight),
938
939 /// Computes the depth in the current best chain of the block identified by the given hash.
940 ///
941 /// Returns
942 ///
943 /// * [`ReadResponse::Depth(Some(depth))`](ReadResponse::Depth) if the block is in the best chain;
944 /// * [`ReadResponse::Depth(None)`](ReadResponse::Depth) otherwise.
945 Depth(block::Hash),
946
947 /// Looks up a block by hash or height in the current best chain.
948 ///
949 /// Returns
950 ///
951 /// * [`ReadResponse::Block(Some(Arc<Block>))`](ReadResponse::Block) if the block is in the best chain;
952 /// * [`ReadResponse::Block(None)`](ReadResponse::Block) otherwise.
953 ///
954 /// Note: the [`HashOrHeight`] can be constructed from a [`block::Hash`] or
955 /// [`block::Height`] using `.into()`.
956 Block(HashOrHeight),
957
958 //// Same as Block, but also returns serialized block size.
959 ////
960 /// Returns
961 ///
962 /// * [`ReadResponse::BlockAndSize(Some((Arc<Block>, usize)))`](ReadResponse::BlockAndSize) if the block is in the best chain;
963 /// * [`ReadResponse::BlockAndSize(None)`](ReadResponse::BlockAndSize) otherwise.
964 BlockAndSize(HashOrHeight),
965
966 /// Looks up a block header by hash or height in the current best chain.
967 ///
968 /// Returns
969 ///
970 /// [`Response::BlockHeader(block::Header)`](Response::BlockHeader).
971 ///
972 /// Note: the [`HashOrHeight`] can be constructed from a [`block::Hash`] or
973 /// [`block::Height`] using `.into()`.
974 BlockHeader(HashOrHeight),
975
976 /// Looks up a transaction by hash in the current best chain.
977 ///
978 /// Returns
979 ///
980 /// * [`ReadResponse::Transaction(Some(Arc<Transaction>))`](ReadResponse::Transaction) if the transaction is in the best chain;
981 /// * [`ReadResponse::Transaction(None)`](ReadResponse::Transaction) otherwise.
982 Transaction(transaction::Hash),
983
984 /// Looks up the transaction IDs for a block, using a block hash or height.
985 ///
986 /// Returns
987 ///
988 /// * An ordered list of transaction hashes, or
989 /// * `None` if the block was not found.
990 ///
991 /// Note: Each block has at least one transaction: the coinbase transaction.
992 ///
993 /// Returned txids are in the order they appear in the block.
994 TransactionIdsForBlock(HashOrHeight),
995
996 /// Looks up a UTXO identified by the given [`OutPoint`](transparent::OutPoint),
997 /// returning `None` immediately if it is unknown.
998 ///
999 /// Checks verified blocks in the finalized chain and the _best_ non-finalized chain.
1000 UnspentBestChainUtxo(transparent::OutPoint),
1001
1002 /// Looks up a UTXO identified by the given [`OutPoint`](transparent::OutPoint),
1003 /// returning `None` immediately if it is unknown.
1004 ///
1005 /// Checks verified blocks in the finalized chain and _all_ non-finalized chains.
1006 ///
1007 /// This request is purely informational, there is no guarantee that
1008 /// the UTXO remains unspent in the best chain.
1009 AnyChainUtxo(transparent::OutPoint),
1010
1011 /// Computes a block locator object based on the current best chain.
1012 ///
1013 /// Returns [`ReadResponse::BlockLocator`] with hashes starting
1014 /// from the best chain tip, and following the chain of previous
1015 /// hashes. The first hash is the best chain tip. The last hash is
1016 /// the tip of the finalized portion of the state. Block locators
1017 /// are not continuous - some intermediate hashes might be skipped.
1018 ///
1019 /// If the state is empty, the block locator is also empty.
1020 BlockLocator,
1021
1022 /// Finds the first hash that's in the peer's `known_blocks` and the local best chain.
1023 /// Returns a list of hashes that follow that intersection, from the best chain.
1024 ///
1025 /// If there is no matching hash in the best chain, starts from the genesis hash.
1026 ///
1027 /// Stops the list of hashes after:
1028 /// * adding the best tip,
1029 /// * adding the `stop` hash to the list, if it is in the best chain, or
1030 /// * adding [`MAX_FIND_BLOCK_HASHES_RESULTS`] hashes to the list.
1031 ///
1032 /// Returns an empty list if the state is empty.
1033 ///
1034 /// Returns
1035 ///
1036 /// [`ReadResponse::BlockHashes(Vec<block::Hash>)`](ReadResponse::BlockHashes).
1037 /// See <https://en.bitcoin.it/wiki/Protocol_documentation#getblocks>
1038 FindBlockHashes {
1039 /// Hashes of known blocks, ordered from highest height to lowest height.
1040 known_blocks: Vec<block::Hash>,
1041 /// Optionally, the last block hash to request.
1042 stop: Option<block::Hash>,
1043 },
1044
1045 /// Finds the first hash that's in the peer's `known_blocks` and the local best chain.
1046 /// Returns a list of headers that follow that intersection, from the best chain.
1047 ///
1048 /// If there is no matching hash in the best chain, starts from the genesis header.
1049 ///
1050 /// Stops the list of headers after:
1051 /// * adding the best tip,
1052 /// * adding the header matching the `stop` hash to the list, if it is in the best chain, or
1053 /// * adding [`MAX_FIND_BLOCK_HEADERS_RESULTS`] headers to the list.
1054 ///
1055 /// Returns an empty list if the state is empty.
1056 ///
1057 /// Returns
1058 ///
1059 /// [`ReadResponse::BlockHeaders(Vec<block::Header>)`](ReadResponse::BlockHeaders).
1060 /// See <https://en.bitcoin.it/wiki/Protocol_documentation#getheaders>
1061 FindBlockHeaders {
1062 /// Hashes of known blocks, ordered from highest height to lowest height.
1063 known_blocks: Vec<block::Hash>,
1064 /// Optionally, the hash of the last header to request.
1065 stop: Option<block::Hash>,
1066 },
1067
1068 /// Looks up a Sapling note commitment tree either by a hash or height.
1069 ///
1070 /// Returns
1071 ///
1072 /// * [`ReadResponse::SaplingTree(Some(Arc<NoteCommitmentTree>))`](crate::ReadResponse::SaplingTree)
1073 /// if the corresponding block contains a Sapling note commitment tree.
1074 /// * [`ReadResponse::SaplingTree(None)`](crate::ReadResponse::SaplingTree) otherwise.
1075 SaplingTree(HashOrHeight),
1076
1077 /// Looks up an Orchard note commitment tree either by a hash or height.
1078 ///
1079 /// Returns
1080 ///
1081 /// * [`ReadResponse::OrchardTree(Some(Arc<NoteCommitmentTree>))`](crate::ReadResponse::OrchardTree)
1082 /// if the corresponding block contains a Sapling note commitment tree.
1083 /// * [`ReadResponse::OrchardTree(None)`](crate::ReadResponse::OrchardTree) otherwise.
1084 OrchardTree(HashOrHeight),
1085
1086 /// Returns a list of Sapling note commitment subtrees by their indexes, starting at
1087 /// `start_index`, and returning up to `limit` subtrees.
1088 ///
1089 /// Returns
1090 ///
1091 /// * [`ReadResponse::SaplingSubtree(BTreeMap<_, NoteCommitmentSubtreeData<_>>))`](crate::ReadResponse::SaplingSubtrees)
1092 /// * An empty list if there is no subtree at `start_index`.
1093 SaplingSubtrees {
1094 /// The index of the first 2^16-leaf subtree to return.
1095 start_index: NoteCommitmentSubtreeIndex,
1096 /// The maximum number of subtree values to return.
1097 limit: Option<NoteCommitmentSubtreeIndex>,
1098 },
1099
1100 /// Returns a list of Orchard note commitment subtrees by their indexes, starting at
1101 /// `start_index`, and returning up to `limit` subtrees.
1102 ///
1103 /// Returns
1104 ///
1105 /// * [`ReadResponse::OrchardSubtree(BTreeMap<_, NoteCommitmentSubtreeData<_>>))`](crate::ReadResponse::OrchardSubtrees)
1106 /// * An empty list if there is no subtree at `start_index`.
1107 OrchardSubtrees {
1108 /// The index of the first 2^16-leaf subtree to return.
1109 start_index: NoteCommitmentSubtreeIndex,
1110 /// The maximum number of subtree values to return.
1111 limit: Option<NoteCommitmentSubtreeIndex>,
1112 },
1113
1114 /// Looks up the balance of a set of transparent addresses.
1115 ///
1116 /// Returns an [`Amount`] with the total
1117 /// balance of the set of addresses.
1118 AddressBalance(HashSet<transparent::Address>),
1119
1120 /// Looks up transaction hashes that were sent or received from addresses,
1121 /// in an inclusive blockchain height range.
1122 ///
1123 /// Returns
1124 ///
1125 /// * An ordered, unique map of transaction locations and hashes.
1126 /// * An empty map if no transactions were found for the given arguments.
1127 ///
1128 /// Returned txids are in the order they appear in blocks,
1129 /// which ensures that they are topologically sorted
1130 /// (i.e. parent txids will appear before child txids).
1131 TransactionIdsByAddresses {
1132 /// The requested addresses.
1133 addresses: HashSet<transparent::Address>,
1134
1135 /// The blocks to be queried for transactions.
1136 height_range: RangeInclusive<block::Height>,
1137 },
1138
1139 /// Looks up a spending transaction id by its spent transparent input.
1140 ///
1141 /// Returns [`ReadResponse::TransactionId`] with the hash of the transaction
1142 /// that spent the output at the provided [`transparent::OutPoint`].
1143 #[cfg(feature = "indexer")]
1144 SpendingTransactionId(Spend),
1145
1146 /// Looks up utxos for the provided addresses.
1147 ///
1148 /// Returns a type with found utxos and transaction information.
1149 UtxosByAddresses(HashSet<transparent::Address>),
1150
1151 /// Contextually validates anchors and nullifiers of a transaction on the best chain
1152 ///
1153 /// Returns [`ReadResponse::ValidBestChainTipNullifiersAndAnchors`].
1154 CheckBestChainTipNullifiersAndAnchors(UnminedTx),
1155
1156 /// Calculates the median-time-past for the *next* block on the best chain.
1157 ///
1158 /// Returns [`ReadResponse::BestChainNextMedianTimePast`] when successful.
1159 BestChainNextMedianTimePast,
1160
1161 /// Looks up a block hash by height in the current best chain.
1162 ///
1163 /// Returns
1164 ///
1165 /// * [`ReadResponse::BlockHash(Some(hash))`](ReadResponse::BlockHash) if the block is in the best chain;
1166 /// * [`ReadResponse::BlockHash(None)`](ReadResponse::BlockHash) otherwise.
1167 BestChainBlockHash(block::Height),
1168
1169 /// Get state information from the best block chain.
1170 ///
1171 /// Returns [`ReadResponse::ChainInfo(info)`](ReadResponse::ChainInfo) where `info` is a
1172 /// [`zebra-state::GetBlockTemplateChainInfo`](zebra-state::GetBlockTemplateChainInfo)` structure containing
1173 /// best chain state information.
1174 ChainInfo,
1175
1176 /// Get the average solution rate in the best chain.
1177 ///
1178 /// Returns [`ReadResponse::SolutionRate`]
1179 SolutionRate {
1180 /// The number of blocks to calculate the average difficulty for.
1181 num_blocks: usize,
1182 /// Optionally estimate the network solution rate at the time when this height was mined.
1183 /// Otherwise, estimate at the current tip height.
1184 height: Option<block::Height>,
1185 },
1186
1187 /// Performs contextual validation of the given block, but does not commit it to the state.
1188 ///
1189 /// It is the caller's responsibility to perform semantic validation.
1190 /// (The caller does not need to check proof of work for block proposals.)
1191 ///
1192 /// Returns [`ReadResponse::ValidBlockProposal`] when successful, or an error if
1193 /// the block fails contextual validation.
1194 CheckBlockProposalValidity(SemanticallyVerifiedBlock),
1195
1196 /// Returns [`ReadResponse::TipBlockSize(usize)`](ReadResponse::TipBlockSize)
1197 /// with the current best chain tip block size in bytes.
1198 TipBlockSize,
1199
1200 /// Returns [`ReadResponse::NonFinalizedBlocksListener`] with a channel receiver
1201 /// allowing the caller to listen for new blocks in the non-finalized state.
1202 NonFinalizedBlocksListener,
1203}
1204
1205impl ReadRequest {
1206 fn variant_name(&self) -> &'static str {
1207 match self {
1208 ReadRequest::UsageInfo => "usage_info",
1209 ReadRequest::Tip => "tip",
1210 ReadRequest::TipPoolValues => "tip_pool_values",
1211 ReadRequest::BlockInfo(_) => "block_info",
1212 ReadRequest::Depth(_) => "depth",
1213 ReadRequest::Block(_) => "block",
1214 ReadRequest::BlockAndSize(_) => "block_and_size",
1215 ReadRequest::BlockHeader(_) => "block_header",
1216 ReadRequest::Transaction(_) => "transaction",
1217 ReadRequest::TransactionIdsForBlock(_) => "transaction_ids_for_block",
1218 ReadRequest::UnspentBestChainUtxo { .. } => "unspent_best_chain_utxo",
1219 ReadRequest::AnyChainUtxo { .. } => "any_chain_utxo",
1220 ReadRequest::BlockLocator => "block_locator",
1221 ReadRequest::FindBlockHashes { .. } => "find_block_hashes",
1222 ReadRequest::FindBlockHeaders { .. } => "find_block_headers",
1223 ReadRequest::SaplingTree { .. } => "sapling_tree",
1224 ReadRequest::OrchardTree { .. } => "orchard_tree",
1225 ReadRequest::SaplingSubtrees { .. } => "sapling_subtrees",
1226 ReadRequest::OrchardSubtrees { .. } => "orchard_subtrees",
1227 ReadRequest::AddressBalance { .. } => "address_balance",
1228 ReadRequest::TransactionIdsByAddresses { .. } => "transaction_ids_by_addresses",
1229 ReadRequest::UtxosByAddresses(_) => "utxos_by_addresses",
1230 ReadRequest::CheckBestChainTipNullifiersAndAnchors(_) => {
1231 "best_chain_tip_nullifiers_anchors"
1232 }
1233 ReadRequest::BestChainNextMedianTimePast => "best_chain_next_median_time_past",
1234 ReadRequest::BestChainBlockHash(_) => "best_chain_block_hash",
1235 #[cfg(feature = "indexer")]
1236 ReadRequest::SpendingTransactionId(_) => "spending_transaction_id",
1237 ReadRequest::ChainInfo => "chain_info",
1238 ReadRequest::SolutionRate { .. } => "solution_rate",
1239 ReadRequest::CheckBlockProposalValidity(_) => "check_block_proposal_validity",
1240 ReadRequest::TipBlockSize => "tip_block_size",
1241 ReadRequest::NonFinalizedBlocksListener => "non_finalized_blocks_listener",
1242 }
1243 }
1244
1245 /// Counts metric for ReadStateService call
1246 pub fn count_metric(&self) {
1247 metrics::counter!(
1248 "state.requests",
1249 "service" => "read_state",
1250 "type" => self.variant_name()
1251 )
1252 .increment(1);
1253 }
1254}
1255
1256/// Conversion from read-write [`Request`]s to read-only [`ReadRequest`]s.
1257///
1258/// Used to dispatch read requests concurrently from the [`StateService`](crate::service::StateService).
1259impl TryFrom<Request> for ReadRequest {
1260 type Error = &'static str;
1261
1262 fn try_from(request: Request) -> Result<ReadRequest, Self::Error> {
1263 match request {
1264 Request::Tip => Ok(ReadRequest::Tip),
1265 Request::Depth(hash) => Ok(ReadRequest::Depth(hash)),
1266 Request::BestChainNextMedianTimePast => Ok(ReadRequest::BestChainNextMedianTimePast),
1267 Request::BestChainBlockHash(hash) => Ok(ReadRequest::BestChainBlockHash(hash)),
1268
1269 Request::Block(hash_or_height) => Ok(ReadRequest::Block(hash_or_height)),
1270 Request::BlockAndSize(hash_or_height) => Ok(ReadRequest::BlockAndSize(hash_or_height)),
1271 Request::BlockHeader(hash_or_height) => Ok(ReadRequest::BlockHeader(hash_or_height)),
1272 Request::Transaction(tx_hash) => Ok(ReadRequest::Transaction(tx_hash)),
1273 Request::UnspentBestChainUtxo(outpoint) => {
1274 Ok(ReadRequest::UnspentBestChainUtxo(outpoint))
1275 }
1276
1277 Request::BlockLocator => Ok(ReadRequest::BlockLocator),
1278 Request::FindBlockHashes { known_blocks, stop } => {
1279 Ok(ReadRequest::FindBlockHashes { known_blocks, stop })
1280 }
1281 Request::FindBlockHeaders { known_blocks, stop } => {
1282 Ok(ReadRequest::FindBlockHeaders { known_blocks, stop })
1283 }
1284
1285 Request::CheckBestChainTipNullifiersAndAnchors(tx) => {
1286 Ok(ReadRequest::CheckBestChainTipNullifiersAndAnchors(tx))
1287 }
1288
1289 Request::CommitSemanticallyVerifiedBlock(_)
1290 | Request::CommitCheckpointVerifiedBlock(_)
1291 | Request::InvalidateBlock(_)
1292 | Request::ReconsiderBlock(_) => Err("ReadService does not write blocks"),
1293
1294 Request::AwaitUtxo(_) => Err("ReadService does not track pending UTXOs. \
1295 Manually convert the request to ReadRequest::AnyChainUtxo, \
1296 and handle pending UTXOs"),
1297
1298 Request::KnownBlock(_) => Err("ReadService does not track queued blocks"),
1299
1300 Request::CheckBlockProposalValidity(semantically_verified) => Ok(
1301 ReadRequest::CheckBlockProposalValidity(semantically_verified),
1302 ),
1303 }
1304 }
1305}