Skip to content

Commit

Permalink
uses new Request in references to chain verifier
Browse files Browse the repository at this point in the history
  • Loading branch information
arya2 committed Dec 15, 2022
1 parent 6eb6048 commit 162dedb
Show file tree
Hide file tree
Showing 14 changed files with 125 additions and 99 deletions.
4 changes: 2 additions & 2 deletions zebra-consensus/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ where
};

match request {
Request::Block(_) => match state_service
Request::Commit(_) => match state_service
.ready()
.await
.map_err(VerifyBlockError::Commit)?
Expand All @@ -302,7 +302,7 @@ where
},

#[cfg(feature = "getblocktemplate-rpcs")]
Request::BlockProposal(_) => match state_service
Request::CheckProposal(_) => match state_service
.ready()
.await
.map_err(VerifyBlockError::Validate)?
Expand Down
17 changes: 11 additions & 6 deletions zebra-consensus/src/block/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,31 +4,36 @@ use std::sync::Arc;

use zebra_chain::block::Block;

#[derive(Debug, Clone, PartialEq, Eq)]
/// A request to the chain or block verifier
pub enum Request {
Block(Arc<Block>),
/// Performs semantic validation then calls state with CommitBlock request
Commit(Arc<Block>),

#[cfg(feature = "getblocktemplate-rpcs")]
BlockProposal(Arc<Block>),
/// Performs semantic validation but skips checking the solution,
/// then calls the state with CheckBlockValid request
CheckProposal(Arc<Block>),
}

impl Request {
/// Returns inner block
pub fn block(&self) -> Arc<Block> {
Arc::clone(match self {
Request::Block(block) => block,
Request::Commit(block) => block,

#[cfg(feature = "getblocktemplate-rpcs")]
Request::BlockProposal(block) => block,
Request::CheckProposal(block) => block,
})
}

/// Checks if request is a proposal
pub fn is_proposal(&self) -> bool {
match self {
Request::Block(_) => false,
Request::Commit(_) => false,

#[cfg(feature = "getblocktemplate-rpcs")]
Request::BlockProposal(_) => true,
Request::CheckProposal(_) => true,
}
}
}
50 changes: 32 additions & 18 deletions zebra-consensus/src/block/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,18 @@ use crate::{parameters::SLOW_START_SHIFT, transaction};

use super::*;

static VALID_BLOCK_TRANSCRIPT: Lazy<
Vec<(Arc<Block>, Result<block::Hash, ExpectedTranscriptError>)>,
> = Lazy::new(|| {
let block: Arc<_> =
Block::zcash_deserialize(&zebra_test::vectors::BLOCK_MAINNET_GENESIS_BYTES[..])
.unwrap()
.into();
let hash = Ok(block.as_ref().into());
vec![(block, hash)]
});
static VALID_BLOCK_TRANSCRIPT: Lazy<Vec<(Request, Result<block::Hash, ExpectedTranscriptError>)>> =
Lazy::new(|| {
let block: Arc<_> =
Block::zcash_deserialize(&zebra_test::vectors::BLOCK_MAINNET_GENESIS_BYTES[..])
.unwrap()
.into();
let hash = Ok(block.as_ref().into());
vec![(Request::Commit(block), hash)]
});

static INVALID_TIME_BLOCK_TRANSCRIPT: Lazy<
Vec<(Arc<Block>, Result<block::Hash, ExpectedTranscriptError>)>,
Vec<(Request, Result<block::Hash, ExpectedTranscriptError>)>,
> = Lazy::new(|| {
let mut block: Block =
Block::zcash_deserialize(&zebra_test::vectors::BLOCK_MAINNET_GENESIS_BYTES[..]).unwrap();
Expand All @@ -55,23 +54,29 @@ static INVALID_TIME_BLOCK_TRANSCRIPT: Lazy<
.unwrap();
Arc::make_mut(&mut block.header).time = three_hours_in_the_future;

vec![(Arc::new(block), Err(ExpectedTranscriptError::Any))]
vec![(
Request::Commit(Arc::new(block)),
Err(ExpectedTranscriptError::Any),
)]
});

