zebra/zebra-state/src/response.rs

289 lines
11 KiB
Rust
Raw Normal View History

//! State [`tower::Service`] response types.
use std::{collections::BTreeMap, sync::Arc};
use zebra_chain::{
feat(rpc): Implement `getaddressbalance` RPC (#4138) * Add `Amount::serialize_as_string` helper method A helper method that makes it easier to serialize an `Amount` as a string. This is needed for the response type of the `getaccountbalance` RPC. * Implement state service call for address balance Add `Read{Request,Response}::AddressBalance` variants and implement the handler that calls the query function. * Create an `AddressBalance` response type Only contains the `balance` field which is needed by `lightwalletd`. That field is serialized as a string, following the RPC specification. * Implement `get_address_balance` RPC Query the read-only state service for the information, and wrap it in an `AddressBalance` response type so that it is serialized correctly. * Run `rustfmt` inside `proptest!` block Fix some minor formatting details. * Test `get_address_balance` with valid addresses Check that the RPC leads to a query to the mocked state service for a balance amount. * Test `get_address_balance` with invalid addresses An error message should be returned by the RPC. * Rename metric to `address_balance` Keep it consistent with how it's named in other places. Co-authored-by: teor <teor@riseup.net> * Revert "Add `Amount::serialize_as_string` helper method" This reverts commit 01b432e3d2ac2313a90d55d06b3fa855c0b71330. * Serialize amount as an integer This is different from what the documentation says, but it's what lightwalletd expects. * Add reference to RPC documentation Make sure it is linked to for easy access. * Create an `AddressStrings` type To be used as the input for the `get_address_balance` RPC method. * Use `AddressStrings` in `get_address_balance` RPC Fix the input parameter so that the list of address strings is placed inside a JSON map. * Update property tests to use `AddressStrings` Make sure the proper input type is created. Co-authored-by: teor <teor@riseup.net>
2022-04-20 11:27:00 -07:00
amount::{Amount, NonNegative},
block::{self, Block},
feat(rpc): Implement `z_gettreestate` RPC (#3990) * Impl the elementary structure of the `z_gettreestate` RPC * Fix merging bugs * Fix a merge bug * Fix a merge bug * Move a derive attribute Co-authored-by: teor <teor@riseup.net> * Clarify the support of negative heights * Add Orchard note commitment trees to the response * Add the time to the response * Finalize the `z_gettreestate` RPC * Add a note that verified blocks have coinbase height * Refactor `from_str` for `HashOrHeight` * Fix a mistake in the docs Co-authored-by: teor <teor@riseup.net> * Clarify request types Co-authored-by: teor <teor@riseup.net> * Simplify `hash_or_height` conversion to height Co-authored-by: teor <teor@riseup.net> * Add a TODO about optimization Co-authored-by: teor <teor@riseup.net> * Add a doc comment * Make sure Sapling & Orchard trees don't get mixed up * Serialize Sapling commitment trees * Refactor some comments * Serialize Orchard commitment trees * Serialize block heights * Simplify the serialization of commitment trees * Remove the block time from the RPC response * Simplify the serialization of block heights * Put Sapling & Orchard requests together * Remove a redundant TODO * Add block times to the RPC response * Derive `Clone, Debug, Eq, PartialEq` for `GetTreestate` Co-authored-by: teor <teor@riseup.net> * Derive `Clone`, `Debug`, `Eq` and `PartialEq` for `SerializedTree` * Document the fields of `GetTreestate` * Skip the serialization of empty trees This ensures compatibility with `zcashd` in the `z_gettreestate` RPC. * Document the `impl` of `merkle_tree::Hashable` for nodes * Make the structure of the JSON response consistent with `zcashd` * Derive `Eq` for nodes Co-authored-by: teor <teor@riseup.net> * Convert Sapling commitment trees to a format compatible with zcashd * Refactor the conversion of Sapling commitment trees * Refactor some comments * Refactor comments * Add a description of the conversion Co-authored-by: Conrado Gouvea <conrado@zfnd.org> * Fix comment indenting * Document the conversion between the dense and sparse formats Co-authored-by: teor <teor@riseup.net> Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com> Co-authored-by: Conrado Gouvea <conrado@zfnd.org>
2022-05-12 00:00:12 -07:00
orchard, sapling,
serialization::DateTime32,
transaction::{self, Transaction},
transparent,
};
#[cfg(feature = "getblocktemplate-rpcs")]
use zebra_chain::work::difficulty::CompactDifficulty;
// Allow *only* these unused imports, so that rustdoc link resolution
// will work with inline links.
#[allow(unused_imports)]
use crate::{ReadRequest, Request};
use crate::{service::read::AddressUtxos, TransactionLocation};
#[derive(Clone, Debug, PartialEq, Eq)]
/// A response to a [`StateService`](crate::service::StateService) [`Request`].
pub enum Response {
/// Response to [`Request::CommitBlock`] indicating that a block was
/// successfully committed to the state.
Committed(block::Hash),
/// Response to [`Request::Depth`] with the depth of the specified block.
Depth(Option<u32>),
/// Response to [`Request::Tip`] with the current best chain tip.
Tip(Option<(block::Height, block::Hash)>),
/// Response to [`Request::BlockLocator`] with a block locator object.
BlockLocator(Vec<block::Hash>),
/// Response to [`Request::Transaction`] with the specified transaction.
Transaction(Option<Arc<Transaction>>),
/// Response to [`Request::UnspentBestChainUtxo`] with the UTXO
UnspentBestChainUtxo(Option<transparent::Utxo>),
/// Response to [`Request::Block`] with the specified block.
Block(Option<Arc<Block>>),
/// The response to a `AwaitUtxo` request, from any non-finalized chains, finalized chain,
/// pending unverified blocks, or blocks received after the request was sent.
Utxo(transparent::Utxo),
/// The response to a `FindBlockHashes` request.
BlockHashes(Vec<block::Hash>),
/// The response to a `FindBlockHeaders` request.
BlockHeaders(Vec<block::CountedHeader>),
change(mempool): Contextually validates mempool transactions in best chain (#5716) * updates comments * adds check nullifier no dup fns for transactions * Adds: - check::anchors fn for tx iter - TODO comments for unifying nullifiers and anchors checks - new state request Updates unknown anchor errors to accomodate tx-only check Calls new state fn from transaction verifier * updates check::anchors fns to use transactions updates TransactionContextualValidity request to check sprout anchors adds comment mentioning TransactionContextualValidity ignores UTXOs * conditions new state req call on is_mempool updates tests * fix doc link / lint error * checks for duplicate nullifiers with closures * Update zebra-state/src/service/check/nullifier.rs Co-authored-by: teor <teor@riseup.net> * documents find_duplicate_nullifier params moves if let statement into for loop * renames new state req/res * asserts correct response variant in tx verifier * adds CheckBestChainTipShieldedSpends call in tx verifier to async checks * re-adds tracing instrumentation to check::anchors fn renames transaction_in_state to transaction_in_chain * adds block/tx wrapper fns for anchors checks * uses UnminedTx instead of transaction.hash() deletes broken test * updates new state req/res name * updates tests and uses par_iter for anchors checks * Updates check::anchors pub fn docs. * Adds: - comments / docs - a TransactionError variant for ValidateContextError * Apply suggestions from code review Co-authored-by: teor <teor@riseup.net> * moves downcast to From impl rustfmt * moves the ValidateContextError into an Arc updates comments and naming * leaves par_iter for another PR * puts io::Error in an Arc * updates anchors tests to call tx_anchors check * updates tests to call tx_no_duplicates_in_chain slightly improves formatting * Update zebra-consensus/src/error.rs Co-authored-by: teor <teor@riseup.net> * moves Arc from HistoryError to ValidateContextError Co-authored-by: teor <teor@riseup.net>
2022-11-29 20:40:15 -08:00
/// Response to [`Request::CheckBestChainTipNullifiersAndAnchors`].
///
/// Does not check transparent UTXO inputs
ValidBestChainTipNullifiersAndAnchors,
change(rpc): Add proposal capability to getblocktemplate (#5870) * adds ValidateBlock request to state * adds `Request` enum in block verifier skips solution check for BlockProposal requests calls CheckBlockValidity instead of Commit block for BlockProposal requests * uses new Request in references to chain verifier * adds getblocktemplate proposal mode response type * makes getblocktemplate-rpcs feature in zebra-consensus select getblocktemplate-rpcs in zebra-state * Adds PR review revisions * adds info log in CheckBlockProposalValidity * Reverts replacement of match statement * adds `GetBlockTemplate::capabilities` fn * conditions calling checkpoint verifier on !request.is_proposal * updates references to validate_and_commit_non_finalized * adds snapshot test, updates test vectors * adds `should_count_metrics` to NonFinalizedState * Returns an error from chain verifier for block proposal requests below checkpoint height adds feature flags * adds "proposal" to GET_BLOCK_TEMPLATE_CAPABILITIES_FIELD * adds back block::Request to zebra-consensus lib * updates snapshots * Removes unnecessary network arg * skips req in tracing intstrument for read state * Moves out block proposal validation to its own fn * corrects `difficulty_threshold_is_valid` docs adds/fixes some comments, adds TODOs general cleanup from a self-review. * Update zebra-state/src/service.rs * Apply suggestions from code review Co-authored-by: teor <teor@riseup.net> * Update zebra-rpc/src/methods/get_block_template_rpcs.rs Co-authored-by: teor <teor@riseup.net> * check best chain tip * Update zebra-state/src/service.rs Co-authored-by: teor <teor@riseup.net> * Applies cleanup suggestions from code review Co-authored-by: teor <teor@riseup.net> Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2023-01-11 15:39:51 -08:00
/// Response to [`Request::BestChainNextMedianTimePast`].
/// Contains the median-time-past for the *next* block on the best chain.
BestChainNextMedianTimePast(DateTime32),
/// Response to [`Request::BestChainBlockHash`](Request::BestChainBlockHash) with the
/// specified block hash.
BlockHash(Option<block::Hash>),
/// Response to [`Request::KnownBlock`].
KnownBlock(Option<KnownBlock>),
change(rpc): Add proposal capability to getblocktemplate (#5870) * adds ValidateBlock request to state * adds `Request` enum in block verifier skips solution check for BlockProposal requests calls CheckBlockValidity instead of Commit block for BlockProposal requests * uses new Request in references to chain verifier * adds getblocktemplate proposal mode response type * makes getblocktemplate-rpcs feature in zebra-consensus select getblocktemplate-rpcs in zebra-state * Adds PR review revisions * adds info log in CheckBlockProposalValidity * Reverts replacement of match statement * adds `GetBlockTemplate::capabilities` fn * conditions calling checkpoint verifier on !request.is_proposal * updates references to validate_and_commit_non_finalized * adds snapshot test, updates test vectors * adds `should_count_metrics` to NonFinalizedState * Returns an error from chain verifier for block proposal requests below checkpoint height adds feature flags * adds "proposal" to GET_BLOCK_TEMPLATE_CAPABILITIES_FIELD * adds back block::Request to zebra-consensus lib * updates snapshots * Removes unnecessary network arg * skips req in tracing intstrument for read state * Moves out block proposal validation to its own fn * corrects `difficulty_threshold_is_valid` docs adds/fixes some comments, adds TODOs general cleanup from a self-review. * Update zebra-state/src/service.rs * Apply suggestions from code review Co-authored-by: teor <teor@riseup.net> * Update zebra-rpc/src/methods/get_block_template_rpcs.rs Co-authored-by: teor <teor@riseup.net> * check best chain tip * Update zebra-state/src/service.rs Co-authored-by: teor <teor@riseup.net> * Applies cleanup suggestions from code review Co-authored-by: teor <teor@riseup.net> Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2023-01-11 15:39:51 -08:00
#[cfg(feature = "getblocktemplate-rpcs")]
/// Response to [`Request::CheckBlockProposalValidity`](Request::CheckBlockProposalValidity)
change(rpc): Add proposal capability to getblocktemplate (#5870) * adds ValidateBlock request to state * adds `Request` enum in block verifier skips solution check for BlockProposal requests calls CheckBlockValidity instead of Commit block for BlockProposal requests * uses new Request in references to chain verifier * adds getblocktemplate proposal mode response type * makes getblocktemplate-rpcs feature in zebra-consensus select getblocktemplate-rpcs in zebra-state * Adds PR review revisions * adds info log in CheckBlockProposalValidity * Reverts replacement of match statement * adds `GetBlockTemplate::capabilities` fn * conditions calling checkpoint verifier on !request.is_proposal * updates references to validate_and_commit_non_finalized * adds snapshot test, updates test vectors * adds `should_count_metrics` to NonFinalizedState * Returns an error from chain verifier for block proposal requests below checkpoint height adds feature flags * adds "proposal" to GET_BLOCK_TEMPLATE_CAPABILITIES_FIELD * adds back block::Request to zebra-consensus lib * updates snapshots * Removes unnecessary network arg * skips req in tracing intstrument for read state * Moves out block proposal validation to its own fn * corrects `difficulty_threshold_is_valid` docs adds/fixes some comments, adds TODOs general cleanup from a self-review. * Update zebra-state/src/service.rs * Apply suggestions from code review Co-authored-by: teor <teor@riseup.net> * Update zebra-rpc/src/methods/get_block_template_rpcs.rs Co-authored-by: teor <teor@riseup.net> * check best chain tip * Update zebra-state/src/service.rs Co-authored-by: teor <teor@riseup.net> * Applies cleanup suggestions from code review Co-authored-by: teor <teor@riseup.net> Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2023-01-11 15:39:51 -08:00
ValidBlockProposal,
}
#[derive(Clone, Debug, PartialEq, Eq)]
/// An enum of block stores in the state where a block hash could be found.
pub enum KnownBlock {
/// Block is in the best chain.
BestChain,
/// Block is in a side chain.
SideChain,
/// Block is queued to be validated and committed, or rejected and dropped.
Queue,
}
/// Information about a transaction in the best chain
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MinedTx {
/// The transaction.
pub tx: Arc<Transaction>,
/// The transaction height.
pub height: block::Height,
/// The number of confirmations for this transaction
/// (1 + depth of block the transaction was found in)
pub confirmations: u32,
}
impl MinedTx {
/// Creates a new [`MinedTx`]
pub fn new(tx: Arc<Transaction>, height: block::Height, confirmations: u32) -> Self {
Self {
tx,
height,
confirmations,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
/// A response to a read-only
/// [`ReadStateService`](crate::service::ReadStateService)'s
/// [`ReadRequest`](ReadRequest).
pub enum ReadResponse {
/// Response to [`ReadRequest::Tip`] with the current best chain tip.
Tip(Option<(block::Height, block::Hash)>),
/// Response to [`ReadRequest::Depth`] with the depth of the specified block.
Depth(Option<u32>),
/// Response to [`ReadRequest::Block`] with the specified block.
Block(Option<Arc<Block>>),
/// Response to [`ReadRequest::Transaction`] with the specified transaction.
Transaction(Option<MinedTx>),
/// Response to [`ReadRequest::TransactionIdsForBlock`],
/// with an list of transaction hashes in block order,
/// or `None` if the block was not found.
TransactionIdsForBlock(Option<Arc<[transaction::Hash]>>),
/// Response to [`ReadRequest::BlockLocator`] with a block locator object.
BlockLocator(Vec<block::Hash>),
/// The response to a `FindBlockHashes` request.
BlockHashes(Vec<block::Hash>),
/// The response to a `FindBlockHeaders` request.
BlockHeaders(Vec<block::CountedHeader>),
/// The response to a `UnspentBestChainUtxo` request, from verified blocks in the
/// _best_ non-finalized chain, or the finalized chain.
UnspentBestChainUtxo(Option<transparent::Utxo>),
/// The response to an `AnyChainUtxo` request, from verified blocks in
/// _any_ non-finalized chain, or the finalized chain.
///
/// This response is purely informational, there is no guarantee that
/// the UTXO remains unspent in the best chain.
AnyChainUtxo(Option<transparent::Utxo>),
/// Response to [`ReadRequest::SaplingTree`] with the specified Sapling note commitment tree.
feat(rpc): Implement `z_gettreestate` RPC (#3990) * Impl the elementary structure of the `z_gettreestate` RPC * Fix merging bugs * Fix a merge bug * Fix a merge bug * Move a derive attribute Co-authored-by: teor <teor@riseup.net> * Clarify the support of negative heights * Add Orchard note commitment trees to the response * Add the time to the response * Finalize the `z_gettreestate` RPC * Add a note that verified blocks have coinbase height * Refactor `from_str` for `HashOrHeight` * Fix a mistake in the docs Co-authored-by: teor <teor@riseup.net> * Clarify request types Co-authored-by: teor <teor@riseup.net> * Simplify `hash_or_height` conversion to height Co-authored-by: teor <teor@riseup.net> * Add a TODO about optimization Co-authored-by: teor <teor@riseup.net> * Add a doc comment * Make sure Sapling & Orchard trees don't get mixed up * Serialize Sapling commitment trees * Refactor some comments * Serialize Orchard commitment trees * Serialize block heights * Simplify the serialization of commitment trees * Remove the block time from the RPC response * Simplify the serialization of block heights * Put Sapling & Orchard requests together * Remove a redundant TODO * Add block times to the RPC response * Derive `Clone, Debug, Eq, PartialEq` for `GetTreestate` Co-authored-by: teor <teor@riseup.net> * Derive `Clone`, `Debug`, `Eq` and `PartialEq` for `SerializedTree` * Document the fields of `GetTreestate` * Skip the serialization of empty trees This ensures compatibility with `zcashd` in the `z_gettreestate` RPC. * Document the `impl` of `merkle_tree::Hashable` for nodes * Make the structure of the JSON response consistent with `zcashd` * Derive `Eq` for nodes Co-authored-by: teor <teor@riseup.net> * Convert Sapling commitment trees to a format compatible with zcashd * Refactor the conversion of Sapling commitment trees * Refactor some comments * Refactor comments * Add a description of the conversion Co-authored-by: Conrado Gouvea <conrado@zfnd.org> * Fix comment indenting * Document the conversion between the dense and sparse formats Co-authored-by: teor <teor@riseup.net> Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com> Co-authored-by: Conrado Gouvea <conrado@zfnd.org>
2022-05-12 00:00:12 -07:00
SaplingTree(Option<Arc<sapling::tree::NoteCommitmentTree>>),
/// Response to [`ReadRequest::OrchardTree`] with the specified Orchard note commitment tree.
feat(rpc): Implement `z_gettreestate` RPC (#3990) * Impl the elementary structure of the `z_gettreestate` RPC * Fix merging bugs * Fix a merge bug * Fix a merge bug * Move a derive attribute Co-authored-by: teor <teor@riseup.net> * Clarify the support of negative heights * Add Orchard note commitment trees to the response * Add the time to the response * Finalize the `z_gettreestate` RPC * Add a note that verified blocks have coinbase height * Refactor `from_str` for `HashOrHeight` * Fix a mistake in the docs Co-authored-by: teor <teor@riseup.net> * Clarify request types Co-authored-by: teor <teor@riseup.net> * Simplify `hash_or_height` conversion to height Co-authored-by: teor <teor@riseup.net> * Add a TODO about optimization Co-authored-by: teor <teor@riseup.net> * Add a doc comment * Make sure Sapling & Orchard trees don't get mixed up * Serialize Sapling commitment trees * Refactor some comments * Serialize Orchard commitment trees * Serialize block heights * Simplify the serialization of commitment trees * Remove the block time from the RPC response * Simplify the serialization of block heights * Put Sapling & Orchard requests together * Remove a redundant TODO * Add block times to the RPC response * Derive `Clone, Debug, Eq, PartialEq` for `GetTreestate` Co-authored-by: teor <teor@riseup.net> * Derive `Clone`, `Debug`, `Eq` and `PartialEq` for `SerializedTree` * Document the fields of `GetTreestate` * Skip the serialization of empty trees This ensures compatibility with `zcashd` in the `z_gettreestate` RPC. * Document the `impl` of `merkle_tree::Hashable` for nodes * Make the structure of the JSON response consistent with `zcashd` * Derive `Eq` for nodes Co-authored-by: teor <teor@riseup.net> * Convert Sapling commitment trees to a format compatible with zcashd * Refactor the conversion of Sapling commitment trees * Refactor some comments * Refactor comments * Add a description of the conversion Co-authored-by: Conrado Gouvea <conrado@zfnd.org> * Fix comment indenting * Document the conversion between the dense and sparse formats Co-authored-by: teor <teor@riseup.net> Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com> Co-authored-by: Conrado Gouvea <conrado@zfnd.org>
2022-05-12 00:00:12 -07:00
OrchardTree(Option<Arc<orchard::tree::NoteCommitmentTree>>),
/// Response to [`ReadRequest::AddressBalance`] with the total balance of the addresses.
feat(rpc): Implement `getaddressbalance` RPC (#4138) * Add `Amount::serialize_as_string` helper method A helper method that makes it easier to serialize an `Amount` as a string. This is needed for the response type of the `getaccountbalance` RPC. * Implement state service call for address balance Add `Read{Request,Response}::AddressBalance` variants and implement the handler that calls the query function. * Create an `AddressBalance` response type Only contains the `balance` field which is needed by `lightwalletd`. That field is serialized as a string, following the RPC specification. * Implement `get_address_balance` RPC Query the read-only state service for the information, and wrap it in an `AddressBalance` response type so that it is serialized correctly. * Run `rustfmt` inside `proptest!` block Fix some minor formatting details. * Test `get_address_balance` with valid addresses Check that the RPC leads to a query to the mocked state service for a balance amount. * Test `get_address_balance` with invalid addresses An error message should be returned by the RPC. * Rename metric to `address_balance` Keep it consistent with how it's named in other places. Co-authored-by: teor <teor@riseup.net> * Revert "Add `Amount::serialize_as_string` helper method" This reverts commit 01b432e3d2ac2313a90d55d06b3fa855c0b71330. * Serialize amount as an integer This is different from what the documentation says, but it's what lightwalletd expects. * Add reference to RPC documentation Make sure it is linked to for easy access. * Create an `AddressStrings` type To be used as the input for the `get_address_balance` RPC method. * Use `AddressStrings` in `get_address_balance` RPC Fix the input parameter so that the list of address strings is placed inside a JSON map. * Update property tests to use `AddressStrings` Make sure the proper input type is created. Co-authored-by: teor <teor@riseup.net>
2022-04-20 11:27:00 -07:00
AddressBalance(Amount<NonNegative>),
/// Response to [`ReadRequest::TransactionIdsByAddresses`]
/// with the obtained transaction ids, in the order they appear in blocks.
AddressesTransactionIds(BTreeMap<TransactionLocation, transaction::Hash>),
/// Response to [`ReadRequest::UtxosByAddresses`] with found utxos and transaction data.
AddressUtxos(AddressUtxos),
change(mempool): Contextually validates mempool transactions in best chain (#5716) * updates comments * adds check nullifier no dup fns for transactions * Adds: - check::anchors fn for tx iter - TODO comments for unifying nullifiers and anchors checks - new state request Updates unknown anchor errors to accomodate tx-only check Calls new state fn from transaction verifier * updates check::anchors fns to use transactions updates TransactionContextualValidity request to check sprout anchors adds comment mentioning TransactionContextualValidity ignores UTXOs * conditions new state req call on is_mempool updates tests * fix doc link / lint error * checks for duplicate nullifiers with closures * Update zebra-state/src/service/check/nullifier.rs Co-authored-by: teor <teor@riseup.net> * documents find_duplicate_nullifier params moves if let statement into for loop * renames new state req/res * asserts correct response variant in tx verifier * adds CheckBestChainTipShieldedSpends call in tx verifier to async checks * re-adds tracing instrumentation to check::anchors fn renames transaction_in_state to transaction_in_chain * adds block/tx wrapper fns for anchors checks * uses UnminedTx instead of transaction.hash() deletes broken test * updates new state req/res name * updates tests and uses par_iter for anchors checks * Updates check::anchors pub fn docs. * Adds: - comments / docs - a TransactionError variant for ValidateContextError * Apply suggestions from code review Co-authored-by: teor <teor@riseup.net> * moves downcast to From impl rustfmt * moves the ValidateContextError into an Arc updates comments and naming * leaves par_iter for another PR * puts io::Error in an Arc * updates anchors tests to call tx_anchors check * updates tests to call tx_no_duplicates_in_chain slightly improves formatting * Update zebra-consensus/src/error.rs Co-authored-by: teor <teor@riseup.net> * moves Arc from HistoryError to ValidateContextError Co-authored-by: teor <teor@riseup.net>
2022-11-29 20:40:15 -08:00
/// Response to [`ReadRequest::CheckBestChainTipNullifiersAndAnchors`].
///
/// Does not check transparent UTXO inputs
ValidBestChainTipNullifiersAndAnchors,
/// Response to [`ReadRequest::BestChainNextMedianTimePast`].
/// Contains the median-time-past for the *next* block on the best chain.
BestChainNextMedianTimePast(DateTime32),
/// Response to [`ReadRequest::BestChainBlockHash`](ReadRequest::BestChainBlockHash) with the
/// specified block hash.
BlockHash(Option<block::Hash>),
#[cfg(feature = "getblocktemplate-rpcs")]
/// Response to [`ReadRequest::ChainInfo`](ReadRequest::ChainInfo) with the state
/// information needed by the `getblocktemplate` RPC method.
ChainInfo(GetBlockTemplateChainInfo),
#[cfg(feature = "getblocktemplate-rpcs")]
/// Response to [`ReadRequest::SolutionRate`](ReadRequest::SolutionRate)
SolutionRate(Option<u128>),
change(rpc): Add proposal capability to getblocktemplate (#5870) * adds ValidateBlock request to state * adds `Request` enum in block verifier skips solution check for BlockProposal requests calls CheckBlockValidity instead of Commit block for BlockProposal requests * uses new Request in references to chain verifier * adds getblocktemplate proposal mode response type * makes getblocktemplate-rpcs feature in zebra-consensus select getblocktemplate-rpcs in zebra-state * Adds PR review revisions * adds info log in CheckBlockProposalValidity * Reverts replacement of match statement * adds `GetBlockTemplate::capabilities` fn * conditions calling checkpoint verifier on !request.is_proposal * updates references to validate_and_commit_non_finalized * adds snapshot test, updates test vectors * adds `should_count_metrics` to NonFinalizedState * Returns an error from chain verifier for block proposal requests below checkpoint height adds feature flags * adds "proposal" to GET_BLOCK_TEMPLATE_CAPABILITIES_FIELD * adds back block::Request to zebra-consensus lib * updates snapshots * Removes unnecessary network arg * skips req in tracing intstrument for read state * Moves out block proposal validation to its own fn * corrects `difficulty_threshold_is_valid` docs adds/fixes some comments, adds TODOs general cleanup from a self-review. * Update zebra-state/src/service.rs * Apply suggestions from code review Co-authored-by: teor <teor@riseup.net> * Update zebra-rpc/src/methods/get_block_template_rpcs.rs Co-authored-by: teor <teor@riseup.net> * check best chain tip * Update zebra-state/src/service.rs Co-authored-by: teor <teor@riseup.net> * Applies cleanup suggestions from code review Co-authored-by: teor <teor@riseup.net> Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2023-01-11 15:39:51 -08:00
#[cfg(feature = "getblocktemplate-rpcs")]
/// Response to [`ReadRequest::CheckBlockProposalValidity`](ReadRequest::CheckBlockProposalValidity)
change(rpc): Add proposal capability to getblocktemplate (#5870) * adds ValidateBlock request to state * adds `Request` enum in block verifier skips solution check for BlockProposal requests calls CheckBlockValidity instead of Commit block for BlockProposal requests * uses new Request in references to chain verifier * adds getblocktemplate proposal mode response type * makes getblocktemplate-rpcs feature in zebra-consensus select getblocktemplate-rpcs in zebra-state * Adds PR review revisions * adds info log in CheckBlockProposalValidity * Reverts replacement of match statement * adds `GetBlockTemplate::capabilities` fn * conditions calling checkpoint verifier on !request.is_proposal * updates references to validate_and_commit_non_finalized * adds snapshot test, updates test vectors * adds `should_count_metrics` to NonFinalizedState * Returns an error from chain verifier for block proposal requests below checkpoint height adds feature flags * adds "proposal" to GET_BLOCK_TEMPLATE_CAPABILITIES_FIELD * adds back block::Request to zebra-consensus lib * updates snapshots * Removes unnecessary network arg * skips req in tracing intstrument for read state * Moves out block proposal validation to its own fn * corrects `difficulty_threshold_is_valid` docs adds/fixes some comments, adds TODOs general cleanup from a self-review. * Update zebra-state/src/service.rs * Apply suggestions from code review Co-authored-by: teor <teor@riseup.net> * Update zebra-rpc/src/methods/get_block_template_rpcs.rs Co-authored-by: teor <teor@riseup.net> * check best chain tip * Update zebra-state/src/service.rs Co-authored-by: teor <teor@riseup.net> * Applies cleanup suggestions from code review Co-authored-by: teor <teor@riseup.net> Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
2023-01-11 15:39:51 -08:00
ValidBlockProposal,
}
/// A structure with the information needed from the state to build a `getblocktemplate` RPC response.
#[cfg(feature = "getblocktemplate-rpcs")]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GetBlockTemplateChainInfo {
// Data fetched directly from the state tip.
//
/// The current state tip height.
/// The block template for the candidate block has this hash as the previous block hash.
pub tip_hash: block::Hash,
/// The current state tip height.
/// The block template for the candidate block is the next block after this block.
/// Depends on the `tip_hash`.
pub tip_height: block::Height,
/// The history tree of the current best chain.
/// Depends on the `tip_hash`.
pub history_tree: Arc<zebra_chain::history_tree::HistoryTree>,
// Data derived from the state tip and recent blocks, and the current local clock.
//
/// The expected difficulty of the candidate block.
/// Depends on the `tip_hash`, and the local clock on testnet.
pub expected_difficulty: CompactDifficulty,
/// The current system time, adjusted to fit within `min_time` and `max_time`.
/// Always depends on the local clock and the `tip_hash`.
pub cur_time: DateTime32,
/// The mininimum time the miner can use in this block.
/// Depends on the `tip_hash`, and the local clock on testnet.
pub min_time: DateTime32,
/// The maximum time the miner can use in this block.
/// Depends on the `tip_hash`, and the local clock on testnet.
pub max_time: DateTime32,
}
/// Conversion from read-only [`ReadResponse`]s to read-write [`Response`]s.
///
/// Used to return read requests concurrently from the [`StateService`](crate::service::StateService).
impl TryFrom<ReadResponse> for Response {
type Error = &'static str;
fn try_from(response: ReadResponse) -> Result<Response, Self::Error> {
match response {
ReadResponse::Tip(height_and_hash) => Ok(Response::Tip(height_and_hash)),
ReadResponse::Depth(depth) => Ok(Response::Depth(depth)),
ReadResponse::BestChainNextMedianTimePast(median_time_past) => Ok(Response::BestChainNextMedianTimePast(median_time_past)),
ReadResponse::BlockHash(hash) => Ok(Response::BlockHash(hash)),
ReadResponse::Block(block) => Ok(Response::Block(block)),
ReadResponse::Transaction(tx_info) => {
Ok(Response::Transaction(tx_info.map(|tx_info| tx_info.tx)))
}
ReadResponse::UnspentBestChainUtxo(utxo) => Ok(Response::UnspentBestChainUtxo(utxo)),
ReadResponse::AnyChainUtxo(_) => Err("ReadService does not track pending UTXOs. \
Manually unwrap the response, and handle pending UTXOs."),
ReadResponse::BlockLocator(hashes) => Ok(Response::BlockLocator(hashes)),
ReadResponse::BlockHashes(hashes) => Ok(Response::BlockHashes(hashes)),
ReadResponse::BlockHeaders(headers) => Ok(Response::BlockHeaders(headers)),
change(mempool): Contextually validates mempool transactions in best chain (#5716) * updates comments * adds check nullifier no dup fns for transactions * Adds: - check::anchors fn for tx iter - TODO comments for unifying nullifiers and anchors checks - new state request Updates unknown anchor errors to accomodate tx-only check Calls new state fn from transaction verifier * updates check::anchors fns to use transactions updates TransactionContextualValidity request to check sprout anchors adds comment mentioning TransactionContextualValidity ignores UTXOs * conditions new state req call on is_mempool updates tests * fix doc link / lint error * checks for duplicate nullifiers with closures * Update zebra-state/src/service/check/nullifier.rs Co-authored-by: teor <teor@riseup.net> * documents find_duplicate_nullifier params moves if let statement into for loop * renames new state req/res * asserts correct response variant in tx verifier * adds CheckBestChainTipShieldedSpends call in tx verifier to async checks * re-adds tracing instrumentation to check::anchors fn renames transaction_in_state to transaction_in_chain * adds block/tx wrapper fns for anchors checks * uses UnminedTx instead of transaction.hash() deletes broken test * updates new state req/res name * updates tests and uses par_iter for anchors checks * Updates check::anchors pub fn docs. * Adds: - comments / docs - a TransactionError variant for ValidateContextError * Apply suggestions from code review Co-authored-by: teor <teor@riseup.net> * moves downcast to From impl rustfmt * moves the ValidateContextError into an Arc updates comments and naming * leaves par_iter for another PR * puts io::Error in an Arc * updates anchors tests to call tx_anchors check * updates tests to call tx_no_duplicates_in_chain slightly improves formatting * Update zebra-consensus/src/error.rs Co-authored-by: teor <teor@riseup.net> * moves Arc from HistoryError to ValidateContextError Co-authored-by: teor <teor@riseup.net>
2022-11-29 20:40:15 -08:00
ReadResponse::ValidBestChainTipNullifiersAndAnchors => Ok(Response::ValidBestChainTipNullifiersAndAnchors),
ReadResponse::TransactionIdsForBlock(_)
| ReadResponse::SaplingTree(_)
| ReadResponse::OrchardTree(_)
| ReadResponse::AddressBalance(_)
| ReadResponse::AddressesTransactionIds(_)
| ReadResponse::AddressUtxos(_) => {
Err("there is no corresponding Response for this ReadResponse")
}
#[cfg(feature = "getblocktemplate-rpcs")]
ReadResponse::ValidBlockProposal => Ok(Response::ValidBlockProposal),
#[cfg(feature = "getblocktemplate-rpcs")]
ReadResponse::ChainInfo(_) | ReadResponse::SolutionRate(_) => {
Err("there is no corresponding Response for this ReadResponse")
}
}
}
}