Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion crates/core/src/validation/fork_detection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,21 @@ pub trait MainchainView {
/// reads is missing or doesn't decode, where the Java throws; and
/// [`uncle_sum`]'s error where rskj's throws.
pub fn calculate(headers: &[Header]) -> Result<[u8; 12], ValidationError> {
if (headers.len() as u64) < REQUIRED_BLOCKS {
// rskj's `hasEnoughBlocksToCalculateForkDetectionData` refuses a view that
// is not *exactly* `requiredBlocks`, not merely one that is too short.
//
// The two agree on every input that exists today: `validate` asks for
// exactly `REQUIRED_BLOCKS` and every `MainchainView` caps what it returns
// at `count`. The difference is what a longer view would do -- rskj would
// refuse it, and `<` would quietly compute from the first 449 and accept
// the block. That is a consensus split arriving through a change to the
// view builder, which is a place nobody would look for one, so the guard
// says what it means instead.
//
// The miner's `mining::fork_detection::calculate` keeps `<` deliberately:
// it takes the best chain uncapped and returns empty data for a chain too
// short, which is what rskj's `BlockToMineBuilder` does.
if headers.len() as u64 != REQUIRED_BLOCKS {
return Err(ValidationError::ForkDetectionDataUnreadable);
}
let mut data = [0u8; 12];
Expand Down
47 changes: 47 additions & 0 deletions crates/core/src/validation/header_rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,53 @@ impl ParentHeaderValidator for BlockNumberRule {
}
}

/// rskj `BlockHeaderVersionRule`: a header's version must be the one its
/// height calls for.
///
/// 0 before RSKIP-351, 1 from it, 2 from RSKIP-535
/// ([`ChainConfig::header_version`]). rskj runs this in both the block rule
/// list and the snap rule list (`RskContext.getBlockValidationRule`,
/// `getSnapBlockValidationRule`).
///
/// # Why a missing rule is a split rather than a nicety
///
/// Nothing else rejects the mismatch. A header whose version byte is neither
/// 1 nor 2 is read as version 0 -- rustock mirrors rskj building a
/// `BlockHeaderV0` for it -- and a version-2 header below RSKIP-535 decodes
/// perfectly well. So without this rule such a header is accepted here while
/// rskj rejects it, which is the two clients on different chains.
///
/// # Genesis is exempt
///
/// rskj returns `true` for `header.isGenesis()` before looking at the version,
/// and so does this. Genesis comes from configuration rather than from a peer,
/// its version is whatever the file says, and a rule that rejected it would
/// stop the node on a chain whose genesis predates the activation.
pub struct HeaderVersionRule {
pub config: std::sync::Arc<crate::config::ChainConfig>,
}

impl HeaderValidator for HeaderVersionRule {
fn validate(&self, header: &Header) -> Result<(), ValidationError> {
if header.number == 0 {
return Ok(());
}
let required = self.config.activation_heights.header_version(header.number);
// A header with no version fields carries no version, which is what
// version 0 means: before RSKIP-351 there is no field to read, and
// rskj's `BlockHeaderV0.getVersion()` answers 0.
let got = header.version_fields.as_ref().map_or(0, |v| v.version);
if got != required {
return Err(ValidationError::HeaderVersionMismatch {
number: header.number,
required,
got,
});
}
Ok(())
}
}

pub struct ParentHashRule;
impl ParentHeaderValidator for ParentHashRule {
fn validate_with_parent(&self, header: &Header, parent: &Header) -> Result<(), ValidationError> {
Expand Down
25 changes: 24 additions & 1 deletion crates/core/src/validation/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,23 @@ pub enum ValidationError {
#[error("Extra data is {got} bytes, over the {max}-byte maximum")]
ExtraDataTooLarge { max: usize, got: usize },

#[error("Header version is {got}, but block {number} requires {required}")]
HeaderVersionMismatch { number: u64, required: u8, got: u8 },

/// rskj `BlockValidatorImpl.isValid`: `if (block.isGenesis()) return false`.
///
/// Not a statement that the chain's genesis is wrong. It is the validator
/// refusing to answer for a block that never arrives through validation --
/// genesis is loaded from configuration -- so a height-0 block offered to
/// this entry point came from somewhere it should not have.
#[error("Block 0 is not validated: genesis is loaded from configuration, not accepted from a peer")]
GenesisNotValidated,

/// rskj `BlockUnclesHashValidationRule`, which it runs inside
/// `BlockUnclesValidationRule` and therefore in the block rule list.
#[error("Ommers hash is {header}, but the uncle list hashes to {computed}")]
OmmersHashMismatch { header: B256, computed: B256 },

/// Read whole, as rskj's `Coin`s.
#[error("Minimum gas price {got} outside the allowed range [{lower}, {upper}]")]
MinGasPriceOutOfRange {
Expand Down Expand Up @@ -244,6 +261,12 @@ impl HeaderVerifier {
// sync run it: a block no later than its parent is one rskj imports.
.with_static_rule(TimestampRule::new(config.max_future_block_time))
.with_static_rule(block_rules::ExtraDataRule::default())
// rskj's `BlockHeaderVersionRule`, which `RskContext` puts in both
// the block rule list and the snap one. Rustock computed the
// required version for *building* a header and nothing checked an
// incoming one against it, so a header declaring a version its
// height does not call for was accepted here and rejected there.
.with_static_rule(HeaderVersionRule { config: config.clone() })
.with_parent_rule(BlockNumberRule)
.with_parent_rule(BlockParentGasLimitRule { config: config.clone() })
.with_parent_rule(block_rules::PrevMinGasPriceRule)
Expand Down Expand Up @@ -370,7 +393,7 @@ pub mod header_rules;
pub mod difficulty;
pub mod merged_mining;

pub use header_rules::{BlockNumberRule, ParentHashRule, TimestampRule, GasUsedRule, GasLimitRule, BlockParentGasLimitRule};
pub use header_rules::{BlockNumberRule, ParentHashRule, TimestampRule, GasUsedRule, GasLimitRule, BlockParentGasLimitRule, HeaderVersionRule};
pub use difficulty::DifficultyRule;
pub use merged_mining::{BitcoinTimestampRule, MergedMiningRule};
pub use block_rules::{
Expand Down
142 changes: 142 additions & 0 deletions crates/core/src/validation/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1646,6 +1646,29 @@ impl uncles::AncestorSource for Ancestry {
/// rule an uncle faces runs, and without RSKIPUMM, so these headers need no
/// UMM root: `a_header_carries_the_fields_rskj_reads_at_its_height` holds
/// regtest's to it.
/// Give a fixture header the version its height calls for, the way the mining
/// template does (`mining::template`).
///
/// Needed because `HeaderVersionRule` -- rskj's `BlockHeaderVersionRule` --
/// rejects a header whose version disagrees with its height, and these
/// fixtures are built on regtest, where RSKIP-351 and RSKIP-535 are active
/// from the start. An unversioned fixture there is not a header the chain
/// would ever carry, so stamping it is making the fixture realistic rather
/// than working around the rule.
///
/// Before sealing, always: the merged-mining proof commits to the header's
/// hash, and the version is part of it.
fn stamp_version(header: &mut Header, config: &crate::config::ChainConfig) {
let version = config.activation_heights.header_version(header.number);
header.version_fields = (version > 0).then(|| {
crate::types::header::HeaderVersionFields {
version,
edges: config.activation_heights.edges_active(header.number).then(Vec::new),
base_event: None,
}
});
}

fn uncle_config() -> Arc<crate::config::ChainConfig> {
let mut config = crate::config::ChainConfig::regtest();
config.max_future_block_time = 60;
Expand Down Expand Up @@ -1674,6 +1697,7 @@ fn uncle_chain(base: u64) -> (Ancestry, Header, Header) {
/// its parent calls for.
fn uncle_of(parent: &Header, timestamp: u64) -> Header {
let mut uncle = create_dummy_header(parent.number + 1, timestamp, parent.hash());
stamp_version(&mut uncle, &uncle_config());
uncle.beneficiary = Address::repeat_byte(0x0b);
uncle.difficulty = DifficultyRule {
config: uncle_config(),
Expand Down Expand Up @@ -1868,6 +1892,124 @@ fn default_rsk_holds_uncles_to_rskjs_uncle_rules() {
);
}

/// rskj's `hasEnoughBlocksToCalculateForkDetectionData` refuses a view that is
/// not exactly `requiredBlocks`. Rustock refused only a short one, which
/// agrees on every input that exists -- `validate` asks for exactly
/// `REQUIRED_BLOCKS` and every `MainchainView` caps at `count` -- and would
/// have differed on a longer one, computing from the first 449 and accepting a
/// block rskj refuses.
#[test]
fn a_mainchain_view_of_the_wrong_length_is_refused_either_way() {
use crate::validation::fork_detection::{calculate, REQUIRED_BLOCKS};

let view = |n: u64| -> Vec<Header> {
(0..n).map(|i| create_dummy_header(n - i, 1000 + i, B256::ZERO)).collect()
};

for len in [0, 1, REQUIRED_BLOCKS - 1] {
assert_eq!(
calculate(&view(len)),
Err(ValidationError::ForkDetectionDataUnreadable),
"a view of {len} is too short"
);
}
for len in [REQUIRED_BLOCKS + 1, REQUIRED_BLOCKS + 100] {
assert_eq!(
calculate(&view(len)),
Err(ValidationError::ForkDetectionDataUnreadable),
"a view of {len} is too long, and rskj refuses it rather than \
computing from the first {REQUIRED_BLOCKS}"
);
}
// No positive case here on purpose. A view of exactly `REQUIRED_BLOCKS`
// still fails on these fixtures, because they carry no Bitcoin headers for
// the commit-to-parents vector to read -- and that failure uses the *same*
// error variant, so this test could not tell "passed the length guard"
// from "failed the next step". The positive case belongs where there is
// real data for it: `mainnet_block_rules::fork_detection_data_matches_on_\
// real_blocks` recomputes the data for real blocks and compares it against
// what their headers carry, which is better evidence than a fixture could
// give.
}

/// rskj `BlockHeaderVersionRule`, which Rustock did not have: it computed the
/// required version for *building* a header and nothing checked an incoming
/// one, so a header declaring a version its height does not call for was
/// accepted here and rejected by rskj -- the two clients on different chains.
///
/// Every case below is one rskj decides the same way.
#[test]
fn a_header_version_the_height_does_not_call_for_is_refused() {
use crate::validation::HeaderVersionRule;

let at = |rskip351: Option<u64>, rskip535: Option<u64>| {
let mut config = crate::config::ChainConfig::regtest();
config.activation_heights.rskip351 = rskip351;
config.activation_heights.rskip535 = rskip535;
HeaderVersionRule { config: Arc::new(config) }
};
let header = |number: u64, version: Option<u8>| {
let mut h = create_dummy_header(number, 1000, B256::ZERO);
h.version_fields = version.map(|version| crate::types::header::HeaderVersionFields {
version,
edges: None,
base_event: None,
});
h
};

// Before RSKIP-351 the required version is 0, which is what an
// unversioned header answers.
let before = at(None, None);
assert_eq!(before.validate(&header(100, None)), Ok(()));
for declared in [1u8, 2] {
assert_eq!(
before.validate(&header(100, Some(declared))),
Err(ValidationError::HeaderVersionMismatch {
number: 100,
required: 0,
got: declared
}),
"version {declared} below RSKIP-351"
);
}

// From RSKIP-351 and before RSKIP-535 it is 1. A version-2 header here is
// the cheap split: the byte is free to set and it decodes perfectly well.
let v1 = at(Some(50), None);
assert_eq!(v1.validate(&header(100, Some(1))), Ok(()));
assert_eq!(
v1.validate(&header(100, Some(2))),
Err(ValidationError::HeaderVersionMismatch { number: 100, required: 1, got: 2 })
);
assert_eq!(
v1.validate(&header(100, None)),
Err(ValidationError::HeaderVersionMismatch { number: 100, required: 1, got: 0 }),
"an unversioned header above RSKIP-351 answers 0, which is not 1"
);
// Either side of the activation, one block apart.
assert_eq!(v1.validate(&header(49, None)), Ok(()));
assert_eq!(v1.validate(&header(50, Some(1))), Ok(()));

// From RSKIP-535 it is 2.
let v2 = at(Some(50), Some(80));
assert_eq!(v2.validate(&header(100, Some(2))), Ok(()));
assert_eq!(
v2.validate(&header(100, Some(1))),
Err(ValidationError::HeaderVersionMismatch { number: 100, required: 2, got: 1 })
);
assert_eq!(v2.validate(&header(79, Some(1))), Ok(()));
assert_eq!(v2.validate(&header(80, Some(2))), Ok(()));

// Genesis is exempt, as rskj returns true for `header.isGenesis()` before
// looking at the version. It comes from configuration rather than a peer,
// and a rule that refused it would stop a node whose genesis file predates
// the activation.
for version in [None, Some(1), Some(2)] {
assert_eq!(v2.validate(&header(0, version)), Ok(()), "genesis, {version:?}");
}
}

/// rskj's trunk takes the timestamp rule on the header alone. A block no
/// later than its parent is one `BlockValidatorImpl` imports -- the parent
/// form is for uncles, and for rskj's relay -- so this node must take it
Expand Down
12 changes: 10 additions & 2 deletions crates/execution/src/mining/template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -450,12 +450,20 @@ impl BlockTemplateBuilder {
if uncles.is_empty() {
return uncles;
}
// The rule reads the block's number, its parent's hash and its
// uncles, and nothing else of its header.
// The rule reads the block's number, its parent's hash, its uncles and
// the ommers hash it claims of them -- rskj checks that inside
// `BlockUnclesValidationRule` -- and nothing else of its header.
//
// So the candidate has to claim the right one. Everything else here is
// the parent's, and the parent's ommers hash is the hash of a
// different list: inheriting it would make every candidate fail the
// check and the miner would drop every uncle it was offered, silently
// and with no uncle reward.
let block = Block {
header: Header {
number,
parent_hash: parent.hash(),
ommers_hash: crate::processor::compute_ommers_hash(&uncles),
cached_hash: None,
cached_hash_for_merged_mining: None,
..parent.clone()
Expand Down
Loading
Loading