static INVALID_HEADER_SOLUTION_TRANSCRIPT: Lazy<
Vec<(Arc<Block>, Result<block::Hash, ExpectedTranscriptError>)>,
Vec<(Request, Result<block::Hash, ExpectedTranscriptError>)>,
> = Lazy::new(|| {
let mut block: Block =
Block::zcash_deserialize(&zebra_test::vectors::BLOCK_MAINNET_GENESIS_BYTES[..]).unwrap();

// Change nonce to something invalid
Arc::make_mut(&mut block.header).nonce = [0; 32];

vec![(Arc::new(block), Err(ExpectedTranscriptError::Any))]
vec![(
Request::Commit(Arc::new(block)),
Err(ExpectedTranscriptError::Any),
)]
});

static INVALID_COINBASE_TRANSCRIPT: Lazy<
Vec<(Arc<Block>, Result<block::Hash, ExpectedTranscriptError>)>,
Vec<(Request, Result<block::Hash, ExpectedTranscriptError>)>,
> = Lazy::new(|| {
let header = block::Header::zcash_deserialize(&zebra_test::vectors::DUMMY_HEADER[..]).unwrap();

Expand Down Expand Up @@ -105,9 +110,18 @@ static INVALID_COINBASE_TRANSCRIPT: Lazy<
assert_eq!(block3.transactions.len(), 2);

vec![
(Arc::new(block1), Err(ExpectedTranscriptError::Any)),
(Arc::new(block2), Err(ExpectedTranscriptError::Any)),
(Arc::new(block3), Err(ExpectedTranscriptError::Any)),
(
Request::Commit(Arc::new(block1)),
Err(ExpectedTranscriptError::Any),
),
(
Request::Commit(Arc::new(block2)),
Err(ExpectedTranscriptError::Any),
),
(
Request::Commit(Arc::new(block3)),
Err(ExpectedTranscriptError::Any),
),
]
});

