Skip to main content

zebra_state/
response.rs

1//! State [`tower::Service`] response types.
2
3use std::{
4    collections::{BTreeMap, HashMap, HashSet},
5    sync::Arc,
6};
7
8use chrono::{DateTime, Utc};
9
10use zebra_chain::{
11    amount::{Amount, NonNegative},
12    block::{self, Block, ChainHistoryMmrRootHash},
13    block_info::BlockInfo,
14    orchard, sapling,
15    serialization::DateTime32,
16    subtree::{NoteCommitmentSubtreeData, NoteCommitmentSubtreeIndex},
17    transaction::{self, Transaction},
18    transparent,
19    value_balance::ValueBalance,
20};
21
22use zebra_chain::work::difficulty::CompactDifficulty;
23
24// Allow *only* these unused imports, so that rustdoc link resolution
25// will work with inline links.
26#[allow(unused_imports)]
27use crate::{ReadRequest, Request};
28
29use crate::{
30    service::read::AddressUtxos, ContextuallyVerifiedBlock, NonFinalizedState, TransactionLocation,
31    WatchReceiver, MAX_BLOCK_REORG_HEIGHT,
32};
33
34#[cfg(test)]
35mod tests;
36
37/// Keeps early mining work on a block available while the block is being verified.
38///
39/// The state withdraws the work when the guard and all its clones are dropped.
40#[derive(Clone, Debug)]
41pub struct MiningCandidateGuard(pub(crate) tokio::sync::watch::Sender<()>);
42
43impl MiningCandidateGuard {
44    /// Returns a guard for tests, and a receiver that closes when the guard and its clones are
45    /// dropped.
46    #[cfg(any(test, feature = "proptest-impl"))]
47    pub fn new_for_tests() -> (Self, tokio::sync::watch::Receiver<()>) {
48        let (guard, verification) = tokio::sync::watch::channel(());
49
50        (Self(guard), verification)
51    }
52}
53
54impl PartialEq for MiningCandidateGuard {
55    fn eq(&self, other: &Self) -> bool {
56        self.0.same_channel(&other.0)
57    }
58}
59
60impl Eq for MiningCandidateGuard {}
61
62/// A subscription to publications and withdrawals of early mining work.
63///
64/// A default subscription never reports any changes.
65#[derive(Clone, Debug)]
66pub struct MiningCandidateChanges(
67    pub(crate) tokio::sync::watch::Receiver<Option<crate::service::MiningCandidate>>,
68);
69
70impl MiningCandidateChanges {
71    /// Returns a subscription for tests, and a function that changes what it reports: early
72    /// mining work with a parent hash and chain info is published, and `None` withdraws it.
73    #[cfg(any(test, feature = "proptest-impl"))]
74    pub fn new_for_tests() -> (
75        Self,
76        impl Fn(Option<(block::Hash, GetBlockTemplateChainInfo)>) + Send + Sync + 'static,
77    ) {
78        let (sender, receiver) = tokio::sync::watch::channel(None);
79        let set = move |candidate: Option<(block::Hash, GetBlockTemplateChainInfo)>| {
80            sender.send_replace(candidate.map(|(parent_hash, chain_info)| {
81                crate::service::MiningCandidate::new_for_tests(parent_hash, chain_info)
82            }));
83        };
84
85        (Self(receiver), set)
86    }
87
88    /// Marks the changes up to now as seen, so [`Self::changed`] only reports later ones.
89    pub fn mark_seen(&mut self) {
90        self.0.mark_unchanged();
91    }
92
93    /// Waits until early mining work is published or withdrawn.
94    ///
95    /// Never returns if the state has shut down, so it can be used in a `select!`.
96    pub async fn changed(&mut self) {
97        if self.0.changed().await.is_err() {
98            std::future::pending::<()>().await;
99        }
100    }
101
102    /// Waits until early mining work is published, ignoring withdrawals.
103    ///
104    /// Never returns if the state has shut down, so it can be used in a `select!`.
105    pub async fn published(&mut self) {
106        loop {
107            self.changed().await;
108
109            if self.0.borrow_and_update().is_some() {
110                return;
111            }
112        }
113    }
114}
115
116impl Default for MiningCandidateChanges {
117    fn default() -> Self {
118        Self(tokio::sync::watch::channel(None).1)
119    }
120}
121
122impl PartialEq for MiningCandidateChanges {
123    fn eq(&self, other: &Self) -> bool {
124        self.0.same_channel(&other.0)
125    }
126}
127
128impl Eq for MiningCandidateChanges {}
129
130#[derive(Clone, Debug, PartialEq, Eq)]
131/// A response to a [`StateService`](crate::service::StateService) [`Request`].
132pub enum Response {
133    /// Response to [`Request::MiningCandidate`].
134    ///
135    /// `None` if nothing is subscribed to early mining work, or if the state is already
136    /// computing early work on another block.
137    MiningCandidate(Option<MiningCandidateGuard>),
138
139    /// Response to [`Request::CommitSemanticallyVerifiedBlock`] and [`Request::CommitCheckpointVerifiedBlock`]
140    /// indicating that a block was successfully committed to the state.
141    Committed(block::Hash),
142
143    /// Response to [`Request::InvalidateBlock`] indicating that a block was found and
144    /// invalidated in the state.
145    Invalidated(block::Hash),
146
147    /// Response to [`Request::ReconsiderBlock`] indicating that a previously invalidated
148    /// block was reconsidered and re-committed to the non-finalized state. Contains a list
149    /// of block hashes that were reconsidered in the state and successfully re-committed.
150    Reconsidered(Vec<block::Hash>),
151
152    /// Response to [`Request::Depth`] with the depth of the specified block.
153    Depth(Option<u32>),
154
155    /// Response to [`Request::Tip`] with the current best chain tip.
156    //
157    // TODO: remove this request, and replace it with a call to
158    //       `LatestChainTip::best_tip_height_and_hash()`
159    Tip(Option<(block::Height, block::Hash)>),
160
161    /// Response to [`Request::BlockLocator`] with a block locator object.
162    BlockLocator(Vec<block::Hash>),
163
164    /// Response to [`Request::Transaction`] with the specified transaction.
165    Transaction(Option<Arc<Transaction>>),
166
167    /// Response to [`Request::AnyChainTransaction`] with the specified transaction.
168    AnyChainTransaction(Option<AnyTx>),
169
170    /// Response to [`Request::UnspentBestChainUtxo`] with the UTXO
171    UnspentBestChainUtxo(Option<transparent::Utxo>),
172
173    /// Response to [`Request::Block`] with the specified block.
174    Block(Option<Arc<Block>>),
175
176    /// Response to [`Request::BlockAndSize`] with the specified block and size.
177    BlockAndSize(Option<(Arc<Block>, usize)>),
178
179    /// The response to a `BlockHeader` request.
180    BlockHeader {
181        /// The header of the requested block
182        header: Arc<block::Header>,
183        /// The hash of the requested block
184        hash: block::Hash,
185        /// The height of the requested block
186        height: block::Height,
187        /// The hash of the next block after the requested block
188        next_block_hash: Option<block::Hash>,
189    },
190
191    /// The response to a `AwaitUtxo` request, from any non-finalized chains, finalized chain,
192    /// pending unverified blocks, or blocks received after the request was sent.
193    Utxo(transparent::Utxo),
194
195    /// The response to a `FindBlockHashes` request.
196    BlockHashes(Vec<block::Hash>),
197
198    /// The response to a `FindBlockHeaders` request.
199    BlockHeaders(Vec<block::CountedHeader>),
200
201    /// Response to [`Request::CheckBestChainTipNullifiersAndAnchors`].
202    ///
203    /// Does not check transparent UTXO inputs
204    ValidBestChainTipNullifiersAndAnchors,
205
206    /// Response to [`Request::BestChainNextMedianTimePast`].
207    /// Contains the median-time-past for the *next* block on the best chain.
208    BestChainNextMedianTimePast(DateTime32),
209
210    /// Response to [`Request::BestChainBlockHash`] with the specified block hash.
211    BlockHash(Option<block::Hash>),
212
213    /// Response to [`Request::KnownBlock`].
214    KnownBlock(Option<KnownBlock>),
215
216    /// Response to [`Request::CheckBlockProposalValidity`], with the result of validating the
217    /// proposal, which [`Request::CommitContextuallyVerifiedBlock`] can commit once it is solved.
218    ValidBlockProposal(Box<ContextuallyVerifiedBlock>),
219}
220
221#[derive(Clone, Debug, PartialEq, Eq)]
222/// An enum of block stores in the state where a block hash could be found.
223pub enum KnownBlock {
224    /// Block is in the finalized portion of the best chain.
225    Finalized,
226
227    /// Block is in the best chain.
228    BestChain,
229
230    /// Block is in a side chain.
231    SideChain,
232
233    /// Block is in a block write channel
234    WriteChannel,
235
236    /// Block is queued to be validated and committed, or rejected and dropped.
237    Queue,
238}
239
240impl std::fmt::Display for KnownBlock {
241    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
242        match self {
243            KnownBlock::Finalized => write!(f, "finalized state"),
244            KnownBlock::BestChain => write!(f, "best chain"),
245            KnownBlock::SideChain => write!(f, "side chain"),
246            KnownBlock::WriteChannel => write!(f, "block write channel"),
247            KnownBlock::Queue => write!(f, "validation/commit queue"),
248        }
249    }
250}
251
252/// Information about a transaction in any chain.
253#[derive(Clone, Debug, PartialEq, Eq)]
254pub enum AnyTx {
255    /// A transaction in the best chain.
256    Mined(MinedTx),
257    /// A transaction in a side chain, and the hash of the block it is in.
258    Side((Arc<Transaction>, block::Hash)),
259}
260
261impl From<AnyTx> for Arc<Transaction> {
262    fn from(any_tx: AnyTx) -> Self {
263        match any_tx {
264            AnyTx::Mined(mined_tx) => mined_tx.tx,
265            AnyTx::Side((tx, _)) => tx,
266        }
267    }
268}
269
270/// Information about a transaction in the best chain
271#[derive(Clone, Debug, PartialEq, Eq)]
272pub struct MinedTx {
273    /// The transaction.
274    pub tx: Arc<Transaction>,
275
276    /// The transaction height.
277    pub height: block::Height,
278
279    /// The number of confirmations for this transaction
280    /// (1 + depth of block the transaction was found in)
281    pub confirmations: u32,
282
283    /// The time of the block where the transaction was mined.
284    pub block_time: DateTime<Utc>,
285
286    /// The best-chain tip hash captured in the same state snapshot used to
287    /// compute `confirmations`.
288    ///
289    /// Callers that combine this response with other state queries should
290    /// pin those follow-up queries to this hash (or to the resolved block
291    /// hash for the transaction) rather than issuing a separate `Tip` /
292    /// `BestChainBlockHash` request, which would re-sample the chain and
293    /// can race with reorgs or new blocks. See issue #10550.
294    pub best_chain_tip_hash: block::Hash,
295}
296
297impl MinedTx {
298    /// Creates a new [`MinedTx`]
299    pub fn new(
300        tx: Arc<Transaction>,
301        height: block::Height,
302        confirmations: u32,
303        block_time: DateTime<Utc>,
304        best_chain_tip_hash: block::Hash,
305    ) -> Self {
306        Self {
307            tx,
308            height,
309            confirmations,
310            block_time,
311            best_chain_tip_hash,
312        }
313    }
314}
315
316/// How many non-finalized block references to buffer in [`NonFinalizedBlocksListener`] before blocking sends.
317///
318/// # Correctness
319///
320/// This should be large enough to typically avoid blocking the sender when the non-finalized state is full so
321/// that the [`NonFinalizedBlocksListener`] reliably receives updates whenever the non-finalized state changes.
322///
323/// If the buffer does fill, sends apply backpressure (the sender awaits a free slot) rather than
324/// dropping blocks, so the listener still receives every block once the consumer catches up.
325// `MAX_BLOCK_REORG_HEIGHT` is a small `u32` constant (the reorg limit), so widening it to `usize`
326// and doubling it cannot overflow on any supported platform.
327const NON_FINALIZED_STATE_CHANGE_BUFFER_SIZE: usize = 2 * MAX_BLOCK_REORG_HEIGHT as usize;
328
329/// A listener for changes in the non-finalized state.
330#[derive(Clone, Debug)]
331pub struct NonFinalizedBlocksListener(
332    pub Arc<tokio::sync::mpsc::Receiver<(zebra_chain::block::Hash, Arc<zebra_chain::block::Block>)>>,
333);
334
335impl NonFinalizedBlocksListener {
336    /// Sends the blocks in `non_finalized_state` that satisfy `take_cond` to `sender`, in
337    /// ascending height order.
338    ///
339    /// Walks each chain from its tip downwards, taking blocks while `take_cond` holds and stopping
340    /// at the first block that fails it, so it sends the blocks a listener hasn't been sent yet by
341    /// stopping at the first block it already has.
342    ///
343    /// Blocks below a fork point belong to every chain that forked there, so each block is only
344    /// sent once, as part of the highest-work chain that contains it.
345    ///
346    /// Returns an error if the receiver has been dropped.
347    async fn take_and_send_blocks<'a>(
348        sender: &tokio::sync::mpsc::Sender<(block::Hash, Arc<Block>)>,
349        non_finalized_state: &'a NonFinalizedState,
350        take_cond: impl Fn(&&ContextuallyVerifiedBlock) -> bool + Copy + 'a,
351    ) -> Result<(), tokio::sync::mpsc::error::SendError<(block::Hash, Arc<Block>)>> {
352        let new_blocks = non_finalized_state.chain_iter().flat_map(move |chain| {
353            // Take blocks from the chain in reverse height order until we reach a block the
354            // listener already has, then restore ascending height order.
355            let mut blocks: Vec<_> = chain
356                .blocks
357                .values()
358                .map(Arc::as_ref)
359                .rev()
360                .take_while(take_cond)
361                .collect();
362            blocks.reverse();
363            blocks
364        });
365
366        // Chains share every block below their fork point, so without this the shared blocks would
367        // be sent once per chain: up to `MAX_NON_FINALIZED_CHAIN_FORKS` copies of a chain that can
368        // be `MAX_BLOCK_REORG_HEIGHT` blocks long, which overflows the channel buffer and makes the
369        // listener wait on the consumer during an ordinary initial send. `chain_iter()` yields the
370        // highest-work chain first, so a fork's remaining blocks still follow the shared ancestors
371        // they build on.
372        let mut sent_hashes = HashSet::new();
373
374        for cv_block in new_blocks {
375            if !sent_hashes.insert(cv_block.hash) {
376                continue;
377            }
378
379            sender.send((cv_block.hash, cv_block.block.clone())).await?;
380        }
381
382        Ok(())
383    }
384
385    /// Spawns a task to listen for changes in the non-finalized state and sends any blocks in the non-finalized state
386    /// to the caller that have not already been sent.
387    ///
388    /// `known_chain_tips` holds the hashes of chain tips the caller already has. On the first send
389    /// only, each non-finalized chain is walked from its tip downwards and blocks are sent until a
390    /// hash in this set is reached, so any block at or below a known tip on the same chain is
391    /// skipped. If it is empty, every block currently in the non-finalized state is sent. After the
392    /// first send, those blocks are already tracked as sent, so later sends only forward blocks that
393    /// weren't in the previously seen non-finalized state.
394    ///
395    /// Returns a new instance of [`NonFinalizedBlocksListener`] for the caller to listen for new blocks in the non-finalized state.
396    pub fn spawn(
397        mut non_finalized_state_receiver: WatchReceiver<NonFinalizedState>,
398        known_chain_tips: HashSet<block::Hash>,
399    ) -> Self {
400        let (sender, receiver) = tokio::sync::mpsc::channel(NON_FINALIZED_STATE_CHANGE_BUFFER_SIZE);
401
402        tokio::spawn(async move {
403            // `prev_non_finalized_state` starts as the current non-finalized state. The first send
404            // below skips blocks at or below the caller's known chain tips; afterwards those blocks
405            // are already in `prev_non_finalized_state`, so later sends only need to check it.
406            let mut prev_non_finalized_state = non_finalized_state_receiver.cloned_watch_data();
407
408            // Send the blocks the caller is missing relative to its known chain tips. This checks
409            // `known_chain_tips` once; from here on those blocks are covered by the state check.
410            if Self::take_and_send_blocks(&sender, &prev_non_finalized_state, |b| {
411                !known_chain_tips.contains(&b.hash)
412            })
413            .await
414            .is_err()
415            {
416                tracing::debug!("non-finalized blocks receiver closed, ending task");
417                return;
418            }
419
420            // # Correctness
421            //
422            // This loop should check that the non-finalized state receiver has changed sooner
423            // than the non-finalized state could possibly have changed to avoid missing updates, so
424            // the logic here should be quicker than the contextual verification logic that precedes
425            // commits to the non-finalized state.
426            //
427            // See the `NON_FINALIZED_STATE_CHANGE_BUFFER_SIZE` documentation for more details.
428            loop {
429                let non_finalized_state = non_finalized_state_receiver.cloned_watch_data();
430
431                // Send blocks that weren't in the last seen copy of the non-finalized state. The
432                // caller's known tips are already covered by `prev_non_finalized_state`.
433                if Self::take_and_send_blocks(&sender, &non_finalized_state, |b| {
434                    !prev_non_finalized_state.any_chain_contains(&b.hash)
435                })
436                .await
437                .is_err()
438                {
439                    tracing::debug!("non-finalized blocks receiver closed, ending task");
440                    return;
441                }
442
443                prev_non_finalized_state = non_finalized_state;
444
445                // Wait for the next update to the non-finalized state.
446                if let Err(error) = non_finalized_state_receiver.changed().await {
447                    warn!(
448                        ?error,
449                        "non-finalized state receiver closed, is Zebra shutting down?"
450                    );
451                    break;
452                }
453            }
454        });
455
456        Self(Arc::new(receiver))
457    }
458
459    /// Consumes `self`, unwrapping the inner [`Arc`] and returning the non-finalized state change channel receiver.
460    ///
461    /// # Panics
462    ///
463    /// If the `Arc` has more than one strong reference, this will panic.
464    pub fn unwrap(
465        self,
466    ) -> tokio::sync::mpsc::Receiver<(zebra_chain::block::Hash, Arc<zebra_chain::block::Block>)>
467    {
468        Arc::try_unwrap(self.0).unwrap()
469    }
470}
471
472impl PartialEq for NonFinalizedBlocksListener {
473    fn eq(&self, other: &Self) -> bool {
474        Arc::ptr_eq(&self.0, &other.0)
475    }
476}
477
478impl Eq for NonFinalizedBlocksListener {}
479
480#[derive(Clone, Debug, PartialEq, Eq)]
481/// A response to a read-only
482/// [`ReadStateService`](crate::service::ReadStateService)'s [`ReadRequest`].
483pub enum ReadResponse {
484    /// Response to [`ReadRequest::UsageInfo`] with the current best chain tip.
485    UsageInfo(u64),
486
487    /// Response to [`ReadRequest::Tip`] with the current best chain tip.
488    Tip(Option<(block::Height, block::Hash)>),
489
490    /// Response to [`ReadRequest::TipPoolValues`] with
491    /// the current best chain tip and its [`ValueBalance`].
492    TipPoolValues {
493        /// The current best chain tip height.
494        tip_height: block::Height,
495        /// The current best chain tip hash.
496        tip_hash: block::Hash,
497        /// The value pool balance at the current best chain tip.
498        value_balance: ValueBalance<NonNegative>,
499    },
500
501    /// Response to [`ReadRequest::BlockInfo`] with
502    /// the block info after the specified block.
503    BlockInfo(Option<BlockInfo>),
504
505    /// Response to [`ReadRequest::Depth`] with the depth of the specified block.
506    Depth(Option<u32>),
507
508    /// Response to [`ReadRequest::Block`] with the specified block.
509    Block(Option<Arc<Block>>),
510
511    /// Response to [`ReadRequest::BlockAndSize`] with the specified block and
512    /// serialized size.
513    BlockAndSize(Option<(Arc<Block>, usize)>),
514
515    /// Response to [`ReadRequest::SpentOutputs`] with the outputs spent by the
516    /// non-coinbase inputs of the specified block, keyed by the spending
517    /// [`OutPoint`](transparent::OutPoint), or `None` if the block was not found.
518    ///
519    /// An outpoint whose spent output could not be found in the best chain is
520    /// omitted from the map.
521    SpentOutputs(Option<HashMap<transparent::OutPoint, transparent::Utxo>>),
522
523    /// The response to a `BlockHeader` request.
524    BlockHeader {
525        /// The header of the requested block
526        header: Arc<block::Header>,
527        /// The hash of the requested block
528        hash: block::Hash,
529        /// The height of the requested block
530        height: block::Height,
531        /// The hash of the next block after the requested block
532        next_block_hash: Option<block::Hash>,
533    },
534
535    /// Response to [`ReadRequest::Transaction`] with the specified transaction.
536    Transaction(Option<MinedTx>),
537
538    /// Response to [`Request::Transaction`] with the specified transaction.
539    AnyChainTransaction(Option<AnyTx>),
540
541    /// Response to [`ReadRequest::TransactionIdsForBlock`],
542    /// with an list of transaction hashes in block order,
543    /// or `None` if the block was not found.
544    TransactionIdsForBlock(Option<Arc<[transaction::Hash]>>),
545
546    /// Response to [`ReadRequest::AnyChainTransactionIdsForBlock`], with an list of
547    /// transaction hashes in block order and a flag indicating if the block is
548    /// in the best chain, or `None` if the block was not found.
549    AnyChainTransactionIdsForBlock(Option<(Arc<[transaction::Hash]>, bool)>),
550
551    /// Response to [`ReadRequest::SpendingTransactionId`],
552    /// with an list of transaction hashes in block order,
553    /// or `None` if the block was not found.
554    #[cfg(feature = "indexer")]
555    TransactionId(Option<transaction::Hash>),
556
557    /// Response to [`ReadRequest::BlockLocator`] with a block locator object.
558    BlockLocator(Vec<block::Hash>),
559
560    /// The response to a `FindBlockHashes` request.
561    BlockHashes(Vec<block::Hash>),
562
563    /// The response to a `FindBlockHeaders` request.
564    BlockHeaders(Vec<block::CountedHeader>),
565
566    /// The response to a `FindForkPoint` request.
567    /// Returns the height and hash of the fork point, or `None` if no locator entry is
568    /// on the best chain.
569    ForkPoint(Option<(block::Height, block::Hash)>),
570
571    /// The response to a `UnspentBestChainUtxo` request, from verified blocks in the
572    /// _best_ non-finalized chain, or the finalized chain.
573    UnspentBestChainUtxo(Option<transparent::Utxo>),
574
575    /// The response to an `AnyChainUtxo` request, from verified blocks in
576    /// _any_ non-finalized chain, or the finalized chain.
577    ///
578    /// This response is purely informational, there is no guarantee that
579    /// the UTXO remains unspent in the best chain.
580    AnyChainUtxo(Option<transparent::Utxo>),
581
582    /// Response to [`ReadRequest::SaplingTree`] with the specified Sapling note commitment tree.
583    SaplingTree(Option<Arc<sapling::tree::NoteCommitmentTree>>),
584
585    /// Response to [`ReadRequest::OrchardTree`] with the specified Orchard note commitment tree.
586    OrchardTree(Option<Arc<orchard::tree::NoteCommitmentTree>>),
587
588    /// Response to [`ReadRequest::IronwoodTree`] with the specified Ironwood note commitment tree.
589    IronwoodTree(Option<Arc<orchard::tree::NoteCommitmentTree>>),
590
591    /// Response to [`ReadRequest::SaplingSubtrees`] with the specified Sapling note commitment
592    /// subtrees.
593    SaplingSubtrees(
594        BTreeMap<NoteCommitmentSubtreeIndex, NoteCommitmentSubtreeData<sapling_crypto::Node>>,
595    ),
596
597    /// Response to [`ReadRequest::OrchardSubtrees`] with the specified Orchard note commitment
598    /// subtrees.
599    OrchardSubtrees(
600        BTreeMap<NoteCommitmentSubtreeIndex, NoteCommitmentSubtreeData<orchard::tree::Node>>,
601    ),
602
603    /// Response to [`ReadRequest::IronwoodSubtrees`] with the specified Ironwood note commitment
604    /// subtrees. Ironwood reuses the Orchard note type.
605    IronwoodSubtrees(
606        BTreeMap<NoteCommitmentSubtreeIndex, NoteCommitmentSubtreeData<orchard::tree::Node>>,
607    ),
608
609    /// Response to [`ReadRequest::AddressBalance`] with the total balance of the addresses,
610    /// and the total received funds, including change.
611    AddressBalance {
612        /// The total balance of the addresses.
613        balance: Amount<NonNegative>,
614        /// The total received funds in zatoshis, including change.
615        received: u64,
616    },
617
618    /// Response to [`ReadRequest::TransactionIdsByAddresses`]
619    /// with the obtained transaction ids, in the order they appear in blocks.
620    AddressesTransactionIds(BTreeMap<TransactionLocation, transaction::Hash>),
621
622    /// Response to [`ReadRequest::UtxosByAddresses`] with found utxos and transaction data.
623    AddressUtxos(AddressUtxos),
624
625    /// Response to [`ReadRequest::CheckBestChainTipNullifiersAndAnchors`].
626    ///
627    /// Does not check transparent UTXO inputs
628    ValidBestChainTipNullifiersAndAnchors,
629
630    /// Response to [`ReadRequest::BestChainNextMedianTimePast`].
631    /// Contains the median-time-past for the *next* block on the best chain.
632    BestChainNextMedianTimePast(DateTime32),
633
634    /// Response to [`ReadRequest::BestChainBlockHash`] with the specified block hash.
635    BlockHash(Option<block::Hash>),
636
637    /// Response to [`ReadRequest::ChainInfo`] with the state
638    /// information needed by the `getblocktemplate` RPC method.
639    ChainInfo(GetBlockTemplateChainInfo),
640
641    /// Response to [`ReadRequest::MiningCandidate`] with the state information needed to build
642    /// a block template on top of a block that is still being verified.
643    ///
644    /// Its chain value pools are empty, because they depend on unverified transactions.
645    MiningCandidate(Option<GetBlockTemplateChainInfo>),
646
647    /// Response to [`ReadRequest::MiningCandidateChanges`].
648    MiningCandidateChanges(MiningCandidateChanges),
649
650    /// Response to [`ReadRequest::SolutionRate`]
651    SolutionRate(Option<u128>),
652
653    /// Response to [`ReadRequest::CheckBlockProposalValidity`], with the result of validating
654    /// the proposal.
655    ValidBlockProposal(Box<ContextuallyVerifiedBlock>),
656
657    /// Response to [`ReadRequest::TipBlockSize`]
658    TipBlockSize(Option<usize>),
659
660    /// Successful response to [`ReadRequest::CheckBestTipHeader`].
661    ValidBestTipHeader,
662
663    /// Successful response to [`ReadRequest::CheckBestTipBlockCommitments`].
664    ValidBestTipBlockCommitments,
665
666    /// Response to [`ReadRequest::NonFinalizedBlocksListener`]
667    NonFinalizedBlocksListener(NonFinalizedBlocksListener),
668
669    /// Response to [`ReadRequest::IsTransparentOutputSpent`]
670    IsTransparentOutputSpent(bool),
671}
672
673/// A structure with the information needed from the state to build a `getblocktemplate` RPC response.
674#[derive(Clone, Debug, Eq, PartialEq)]
675pub struct GetBlockTemplateChainInfo {
676    // Data fetched directly from the state tip.
677    //
678    /// The current state tip height.
679    /// The block template for the candidate block has this hash as the previous block hash.
680    pub tip_hash: block::Hash,
681
682    /// The current state tip height.
683    /// The block template for the candidate block is the next block after this block.
684    /// Depends on the `tip_hash`.
685    pub tip_height: block::Height,
686
687    /// The FlyClient chain history root as of the end of the chain tip block.
688    /// Depends on the `tip_hash`.
689    pub chain_history_root: Option<ChainHistoryMmrRootHash>,
690
691    // Data derived from the state tip and recent blocks, and the current local clock.
692    //
693    /// The expected difficulty of the candidate block.
694    /// Depends on the `tip_hash`, and the local clock on testnet.
695    pub expected_difficulty: CompactDifficulty,
696
697    /// The current system time, adjusted to fit within `min_time` and `max_time`.
698    /// Always depends on the local clock and the `tip_hash`.
699    pub cur_time: DateTime32,
700
701    /// The mininimum time the miner can use in this block.
702    /// Depends on the `tip_hash`, and the local clock on testnet.
703    pub min_time: DateTime32,
704
705    /// The maximum time the miner can use in this block.
706    /// Depends on the `tip_hash`, and the local clock on testnet.
707    pub max_time: DateTime32,
708
709    /// The chain value pools after the tip block, which determine the candidate block's subsidy
710    /// once the [halving-preserving issuance ZIP][zip] is active.
711    /// Depends on the `tip_hash`.
712    ///
713    /// [zip]: https://zips.z.cash/zip-0237
714    pub chain_value_pools:
715        zebra_chain::value_balance::ValueBalance<zebra_chain::amount::NonNegative>,
716}
717
718/// Conversion from read-only [`ReadResponse`]s to read-write [`Response`]s.
719///
720/// Used to return read requests concurrently from the [`StateService`](crate::service::StateService).
721impl TryFrom<ReadResponse> for Response {
722    type Error = &'static str;
723
724    fn try_from(response: ReadResponse) -> Result<Response, Self::Error> {
725        match response {
726            ReadResponse::Tip(height_and_hash) => Ok(Response::Tip(height_and_hash)),
727            ReadResponse::Depth(depth) => Ok(Response::Depth(depth)),
728            ReadResponse::BestChainNextMedianTimePast(median_time_past) => Ok(Response::BestChainNextMedianTimePast(median_time_past)),
729            ReadResponse::BlockHash(hash) => Ok(Response::BlockHash(hash)),
730
731            ReadResponse::Block(block) => Ok(Response::Block(block)),
732            ReadResponse::BlockAndSize(block) => Ok(Response::BlockAndSize(block)),
733            ReadResponse::BlockHeader {
734                header,
735                hash,
736                height,
737                next_block_hash
738            } => Ok(Response::BlockHeader {
739                header,
740                hash,
741                height,
742                next_block_hash
743            }),
744            ReadResponse::Transaction(tx_info) => {
745                Ok(Response::Transaction(tx_info.map(|tx_info| tx_info.tx)))
746            }
747            ReadResponse::AnyChainTransaction(tx) => Ok(Response::AnyChainTransaction(tx)),
748            ReadResponse::UnspentBestChainUtxo(utxo) => Ok(Response::UnspentBestChainUtxo(utxo)),
749
750
751            ReadResponse::AnyChainUtxo(_) => Err("ReadService does not track pending UTXOs. \
752                                                  Manually unwrap the response, and handle pending UTXOs."),
753
754            ReadResponse::BlockLocator(hashes) => Ok(Response::BlockLocator(hashes)),
755            ReadResponse::BlockHashes(hashes) => Ok(Response::BlockHashes(hashes)),
756            ReadResponse::BlockHeaders(headers) => Ok(Response::BlockHeaders(headers)),
757
758            ReadResponse::ValidBestChainTipNullifiersAndAnchors => Ok(Response::ValidBestChainTipNullifiersAndAnchors),
759
760            ReadResponse::UsageInfo(_)
761            | ReadResponse::TipPoolValues { .. }
762            | ReadResponse::BlockInfo(_)
763            | ReadResponse::TransactionIdsForBlock(_)
764            | ReadResponse::SpentOutputs(_)
765            | ReadResponse::AnyChainTransactionIdsForBlock(_)
766            | ReadResponse::SaplingTree(_)
767            | ReadResponse::OrchardTree(_)
768            | ReadResponse::IronwoodTree(_)
769            | ReadResponse::SaplingSubtrees(_)
770            | ReadResponse::OrchardSubtrees(_)
771            | ReadResponse::IronwoodSubtrees(_)
772            | ReadResponse::AddressBalance { .. }
773            | ReadResponse::AddressesTransactionIds(_)
774            | ReadResponse::AddressUtxos(_)
775            | ReadResponse::ChainInfo(_)
776            | ReadResponse::MiningCandidate(_)
777            | ReadResponse::MiningCandidateChanges(_)
778            | ReadResponse::NonFinalizedBlocksListener(_)
779            | ReadResponse::IsTransparentOutputSpent(_)
780            | ReadResponse::ForkPoint(_) => {
781                Err("there is no corresponding Response for this ReadResponse")
782            }
783
784            #[cfg(feature = "indexer")]
785            ReadResponse::TransactionId(_) => Err("there is no corresponding Response for this ReadResponse"),
786
787            ReadResponse::ValidBlockProposal(block) => Ok(Response::ValidBlockProposal(block)),
788
789            ReadResponse::SolutionRate(_)
790            | ReadResponse::TipBlockSize(_)
791            | ReadResponse::ValidBestTipHeader
792            | ReadResponse::ValidBestTipBlockCommitments => {
793                Err("there is no corresponding Response for this ReadResponse")
794            }
795        }
796    }
797}