Compare commits

...

13 Commits

Author SHA1 Message Date
Marek d39c60d53c
Merge 3a66152d9e into d84d7356dd 2024-04-26 12:25:44 +00:00
Marek 3a66152d9e Impl `From` for a reference type correctly
The previous implementation called `into` on a reference without
dereferencing it. I thought the compiler would implicitly dereference,
but it didn't, which lead to infinite recursion since the fn ended up
calling itself.
2024-04-26 14:21:47 +02:00
Arya d84d7356dd
add(consensus): Adds `disable_pow` and `genesis_hash` fields, converts `equihash::Solution` to an enum (#8421)
* minor cleanup and rename

* Adds an empty NetworkParameters struct to Network::Testnet variant, updates production code.

* Updates tests

* Adds `NetworkKind` and uses it instead of `Network` in `HistoryTreeParts` and `transparent::Address`

* Adds a [network.testnet_parameters] section to the config, uses `NetworkKind` as zebra_network::Config::network field type, and converts 'Network' to `NetworkKind` before serializing

* Applies some suggestions from code review

* Applies suggestions from code review

* returns b58 prefix constants directly to remove From<NetworkKind> impl for zcash_primitives::consensus::Network

* Applies more suggestions from code review.

* moves conversions to zcash_primitives::consensus::Network to where they're used.

* Apply suggestions from code review

Co-authored-by: Marek <mail@marek.onl>

* rename `network` variables and method names typed as NetworkKind to `network_kind`

* use only test block heights for the network associated with them

* Applies more suggestions from code review.

* Rename `NetworkParameters` to `Parameters` and move it a new `testnet` module

* adds activation heights field

* updates stored test config, adds a quicker test for checking that stored configs can be parsed, adds an intermediate representation of activation heights

* implement Parameters for Network

* Passes &Network directly instead of converting to zp_consensus::Network where there were conversions

* fixes a bad merge (removes a network conversion in zcash_note_encryption)

* Adds a test for the Parameters impl for zebra_chain::Network

* fixes doc links

* - Makes the `activation_heights` config field optional by adding a #[serde(default)]
- Panics if a non-zero activation height is provided for the `Genesis` network upgrade
- Always sets the `Genesis` and `BeforeOverwinter` network upgrade activation heights to 0 and 1, `BeforeOverwinter` could be overwritten by a later network upgrade
- Makes the `activation_heights` field on `Parameters` private, adds/uses an accessor method instead, and adds a builder struct and `build()` method

* small refactor of activation_heights() method

* check that activation heights are in the right order

* Updates `NetworkUpgrade::activation_height()` to return the height of the next NetworkUpgrade if it doesn't find the activation height of `&self`

* checks that the miner address is of TestnetKind on Regtest and update assertion message

* Adds a DNetworkUpgradeActivationHeights struct for better control over how activation heights can be configured

* moves all ordered network upgrades to a constant, adds a no_duplicates test, moves struct with activation heights outside deserialization impl and accepts it in `ParametersBuilder::activation_heights()` instead of a Vec

* panics if any network upgrades are configured to activate at Height(0) because it's reserved for Genesis

* Simplifies the `ParametersBuilder::activation_heights()` method and removes an unnecessary test.

* Adds Sapling HRPs as fields on testnet params. (#8398)

* Applies suggestions from code review.

* Update zebra-chain/src/parameters/network_upgrade.rs

Co-authored-by: Marek <mail@marek.onl>

* Adds `network_name` field and accessor method on `Parameters`, uses it in the `Display` impl for `Network`

* Removes unnecessary `.filter()`

* adds constraints on valid network names and a test

* adds config field for setting network name, adds "with_" prefix to ParameterBuilder setter methods

* Adds `MainnetKind`, `TestnetKind`, and `RegtestKind` to reserved network names

* updates stored test configs and fixes `network_name()` docs

* Adds a `new_regtest()` method on `Network` and `testnet::Parameters`, updates config deserialization to return an error if the initial_testnet_peers include any default initial peers AND contain configured activation heights

* Updates `activates_network_upgrades_correctly` test to check Regtest activation heights (and default Mainnet/Testnet)

* Refactors if-let & match statement into general match statement, removes constraint against including `testnet_parameters` field/section in the config when using `Mainnet` or `Regtest`

* Removes outdated TODO

* Restores `testnet_parameters` section of the latest stored config.

* Adds `with_sapling_hrps()` method and uses it to set the Regtest HRPs in `new_regtest()`.

Adds a test for Sapling HRP validation

* Checks that default Mainnet/Testnet/Regtest Sapling HRPs pass validation in `with_sapling_hrps()`

* Uses the correct constant in test

* Adds `is_regtest()` methods

* Adds genesis hash methods and fields to `testnet::Parameters` and its builder

* Copies Regtest genesis block from zcashd

* moves genesis hash check to Network.checkpoint_list()

* Checks the first line in the checkpoint list instead of the first item in the BTreeMap

* Checks that there is _some_ genesis block in the checkpoints list in `from_list()`, adds Regtest checkpoints (which only includes the genesis block)

* Adds a doc comment to `ParametersBuilder::default()`

* Adds a `disable_pow` field and skips checking proof of work if it's true

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

* use genesis_hash as first checkpoint when checkpoints are missing for configured testnets too

* Applies suggestions from code review.

* Reverts changes to `activation_height()` method

* Avoids panic in test

* Updates test docs

* drop custom panic hooks after expected panics

---------

Co-authored-by: Marek <mail@marek.onl>
2024-04-26 05:30:36 +00:00
Arya c28e37bf23
disables `rejection_restores_internal_state_genesis` test on Windows (#8468) 2024-04-26 05:30:31 +00:00
Marek 8fca642d39
Merge branch 'main' into impl-Params-from-zcash-protocol 2024-04-24 19:33:44 +00:00
Marek 8a7dcedca7 Merge branch 'main' into impl-Params-from-zcash-protocol 2024-04-24 17:30:23 +02:00
Marek 0aa9c69298 Remove a redundant `impl From` 2024-04-24 16:45:12 +02:00
Marek 78ed227a2a Merge branch 'main' into impl-Params-from-zcash-protocol 2024-04-22 21:49:40 +02:00
Marek 98a136af98 Move `mod address` from under the gbt feature 2024-04-22 21:47:41 +02:00
Marek ba6c0d7110 Impl `zcash_protocol::consensus::Parameters` 2024-04-22 20:22:07 +02:00
Marek 3084f3bb69 Impl conversions between network upgrades 2024-04-22 20:20:58 +02:00
Marek 9a45ada2a8 Impl and use conversion between network kinds
These conversions will make implementing
`zcash_protocol::consensus::Parameters` for `Network` easier.
2024-04-22 20:17:31 +02:00
Marek 09920d045e Use full paths for types from `zcash_primitives`
Upcoming commits will use `zcash_protocol::consensus::Parameters`, which
would make names such as `zp_consensus::Parameters` ambiguous since such
a name could stand for both `zcash_primitives...` and
`zcash_protocol...`.
2024-04-22 17:58:19 +02:00
19 changed files with 321 additions and 125 deletions

View File

@ -5898,6 +5898,7 @@ dependencies = [
"zcash_history",
"zcash_note_encryption",
"zcash_primitives",
"zcash_protocol",
"zebra-test",
]

View File

@ -98,6 +98,8 @@ zcash_encoding = "0.2.0"
zcash_history = "0.4.0"
zcash_note_encryption = "0.4.0"
zcash_primitives = { version = "0.13.0", features = ["transparent-inputs"] }
zcash_protocol = { version = "0.1.1" }
zcash_address = { version = "0.3.2" }
# Time
chrono = { version = "0.4.38", default-features = false, features = ["clock", "std", "serde"] }
@ -131,8 +133,6 @@ serde_json = { version = "1.0.116", optional = true }
# Production feature async-error and testing feature proptest-impl
tokio = { version = "1.37.0", optional = true }
zcash_address = { version = "0.3.2" }
# Experimental feature shielded-scan
zcash_client_backend = { version = "0.10.0-rc.1", optional = true }

View File

@ -25,6 +25,7 @@ mod header;
mod height;
mod serialize;
pub mod genesis;
pub mod merkle;
#[cfg(any(test, feature = "proptest-impl"))]

View File

@ -0,0 +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() -> 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

@ -0,0 +1 @@
040000000000000000000000000000000000000000000000000000000000000000000000db4d7a85b768123f1dff1d4c4cece70083b2d27e117b4ac2e31d087988a5eac40000000000000000000000000000000000000000000000000000000000000000dae5494d0f0f0f2009000000000000000000000000000000000000000000000000000000000000002401936b7db1eb4ac39f151b8704642d0a8bda13ec547d54cd5e43ba142fc6d8877cab07b30101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4d04ffff071f0104455a6361736830623963346565663862376363343137656535303031653335303039383462366665613335363833613763616331343161303433633432303634383335643334ffffffff010000000000000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000

View File

@ -455,9 +455,15 @@ impl HistoryTree {
sapling_root: &sapling::tree::Root,
orchard_root: &orchard::tree::Root,
) -> Result<(), HistoryTreeError> {
let heartwood_height = NetworkUpgrade::Heartwood
.activation_height(network)
.expect("Heartwood height is known");
let Some(heartwood_height) = NetworkUpgrade::Heartwood.activation_height(network) else {
assert!(
self.0.is_none(),
"history tree must not exist pre-Heartwood"
);
return Ok(());
};
match block
.coinbase_height()
.expect("must have height")

View File

@ -4,8 +4,6 @@ use std::{fmt, str::FromStr, sync::Arc};
use thiserror::Error;
use zcash_primitives::{consensus as zp_consensus, constants as zp_constants};
use crate::{
block::{self, Height, HeightDiff},
parameters::NetworkUpgrade,
@ -96,8 +94,10 @@ impl NetworkKind {
/// pay-to-public-key-hash payment addresses for the network.
pub fn b58_pubkey_address_prefix(self) -> [u8; 2] {
match self {
Self::Mainnet => zp_constants::mainnet::B58_PUBKEY_ADDRESS_PREFIX,
Self::Testnet | Self::Regtest => zp_constants::testnet::B58_PUBKEY_ADDRESS_PREFIX,
Self::Mainnet => zcash_primitives::constants::mainnet::B58_PUBKEY_ADDRESS_PREFIX,
Self::Testnet | Self::Regtest => {
zcash_primitives::constants::testnet::B58_PUBKEY_ADDRESS_PREFIX
}
}
}
@ -105,8 +105,10 @@ impl NetworkKind {
/// payment addresses for the network.
pub fn b58_script_address_prefix(self) -> [u8; 2] {
match self {
Self::Mainnet => zp_constants::mainnet::B58_SCRIPT_ADDRESS_PREFIX,
Self::Testnet | Self::Regtest => zp_constants::testnet::B58_SCRIPT_ADDRESS_PREFIX,
Self::Mainnet => zcash_primitives::constants::mainnet::B58_SCRIPT_ADDRESS_PREFIX,
Self::Testnet | Self::Regtest => {
zcash_primitives::constants::testnet::B58_SCRIPT_ADDRESS_PREFIX
}
}
}
@ -189,6 +191,14 @@ impl Network {
}
}
/// Returns true if proof-of-work validation should be disabled for this network
pub fn disable_pow(&self) -> bool {
if let Self::Testnet(params) = self {
params.disable_pow()
} else {
false
}
}
/// Returns the [`NetworkKind`] for this network.
pub fn kind(&self) -> NetworkKind {
match self {
@ -288,32 +298,23 @@ impl FromStr for Network {
#[error("Invalid network: {0}")]
pub struct InvalidNetworkError(String);
impl zp_consensus::Parameters for Network {
impl zcash_primitives::consensus::Parameters for Network {
fn activation_height(
&self,
nu: zcash_primitives::consensus::NetworkUpgrade,
) -> Option<zcash_primitives::consensus::BlockHeight> {
let target_nu = match nu {
zp_consensus::NetworkUpgrade::Overwinter => NetworkUpgrade::Overwinter,
zp_consensus::NetworkUpgrade::Sapling => NetworkUpgrade::Sapling,
zp_consensus::NetworkUpgrade::Blossom => NetworkUpgrade::Blossom,
zp_consensus::NetworkUpgrade::Heartwood => NetworkUpgrade::Heartwood,
zp_consensus::NetworkUpgrade::Canopy => NetworkUpgrade::Canopy,
zp_consensus::NetworkUpgrade::Nu5 => NetworkUpgrade::Nu5,
};
// Heights are hard-coded below Height::MAX or checked when the config is parsed.
target_nu
NetworkUpgrade::from(nu)
.activation_height(self)
.map(|Height(h)| zp_consensus::BlockHeight::from_u32(h))
.map(|Height(h)| zcash_primitives::consensus::BlockHeight::from_u32(h))
}
fn coin_type(&self) -> u32 {
match self {
Network::Mainnet => zp_constants::mainnet::COIN_TYPE,
Network::Mainnet => zcash_primitives::constants::mainnet::COIN_TYPE,
// The regtest cointype reuses the testnet cointype,
// See <https://github.com/satoshilabs/slips/blob/master/slip-0044.md>
Network::Testnet(_) => zp_constants::testnet::COIN_TYPE,
Network::Testnet(_) => zcash_primitives::constants::testnet::COIN_TYPE,
}
}
@ -327,21 +328,25 @@ impl zp_consensus::Parameters for Network {
fn hrp_sapling_extended_spending_key(&self) -> &str {
match self {
Network::Mainnet => zp_constants::mainnet::HRP_SAPLING_EXTENDED_SPENDING_KEY,
Network::Mainnet => {
zcash_primitives::constants::mainnet::HRP_SAPLING_EXTENDED_SPENDING_KEY
}
Network::Testnet(params) => params.hrp_sapling_extended_spending_key(),
}
}
fn hrp_sapling_extended_full_viewing_key(&self) -> &str {
match self {
Network::Mainnet => zp_constants::mainnet::HRP_SAPLING_EXTENDED_FULL_VIEWING_KEY,
Network::Mainnet => {
zcash_primitives::constants::mainnet::HRP_SAPLING_EXTENDED_FULL_VIEWING_KEY
}
Network::Testnet(params) => params.hrp_sapling_extended_full_viewing_key(),
}
}
fn hrp_sapling_payment_address(&self) -> &str {
match self {
Network::Mainnet => zp_constants::mainnet::HRP_SAPLING_PAYMENT_ADDRESS,
Network::Mainnet => zcash_primitives::constants::mainnet::HRP_SAPLING_PAYMENT_ADDRESS,
Network::Testnet(params) => params.hrp_sapling_payment_address(),
}
}
@ -354,3 +359,18 @@ impl zp_consensus::Parameters for Network {
self.kind().b58_script_address_prefix()
}
}
impl zcash_protocol::consensus::Parameters for Network {
fn network_type(&self) -> zcash_address::Network {
self.kind().into()
}
fn activation_height(
&self,
nu: zcash_protocol::consensus::NetworkUpgrade,
) -> Option<zcash_protocol::consensus::BlockHeight> {
NetworkUpgrade::from(nu)
.activation_height(self)
.map(|Height(h)| zcash_protocol::consensus::BlockHeight::from_u32(h))
}
}

View File

@ -4,7 +4,7 @@ use std::{collections::BTreeMap, fmt};
use zcash_primitives::constants as zp_constants;
use crate::{
block::Height,
block::{self, Height},
parameters::{
network_upgrade::TESTNET_ACTIVATION_HEIGHTS, Network, NetworkUpgrade,
NETWORK_UPGRADES_IN_ORDER,
@ -27,6 +27,14 @@ pub const MAX_NETWORK_NAME_LENGTH: usize = 30;
/// Maximum length for a configured human-readable prefix.
pub const MAX_HRP_LENGTH: usize = 30;
/// The block hash of the Regtest genesis block, `zcash-cli -regtest getblockhash 0`
const REGTEST_GENESIS_HASH: &str =
"029f11d80ef9765602235e1bc9727e3eb6ba20839319f761fee920d63401e327";
/// The block hash of the Testnet genesis block, `zcash-cli -testnet getblockhash 0`
const TESTNET_GENESIS_HASH: &str =
"05a60a92d99d85997cce3b87616c089f6124d7342af37106edc76126334a2c38";
/// Configurable activation heights for Regtest and configured Testnets.
#[derive(Deserialize, Default)]
#[serde(rename_all = "PascalCase")]
@ -53,6 +61,8 @@ pub struct ConfiguredActivationHeights {
pub struct ParametersBuilder {
/// The name of this network to be used by the `Display` trait impl.
network_name: String,
/// The genesis block hash
genesis_hash: block::Hash,
/// The network upgrade activation heights for this network, see [`Parameters::activation_heights`] for more details.
activation_heights: BTreeMap<Height, NetworkUpgrade>,
/// Sapling extended spending key human-readable prefix for this network
@ -61,9 +71,12 @@ pub struct ParametersBuilder {
hrp_sapling_extended_full_viewing_key: String,
/// Sapling payment address human-readable prefix for this network
hrp_sapling_payment_address: String,
/// A flag for disabling proof-of-work checks when Zebra is validating blocks
disable_pow: bool,
}
impl Default for ParametersBuilder {
/// Creates a [`ParametersBuilder`] with all of the default Testnet parameters except `network_name`.
fn default() -> Self {
Self {
network_name: "UnknownTestnet".to_string(),
@ -77,6 +90,10 @@ impl Default for ParametersBuilder {
zp_constants::testnet::HRP_SAPLING_EXTENDED_FULL_VIEWING_KEY.to_string(),
hrp_sapling_payment_address: zp_constants::testnet::HRP_SAPLING_PAYMENT_ADDRESS
.to_string(),
genesis_hash: TESTNET_GENESIS_HASH
.parse()
.expect("hard-coded hash parses"),
disable_pow: false,
}
}
}
@ -144,6 +161,15 @@ impl ParametersBuilder {
self
}
/// Parses the hex-encoded block hash and sets it as the genesis hash in the [`Parameters`] being built.
pub fn with_genesis_hash(mut self, genesis_hash: impl fmt::Display) -> Self {
self.genesis_hash = genesis_hash
.to_string()
.parse()
.expect("configured genesis hash must parse");
self
}
/// Checks that the provided network upgrade activation heights are in the correct order, then
/// sets them as the new network upgrade activation heights.
pub fn with_activation_heights(
@ -208,21 +234,31 @@ impl ParametersBuilder {
self
}
/// Sets the `disable_pow` flag to be used in the [`Parameters`] being built.
pub fn with_disable_pow(mut self, disable_pow: bool) -> Self {
self.disable_pow = disable_pow;
self
}
/// Converts the builder to a [`Parameters`] struct
pub fn finish(self) -> Parameters {
let Self {
network_name,
genesis_hash,
activation_heights,
hrp_sapling_extended_spending_key,
hrp_sapling_extended_full_viewing_key,
hrp_sapling_payment_address,
disable_pow,
} = self;
Parameters {
network_name,
genesis_hash,
activation_heights,
hrp_sapling_extended_spending_key,
hrp_sapling_extended_full_viewing_key,
hrp_sapling_payment_address,
disable_pow,
}
}
@ -237,6 +273,8 @@ impl ParametersBuilder {
pub struct Parameters {
/// The name of this network to be used by the `Display` trait impl.
network_name: String,
/// The genesis block hash
genesis_hash: block::Hash,
/// The network upgrade activation heights for this network.
///
/// Note: This value is ignored by `Network::activation_list()` when `zebra-chain` is
@ -249,6 +287,8 @@ pub struct Parameters {
hrp_sapling_extended_full_viewing_key: String,
/// Sapling payment address human-readable prefix for this network
hrp_sapling_payment_address: String,
/// A flag for disabling proof-of-work checks when Zebra is validating blocks
disable_pow: bool,
}
impl Default for Parameters {
@ -274,6 +314,8 @@ impl Parameters {
Self {
network_name: "Regtest".to_string(),
..Self::build()
.with_genesis_hash(REGTEST_GENESIS_HASH)
.with_disable_pow(true)
.with_sapling_hrps(
zp_constants::regtest::HRP_SAPLING_EXTENDED_SPENDING_KEY,
zp_constants::regtest::HRP_SAPLING_EXTENDED_FULL_VIEWING_KEY,
@ -295,16 +337,21 @@ impl Parameters {
pub fn is_regtest(&self) -> bool {
let Self {
network_name,
genesis_hash,
// Activation heights are configurable on Regtest
activation_heights: _,
hrp_sapling_extended_spending_key,
hrp_sapling_extended_full_viewing_key,
hrp_sapling_payment_address,
..
disable_pow,
} = Self::new_regtest(ConfiguredActivationHeights::default());
self.network_name == network_name
&& self.genesis_hash == genesis_hash
&& self.hrp_sapling_extended_spending_key == hrp_sapling_extended_spending_key
&& self.hrp_sapling_extended_full_viewing_key == hrp_sapling_extended_full_viewing_key
&& self.hrp_sapling_payment_address == hrp_sapling_payment_address
&& self.disable_pow == disable_pow
}
/// Returns the network name
@ -312,6 +359,11 @@ impl Parameters {
&self.network_name
}
/// Returns the genesis hash
pub fn genesis_hash(&self) -> block::Hash {
self.genesis_hash
}
/// Returns the network upgrade activation heights
pub fn activation_heights(&self) -> &BTreeMap<Height, NetworkUpgrade> {
&self.activation_heights
@ -331,4 +383,9 @@ impl Parameters {
pub fn hrp_sapling_payment_address(&self) -> &str {
&self.hrp_sapling_payment_address
}
/// Returns true if proof-of-work validation should be disabled for this network
pub fn disable_pow(&self) -> bool {
self.disable_pow
}
}

View File

@ -493,6 +493,32 @@ impl NetworkUpgrade {
}
}
impl From<zcash_protocol::consensus::NetworkUpgrade> for NetworkUpgrade {
fn from(nu: zcash_protocol::consensus::NetworkUpgrade) -> Self {
match nu {
zcash_protocol::consensus::NetworkUpgrade::Overwinter => Self::Overwinter,
zcash_protocol::consensus::NetworkUpgrade::Sapling => Self::Sapling,
zcash_protocol::consensus::NetworkUpgrade::Blossom => Self::Blossom,
zcash_protocol::consensus::NetworkUpgrade::Heartwood => Self::Heartwood,
zcash_protocol::consensus::NetworkUpgrade::Canopy => Self::Canopy,
zcash_protocol::consensus::NetworkUpgrade::Nu5 => Self::Nu5,
}
}
}
impl From<zcash_primitives::consensus::NetworkUpgrade> for NetworkUpgrade {
fn from(value: zcash_primitives::consensus::NetworkUpgrade) -> Self {
match value {
zcash_primitives::consensus::NetworkUpgrade::Overwinter => NetworkUpgrade::Overwinter,
zcash_primitives::consensus::NetworkUpgrade::Sapling => NetworkUpgrade::Sapling,
zcash_primitives::consensus::NetworkUpgrade::Blossom => NetworkUpgrade::Blossom,
zcash_primitives::consensus::NetworkUpgrade::Heartwood => NetworkUpgrade::Heartwood,
zcash_primitives::consensus::NetworkUpgrade::Canopy => NetworkUpgrade::Canopy,
zcash_primitives::consensus::NetworkUpgrade::Nu5 => NetworkUpgrade::Nu5,
}
}
}
impl ConsensusBranchId {
/// The value used by `zcashd` RPCs for missing consensus branch IDs.
///

View File

@ -6,10 +6,8 @@
mod proofs;
#[cfg(feature = "getblocktemplate-rpcs")]
mod address;
#[cfg(feature = "getblocktemplate-rpcs")]
pub use address::Address;
#[cfg(feature = "shielded-scan")]

View File

@ -49,7 +49,7 @@ impl zcash_address::TryFromAddress for Address {
data: [u8; 20],
) -> Result<Self, zcash_address::ConversionError<Self::Error>> {
Ok(Self::Transparent(transparent::Address::from_pub_key_hash(
NetworkKind::from_zcash_address(network),
network.into(),
data,
)))
}
@ -59,7 +59,7 @@ impl zcash_address::TryFromAddress for Address {
data: [u8; 20],
) -> Result<Self, zcash_address::ConversionError<Self::Error>> {
Ok(Self::Transparent(transparent::Address::from_script_hash(
NetworkKind::from_zcash_address(network),
network.into(),
data,
)))
}
@ -68,7 +68,7 @@ impl zcash_address::TryFromAddress for Address {
network: zcash_address::Network,
data: [u8; 43],
) -> Result<Self, zcash_address::ConversionError<Self::Error>> {
let network = NetworkKind::from_zcash_address(network);
let network = network.into();
sapling::PaymentAddress::from_bytes(&data)
.map(|address| Self::Sapling { address, network })
.ok_or_else(|| BoxError::from("not a valid sapling address").into())
@ -78,7 +78,7 @@ impl zcash_address::TryFromAddress for Address {
network: zcash_address::Network,
unified_address: zcash_address::unified::Address,
) -> Result<Self, zcash_address::ConversionError<Self::Error>> {
let network = NetworkKind::from_zcash_address(network);
let network = network.into();
let mut orchard = None;
let mut sapling = None;
let mut transparent = None;
@ -163,7 +163,7 @@ impl Address {
Self::Transparent(address) => Some(address.to_string()),
Self::Sapling { address, network } => {
let data = address.to_bytes();
let address = ZcashAddress::from_sapling(network.to_zcash_address(), data);
let address = ZcashAddress::from_sapling(network.into(), data);
Some(address.encode())
}
Self::Unified { .. } => None,
@ -171,26 +171,28 @@ impl Address {
}
}
impl NetworkKind {
/// Converts a [`zcash_address::Network`] to a [`NetworkKind`].
///
/// This method is meant to be used for decoding Zcash addresses in zebra-rpc methods.
fn from_zcash_address(network: zcash_address::Network) -> Self {
impl From<zcash_address::Network> for NetworkKind {
fn from(network: zcash_address::Network) -> Self {
match network {
zcash_address::Network::Main => NetworkKind::Mainnet,
zcash_address::Network::Test => NetworkKind::Testnet,
zcash_address::Network::Regtest => NetworkKind::Regtest,
}
}
}
/// Converts a [`zcash_address::Network`] to a [`NetworkKind`].
///
/// This method is meant to be used for encoding Zcash addresses in zebra-rpc methods.
fn to_zcash_address(self) -> zcash_address::Network {
match self {
impl From<NetworkKind> for zcash_address::Network {
fn from(network: NetworkKind) -> Self {
match network {
NetworkKind::Mainnet => zcash_address::Network::Main,
NetworkKind::Testnet => zcash_address::Network::Test,
NetworkKind::Regtest => zcash_address::Network::Regtest,
}
}
}
impl From<&NetworkKind> for zcash_address::Network {
fn from(network: &NetworkKind) -> Self {
(*network).into()
}
}

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.
/// A wrapper around `[u8; n]` where `n` is the solution size because
/// Rust doesn't implement common traits like `Debug`, `Clone`, etc.
/// for collections like arrays 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

@ -176,16 +176,18 @@ where
Err(BlockError::MaxHeight(height, hash, block::Height::MAX))?;
}
// > The block data MUST be validated and checked against the server's usual
// > acceptance rules (excluding the check for a valid proof-of-work).
// <https://en.bitcoin.it/wiki/BIP_0023#Block_Proposal>
if request.is_proposal() {
check::difficulty_threshold_is_valid(&block.header, &network, &height, &hash)?;
} else {
// Do the difficulty checks first, to raise the threshold for
// attacks that use any other fields.
check::difficulty_is_valid(&block.header, &network, &height, &hash)?;
check::equihash_solution_is_valid(&block.header)?;
if !network.disable_pow() {
// > The block data MUST be validated and checked against the server's usual
// > acceptance rules (excluding the check for a valid proof-of-work).
// <https://en.bitcoin.it/wiki/BIP_0023#Block_Proposal>
if request.is_proposal() {
check::difficulty_threshold_is_valid(&block.header, &network, &height, &hash)?;
} else {
// Do the difficulty checks first, to raise the threshold for
// attacks that use any other fields.
check::difficulty_is_valid(&block.header, &network, &height, &hash)?;
check::equihash_solution_is_valid(&block.header)?;
}
}
// Next, check the Merkle root validity, to ensure that

View File

@ -595,8 +595,10 @@ where
.ok_or(VerifyCheckpointError::CoinbaseHeight { hash })?;
self.check_height(height)?;
crate::block::check::difficulty_is_valid(&block.header, &self.network, &height, &hash)?;
crate::block::check::equihash_solution_is_valid(&block.header)?;
if !self.network.disable_pow() {
crate::block::check::difficulty_is_valid(&block.header, &self.network, &height, &hash)?;
crate::block::check::equihash_solution_is_valid(&block.header)?;
}
// don't do precalculation until the block passes basic difficulty checks
let block = CheckpointVerifiedBlock::with_hash(block, hash);

View File

@ -55,41 +55,60 @@ impl ParameterCheckpoint for Network {
fn genesis_hash(&self) -> zebra_chain::block::Hash {
match self {
// zcash-cli getblockhash 0
Network::Mainnet => "00040fe8ec8471911baa1db1266ea15dd06b4a8a5c453883c000b031973dce08",
// zcash-cli -testnet getblockhash 0
// TODO: Add a `genesis_hash` field to `testnet::Parameters` and return it here (#8366)
Network::Testnet(_params) => {
"05a60a92d99d85997cce3b87616c089f6124d7342af37106edc76126334a2c38"
}
Network::Mainnet => "00040fe8ec8471911baa1db1266ea15dd06b4a8a5c453883c000b031973dce08"
.parse()
.expect("hard-coded hash parses"),
// See `zebra_chain::parameters::network::testnet` for more details.
Network::Testnet(params) => params.genesis_hash(),
}
.parse()
.expect("hard-coded hash parses")
}
fn checkpoint_list(&self) -> CheckpointList {
// parse calls CheckpointList::from_list
// TODO:
// - Add a `genesis_hash` field to `testnet::Parameters` and return it here (#8366)
// - Try to disable checkpoints entirely for regtest and custom testnets
let checkpoint_list: CheckpointList = match self {
Network::Mainnet => MAINNET_CHECKPOINTS
.parse()
.expect("Hard-coded Mainnet checkpoint list parses and validates"),
Network::Testnet(_params) => TESTNET_CHECKPOINTS
.parse()
.expect("Hard-coded Testnet checkpoint list parses and validates"),
let (checkpoints_for_network, should_fallback_to_genesis_hash_as_checkpoint) = match self {
Network::Mainnet => (MAINNET_CHECKPOINTS, false),
Network::Testnet(params) if params.is_default_testnet() => (TESTNET_CHECKPOINTS, false),
Network::Testnet(_params) => (TESTNET_CHECKPOINTS, true),
};
match checkpoint_list.hash(block::Height(0)) {
Some(hash) if hash == self.genesis_hash() => checkpoint_list,
Some(_) => {
panic!("The hard-coded genesis checkpoint does not match the network genesis hash")
// Check that the list starts with the correct genesis block and parses checkpoint list.
let first_checkpoint_height = checkpoints_for_network
.lines()
.next()
.map(checkpoint_height_and_hash);
match first_checkpoint_height {
// parse calls CheckpointList::from_list
Some(Ok((block::Height(0), hash))) if hash == self.genesis_hash() => {
checkpoints_for_network
.parse()
.expect("hard-coded checkpoint list parses and validates")
}
None => unreachable!("Parser should have checked for a missing genesis checkpoint"),
_ if should_fallback_to_genesis_hash_as_checkpoint => {
CheckpointList::from_list([(block::Height(0), self.genesis_hash())])
.expect("hard-coded checkpoint list parses and validates")
}
Some(Ok((block::Height(0), _))) => {
panic!("the genesis checkpoint does not match the {self} genesis hash")
}
Some(Ok(_)) => panic!("checkpoints must start at the genesis block height 0"),
Some(Err(err)) => panic!("{err}"),
None => panic!(
"there must be at least one checkpoint on default networks, for the genesis block"
),
}
}
}
/// Parses a checkpoint to a [`block::Height`] and [`block::Hash`].
fn checkpoint_height_and_hash(checkpoint: &str) -> Result<(block::Height, block::Hash), BoxError> {
let fields = checkpoint.split(' ').collect::<Vec<_>>();
if let [height, hash] = fields[..] {
Ok((height.parse()?, hash.parse()?))
} else {
Err(format!("Invalid checkpoint format: expected 2 space-separated fields but found {}: '{checkpoint}'", fields.len()).into())
}
}
/// A list of block height and hash checkpoints.
///
/// Checkpoints should be chosen to avoid forks or chain reorganizations,
@ -115,12 +134,7 @@ impl FromStr for CheckpointList {
let mut checkpoint_list: Vec<(block::Height, block::Hash)> = Vec::new();
for checkpoint in s.lines() {
let fields = checkpoint.split(' ').collect::<Vec<_>>();
if let [height, hash] = fields[..] {
checkpoint_list.push((height.parse()?, hash.parse()?));
} else {
Err(format!("Invalid checkpoint format: expected 2 space-separated fields but found {}: '{checkpoint}'", fields.len()))?;
};
checkpoint_list.push(checkpoint_height_and_hash(checkpoint)?);
}
CheckpointList::from_list(checkpoint_list)
@ -146,17 +160,9 @@ impl CheckpointList {
let checkpoints: BTreeMap<block::Height, block::Hash> =
original_checkpoints.into_iter().collect();
// Check that the list starts with the correct genesis block
// Check that the list starts with _some_ genesis block
match checkpoints.iter().next() {
// TODO: If required (we may not need checkpoints at all in Regtest or custom testnets):
// move this check to `<Network as ParameterCheckpoint>::checkpoint_list(&network)` method above (#8366),
// See <https://github.com/ZcashFoundation/zebra/pull/7924#discussion_r1385865347>
Some((block::Height(0), hash))
if (hash == &Network::Mainnet.genesis_hash()
|| hash == &Network::new_default_testnet().genesis_hash()) => {}
Some((block::Height(0), _)) => {
Err("the genesis checkpoint does not match the Mainnet or Testnet genesis hash")?
}
Some((block::Height(0), _hash)) => {}
Some(_) => Err("checkpoints must start at the genesis block height 0")?,
None => Err("there must be at least one checkpoint, for the genesis block")?,
};

View File

@ -237,6 +237,7 @@ fn checkpoint_list_load_hard_coded() -> Result<(), BoxError> {
let _ = Mainnet.checkpoint_list();
let _ = Network::new_default_testnet().checkpoint_list();
let _ = Network::new_regtest(Default::default()).checkpoint_list();
Ok(())
}

View File

@ -451,6 +451,7 @@ fn finalized_equals_pushed_history_tree() -> Result<()> {
/// Check that rejected blocks do not change the internal state of a genesis chain
/// in a non-finalized state.
#[test]
#[cfg(not(target_os = "windows"))]
fn rejection_restores_internal_state_genesis() -> Result<()> {
let _init_guard = zebra_test::init();

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};
@ -3099,3 +3101,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"
)
}