Expand Down
24 changes: 13 additions & 11 deletions zebra-consensus/src/chain/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ async fn verifiers_from_network(
network: Network,
) -> (
impl Service<
Arc<Block>,
Request,
Response = block::Hash,
Error = BoxError,
Future = impl Future<Output = Result<block::Hash, BoxError>>,
Expand Down Expand Up @@ -77,35 +77,37 @@ async fn verifiers_from_network(
}

static BLOCK_VERIFY_TRANSCRIPT_GENESIS: Lazy<
Vec<(Arc<Block>, Result<block::Hash, ExpectedTranscriptError>)>,
Vec<(Request, Result<block::Hash, ExpectedTranscriptError>)>,
> = Lazy::new(|| {
let block: Arc<_> =
Block::zcash_deserialize(&zebra_test::vectors::BLOCK_MAINNET_GENESIS_BYTES[..])
.unwrap()
.into();
let hash = Ok(block.hash());

vec![(block, hash)]
vec![(Request::Commit(block), hash)]
});

static BLOCK_VERIFY_TRANSCRIPT_GENESIS_FAIL: Lazy<
Vec<(Arc<Block>, Result<block::Hash, ExpectedTranscriptError>)>,
Vec<(Request, Result<block::Hash, ExpectedTranscriptError>)>,
> = Lazy::new(|| {
let block: Arc<_> =
Block::zcash_deserialize(&zebra_test::vectors::BLOCK_MAINNET_GENESIS_BYTES[..])
.unwrap()
.into();

vec![(block, Err(ExpectedTranscriptError::Any))]
vec![(Request::Commit(block), Err(ExpectedTranscriptError::Any))]
});

static NO_COINBASE_TRANSCRIPT: Lazy<
Vec<(Arc<Block>, Result<block::Hash, ExpectedTranscriptError>)>,
> = Lazy::new(|| {
let block = block_no_transactions();
static NO_COINBASE_TRANSCRIPT: Lazy<Vec<(Request, Result<block::Hash, ExpectedTranscriptError>)>> =
Lazy::new(|| {
let block = block_no_transactions();

vec![(Arc::new(block), Err(ExpectedTranscriptError::Any))]
});
vec![(
Request::Commit(Arc::new(block)),
Err(ExpectedTranscriptError::Any),
)]
});

static NO_COINBASE_STATE_TRANSCRIPT: Lazy<
Vec<(zs::Request, Result<zs::Response, ExpectedTranscriptError>)>,
Expand Down
2 changes: 1 addition & 1 deletion zebra-consensus/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ pub mod error;
pub use block::{
subsidy::funding_streams::funding_stream_address,
subsidy::funding_streams::funding_stream_values, subsidy::funding_streams::new_coinbase_script,
subsidy::general::miner_subsidy, VerifyBlockError, MAX_BLOCK_SIGOPS,
subsidy::general::miner_subsidy, Request, VerifyBlockError, MAX_BLOCK_SIGOPS,
};
pub use chain::VerifyChainError;
pub use checkpoint::{
Expand Down
10 changes: 5 additions & 5 deletions zebra-rpc/src/methods/get_block_template_rpcs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ where
Response = zebra_state::ReadResponse,
Error = zebra_state::BoxError,
>,
ChainVerifier: Service<Arc<Block>, Response = block::Hash, Error = zebra_consensus::BoxError>
ChainVerifier: Service<zebra_consensus::Request, Response = block::Hash, Error = zebra_consensus::BoxError>
+ Clone
+ Send
+ Sync
Expand Down Expand Up @@ -217,7 +217,7 @@ where
+ Sync
+ 'static,
Tip: ChainTip + Clone + Send + Sync + 'static,
ChainVerifier: Service<Arc<Block>, Response = block::Hash, Error = zebra_consensus::BoxError>
ChainVerifier: Service<zebra_consensus::Request, Response = block::Hash, Error = zebra_consensus::BoxError>
+ Clone
+ Send
+ Sync
Expand Down Expand Up @@ -265,12 +265,12 @@ where
+ 'static,
<State as Service<zebra_state::ReadRequest>>::Future: Send,
Tip: ChainTip + Clone + Send + Sync + 'static,
ChainVerifier: Service<Arc<Block>, Response = block::Hash, Error = zebra_consensus::BoxError>
ChainVerifier: Service<zebra_consensus::Request, Response = block::Hash, Error = zebra_consensus::BoxError>
+ Clone
+ Send
+ Sync
+ 'static,
<ChainVerifier as Service<Arc<Block>>>::Future: Send,
<ChainVerifier as Service<zebra_consensus::Request>>::Future: Send,
SyncStatus: ChainSyncStatus + Clone + Send + Sync + 'static,
{
fn get_block_count(&self) -> Result<u32> {
Expand Down Expand Up @@ -601,7 +601,7 @@ where
message: error.to_string(),
data: None,
})?
.call(Arc::new(block))
.call(zebra_consensus::Request::Commit(Arc::new(block)))
.await;

let chain_error = match chain_verifier_response {
Expand Down
16 changes: 8 additions & 8 deletions zebra-rpc/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
//! See the full list of
//! [Differences between JSON-RPC 1.0 and 2.0.](https://www.simple-is-better.org/rpc/#differences-between-1-0-and-2-0)
use std::{fmt, panic, sync::Arc};
use std::{fmt, panic};

use jsonrpc_core::{Compatibility, MetaIoHandler};
use jsonrpc_http_server::{CloseHandle, ServerBuilder};
Expand All @@ -17,10 +17,7 @@ use tower::{buffer::Buffer, Service};
use tracing::{Instrument, *};

use zebra_chain::{
block::{self, Block},
chain_sync_status::ChainSyncStatus,
chain_tip::ChainTip,
parameters::Network,
block, chain_sync_status::ChainSyncStatus, chain_tip::ChainTip, parameters::Network,
};
use zebra_node_services::mempool;

Expand Down Expand Up @@ -107,12 +104,15 @@ impl RpcServer {
+ 'static,
State::Future: Send,
Tip: ChainTip + Clone + Send + Sync + 'static,
ChainVerifier: Service<Arc<Block>, Response = block::Hash, Error = zebra_consensus::BoxError>
+ Clone
ChainVerifier: Service<
zebra_consensus::Request,
Response = block::Hash,
Error = zebra_consensus::BoxError,
> + Clone
+ Send
+ Sync
+ 'static,
<ChainVerifier as Service<Arc<Block>>>::Future: Send,
<ChainVerifier as Service<zebra_consensus::Request>>::Future: Send,
SyncStatus: ChainSyncStatus + Clone + Send + Sync + 'static,
{
if let Some(listen_addr) = config.listen_addr {
Expand Down
14 changes: 7 additions & 7 deletions zebra-state/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -810,7 +810,7 @@ impl ReadStateService {
#[tracing::instrument(level = "debug", skip_all)]
fn check_best_chain_contextual_validity(
&self,
prepared: PreparedBlock,
prepared: &PreparedBlock,
) -> Result<(), crate::ValidateContextError> {
let latest_non_finalized_state = self.latest_non_finalized_state();

Expand All @@ -826,22 +826,22 @@ impl ReadStateService {
self.network,
&self.db,
&latest_non_finalized_state,
&prepared,
prepared,
)?;

// Reads from disk
let sprout_final_treestates =
check::anchors::block_fetch_sprout_final_treestates(&self.db, best_chain, &prepared);
check::anchors::block_fetch_sprout_final_treestates(&self.db, best_chain, prepared);

let spent_utxos = check::utxo::transparent_spend(
&prepared,
prepared,
&best_chain.unspent_utxos(),
&best_chain.spent_utxos,
&self.db,
)?;

check::anchors::block_sapling_orchard_anchors_refer_to_final_treestates(
&self.db, best_chain, &prepared,
&self.db, best_chain, prepared,
)?;

let contextual = crate::request::ContextuallyValidBlock::with_block_and_spent_utxos(
Expand Down Expand Up @@ -1801,15 +1801,15 @@ impl Service<ReadRequest> for ReadStateService {
let span = Span::current();
tokio::task::spawn_blocking(move || {
span.in_scope(move || {
state.check_best_chain_contextual_validity(prepared)?;
state.check_best_chain_contextual_validity(&prepared)?;
// The work is done in the future.
timer.finish(
module_path!(),
line!(),
"ReadRequest::CheckContextualValidity",
);

Ok(ReadResponse::Validated)
Ok(ReadResponse::ValidBlock(prepared.hash))
})
})
.map(|join_result| join_result.expect("panic in ReadRequest::ChainInfo"))
Expand Down
10 changes: 5 additions & 5 deletions zebrad/src/components/inbound.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,7 @@ use tower::{buffer::Buffer, timeout::Timeout, util::BoxService, Service, Service
use zebra_network as zn;
use zebra_state as zs;

use zebra_chain::{
block::{self, Block},
transaction::UnminedTxId,
};
use zebra_chain::{block, transaction::UnminedTxId};
use zebra_consensus::chain::VerifyChainError;
use zebra_network::{
constants::{ADDR_RESPONSE_LIMIT_DENOMINATOR, MAX_ADDRS_IN_MESSAGE},
Expand All @@ -53,7 +50,10 @@ type BlockDownloadPeerSet =
Buffer<BoxService<zn::Request, zn::Response, zn::BoxError>, zn::Request>;
type State = Buffer<BoxService<zs::Request, zs::Response, zs::BoxError>, zs::Request>;
type Mempool = Buffer<BoxService<mempool::Request, mempool::Response, BoxError>, mempool::Request>;
type BlockVerifier = Buffer<BoxService<Arc<Block>, block::Hash, VerifyChainError>, Arc<Block>>;
type BlockVerifier = Buffer<
BoxService<zebra_consensus::Request, block::Hash, VerifyChainError>,
zebra_consensus::Request,
>;
type GossipedBlockDownloads =
BlockDownloads<Timeout<BlockDownloadPeerSet>, Timeout<BlockVerifier>, State>;

Expand Down
Loading

0 comments on commit 162dedb

Please sign in to comment.