From 66336225d8b5329660348783a269f780960a3d5c Mon Sep 17 00:00:00 2001 From: Arya Date: Fri, 19 Apr 2024 20:07:35 -0400 Subject: [PATCH] Makes `equihash::Solution` an enum to support Regtest solutions, adds a test for validating and committing the Regtest genesis block --- zebra-chain/src/block/genesis.rs | 5 +- zebra-chain/src/parameters/network_upgrade.rs | 3 + zebra-chain/src/work/arbitrary.rs | 2 +- zebra-chain/src/work/equihash.rs | 67 +++++++++++++------ zebrad/tests/acceptance.rs | 30 ++++++++- 5 files changed, 83 insertions(+), 24 deletions(-) diff --git a/zebra-chain/src/block/genesis.rs b/zebra-chain/src/block/genesis.rs index 460f26e90..271d79142 100644 --- a/zebra-chain/src/block/genesis.rs +++ b/zebra-chain/src/block/genesis.rs @@ -1,16 +1,19 @@ //! Regtest genesis block +use std::sync::Arc; + use hex::FromHex; use crate::{block::Block, serialization::ZcashDeserializeInto}; /// Genesis block for Regtest, copied from zcashd via `getblock 0 0` RPC method -pub fn regtest_genesis_block() -> Block { +pub fn regtest_genesis_block() -> Arc { let regtest_genesis_block_bytes = >::from_hex(include_str!("genesis/block-regtest-0-000-000.txt").trim()) .expect("Block bytes are in valid hex representation"); regtest_genesis_block_bytes .zcash_deserialize_into() + .map(Arc::new) .expect("hard-coded Regtest genesis block data must deserialize successfully") } diff --git a/zebra-chain/src/parameters/network_upgrade.rs b/zebra-chain/src/parameters/network_upgrade.rs index de546e3b4..6775ed2ee 100644 --- a/zebra-chain/src/parameters/network_upgrade.rs +++ b/zebra-chain/src/parameters/network_upgrade.rs @@ -340,6 +340,9 @@ impl NetworkUpgrade { self.next_upgrade() .and_then(|next_nu| next_nu.activation_height(network)) }) + // TODO: Remove `.expect()` calls on the return value of this function (except for Genesis), or + // update this method's return type + .or(Some(block::Height::MAX)) } /// Returns `true` if `height` is the activation height of any network upgrade diff --git a/zebra-chain/src/work/arbitrary.rs b/zebra-chain/src/work/arbitrary.rs index eac18f63a..660b3d715 100644 --- a/zebra-chain/src/work/arbitrary.rs +++ b/zebra-chain/src/work/arbitrary.rs @@ -10,7 +10,7 @@ impl Arbitrary for equihash::Solution { .prop_map(|v| { let mut bytes = [0; equihash::SOLUTION_SIZE]; bytes.copy_from_slice(v.as_slice()); - Self(bytes) + Self::Common(bytes) }) .boxed() } diff --git a/zebra-chain/src/work/equihash.rs b/zebra-chain/src/work/equihash.rs index 979273580..1d8a4753a 100644 --- a/zebra-chain/src/work/equihash.rs +++ b/zebra-chain/src/work/equihash.rs @@ -29,16 +29,26 @@ pub struct SolverCancelled; /// The size of an Equihash solution in bytes (always 1344). pub(crate) const SOLUTION_SIZE: usize = 1344; +/// The size of an Equihash solution in bytes on Regtest (always 36). +pub(crate) const REGTEST_SOLUTION_SIZE: usize = 36; + /// Equihash Solution in compressed format. /// /// A wrapper around [u8; 1344] because Rust doesn't implement common /// traits like `Debug`, `Clone`, etc for collections like array /// beyond lengths 0 to 32. /// -/// The size of an Equihash solution in bytes is always 1344 so the -/// length of this type is fixed. +/// The size of an Equihash solution in bytes is always 1344 on Mainnet and Testnet, and +/// is always 36 on Regtest so the length of this type is fixed. #[derive(Deserialize, Serialize)] -pub struct Solution(#[serde(with = "BigArray")] pub [u8; SOLUTION_SIZE]); +// It's okay to use the extra space on Regtest +#[allow(clippy::large_enum_variant)] +pub enum Solution { + /// Equihash solution on Mainnet or Testnet + Common(#[serde(with = "BigArray")] [u8; SOLUTION_SIZE]), + /// Equihash solution on Regtest + Regtest(#[serde(with = "BigArray")] [u8; REGTEST_SOLUTION_SIZE]), +} impl Solution { /// The length of the portion of the header used as input when verifying @@ -48,15 +58,24 @@ impl Solution { /// to the verification function. pub const INPUT_LENGTH: usize = 4 + 32 * 3 + 4 * 2; + /// Returns the inner value of the [`Solution`] as a byte slice. + fn value(&self) -> &[u8] { + match self { + Solution::Common(solution) => solution.as_slice(), + Solution::Regtest(solution) => solution.as_slice(), + } + } + /// Returns `Ok(())` if `EquihashSolution` is valid for `header` #[allow(clippy::unwrap_in_result)] pub fn check(&self, header: &Header) -> Result<(), Error> { - let n = 200; - let k = 9; let nonce = &header.nonce; - let solution = &self.0; - let mut input = Vec::new(); + let (solution, n, k) = match self { + Solution::Common(solution) => (solution.as_slice(), 200, 9), + Solution::Regtest(solution) => (solution.as_slice(), 48, 5), + }; + let mut input = Vec::new(); header .zcash_serialize(&mut input) .expect("serialization into a vec can't fail"); @@ -73,23 +92,29 @@ impl Solution { /// Returns a [`Solution`] containing the bytes from `solution`. /// Returns an error if `solution` is the wrong length. pub fn from_bytes(solution: &[u8]) -> Result { - if solution.len() != SOLUTION_SIZE { - return Err(SerializationError::Parse( + match solution.len() { + // Won't panic, because we just checked the length. + SOLUTION_SIZE => { + let mut bytes = [0; SOLUTION_SIZE]; + bytes.copy_from_slice(solution); + Ok(Self::Common(bytes)) + } + REGTEST_SOLUTION_SIZE => { + let mut bytes = [0; REGTEST_SOLUTION_SIZE]; + bytes.copy_from_slice(solution); + Ok(Self::Regtest(bytes)) + } + _unexpected_len => Err(SerializationError::Parse( "incorrect equihash solution size", - )); + )), } - - let mut bytes = [0; SOLUTION_SIZE]; - // Won't panic, because we just checked the length. - bytes.copy_from_slice(solution); - - Ok(Self(bytes)) } /// Returns a [`Solution`] of `[0; SOLUTION_SIZE]` to be used in block proposals. #[cfg(feature = "getblocktemplate-rpcs")] pub fn for_proposal() -> Self { - Self([0; SOLUTION_SIZE]) + // TODO: Accept network as an argument, and if it's Regtest, return the shorter null solution. + Self::Common([0; SOLUTION_SIZE]) } /// Mines and returns one or more [`Solution`]s based on a template `header`. @@ -126,14 +151,14 @@ impl Solution { impl PartialEq for Solution { fn eq(&self, other: &Solution) -> bool { - self.0.as_ref() == other.0.as_ref() + self.value() == other.value() } } impl fmt::Debug for Solution { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_tuple("EquihashSolution") - .field(&hex::encode(&self.0[..])) + .field(&hex::encode(self.value())) .finish() } } @@ -153,13 +178,13 @@ impl Eq for Solution {} #[cfg(any(test, feature = "proptest-impl"))] impl Default for Solution { fn default() -> Self { - Self([0; SOLUTION_SIZE]) + Self::Common([0; SOLUTION_SIZE]) } } impl ZcashSerialize for Solution { fn zcash_serialize(&self, writer: W) -> Result<(), io::Error> { - zcash_serialize_bytes(&self.0.to_vec(), writer) + zcash_serialize_bytes(&self.value().to_vec(), writer) } } diff --git a/zebrad/tests/acceptance.rs b/zebrad/tests/acceptance.rs index eb6a27917..5605d3956 100644 --- a/zebrad/tests/acceptance.rs +++ b/zebrad/tests/acceptance.rs @@ -161,10 +161,12 @@ use color_eyre::{ use semver::Version; use serde_json::Value; +use tower::ServiceExt; use zebra_chain::{ - block::{self, Height}, + block::{self, genesis::regtest_genesis_block, Height}, parameters::Network::{self, *}, }; +use zebra_consensus::ParameterCheckpoint; use zebra_network::constants::PORT_IN_USE_ERROR; use zebra_node_services::rpc_client::RpcRequestClient; use zebra_state::{constants::LOCK_FILE_ERROR, state_database_format_version_in_code}; @@ -3098,3 +3100,29 @@ fn scan_start_where_left() -> Result<()> { async fn scan_task_commands() -> Result<()> { common::shielded_scan::scan_task_commands::run().await } + +/// Checks that the Regtest genesis block can be validated. +#[tokio::test] +async fn validate_regtest_genesis_block() { + let _init_guard = zebra_test::init(); + + let network = Network::new_regtest(Default::default()); + let state = zebra_state::init_test(&network); + let ( + block_verifier_router, + _transaction_verifier, + _parameter_download_task_handle, + _max_checkpoint_height, + ) = zebra_consensus::router::init(zebra_consensus::Config::default(), &network, state).await; + + let genesis_hash = block_verifier_router + .oneshot(zebra_consensus::Request::Commit(regtest_genesis_block())) + .await + .expect("should validate Regtest genesis block"); + + assert_eq!( + genesis_hash, + network.genesis_hash(), + "validated block hash should match network genesis hash" + ) +}