Makes `equihash::Solution` an enum to support Regtest solutions, adds a test for validating and committing the Regtest genesis block

This commit is contained in:
Arya 2024-04-19 20:07:35 -04:00
parent 69d5d75ac5
commit 66336225d8
5 changed files with 83 additions and 24 deletions

View File

@ -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<Block> {
let regtest_genesis_block_bytes =
<Vec<u8>>::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")
}

View File

@ -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

View File

@ -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()
}

View File

@ -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<Self, SerializationError> {
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<Solution> 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<W: io::Write>(&self, writer: W) -> Result<(), io::Error> {
zcash_serialize_bytes(&self.0.to_vec(), writer)
zcash_serialize_bytes(&self.value().to_vec(), writer)
}
}

View File

@ -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"
)
}