diff --git a/crates/core/src/validation/fork_detection.rs b/crates/core/src/validation/fork_detection.rs index 536f7d2c..0f19e2dd 100644 --- a/crates/core/src/validation/fork_detection.rs +++ b/crates/core/src/validation/fork_detection.rs @@ -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]; diff --git a/crates/core/src/validation/header_rules.rs b/crates/core/src/validation/header_rules.rs index 11164729..9da4b788 100644 --- a/crates/core/src/validation/header_rules.rs +++ b/crates/core/src/validation/header_rules.rs @@ -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, +} + +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> { diff --git a/crates/core/src/validation/mod.rs b/crates/core/src/validation/mod.rs index 0360eefc..471dda2b 100644 --- a/crates/core/src/validation/mod.rs +++ b/crates/core/src/validation/mod.rs @@ -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 { @@ -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) @@ -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::{ diff --git a/crates/core/src/validation/tests.rs b/crates/core/src/validation/tests.rs index d8247e2e..f0ac40f5 100644 --- a/crates/core/src/validation/tests.rs +++ b/crates/core/src/validation/tests.rs @@ -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 { let mut config = crate::config::ChainConfig::regtest(); config.max_future_block_time = 60; @@ -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(), @@ -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
{ + (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, rskip535: Option| { + 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| { + 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 diff --git a/crates/execution/src/mining/template.rs b/crates/execution/src/mining/template.rs index 2d8aa556..4cfdb530 100644 --- a/crates/execution/src/mining/template.rs +++ b/crates/execution/src/mining/template.rs @@ -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() diff --git a/crates/execution/src/processor.rs b/crates/execution/src/processor.rs index fd49b10a..b1297bda 100644 --- a/crates/execution/src/processor.rs +++ b/crates/execution/src/processor.rs @@ -765,12 +765,19 @@ impl BlockProcessor { ) -> Result<(), ValidationError> { let number = block.header.number; - // rskj `BlockValidatorImpl.isValid` refuses genesis outright: it is - // loaded from the genesis file, never validated. Genesis carries no - // REMASC transaction, so running these rules on it would reject the - // chain's first block. + // rskj `BlockValidatorImpl.isValid` refuses genesis outright -- + // `if (block.isGenesis()) { return false; }` -- because genesis is + // loaded from the genesis file and never validated. This used to + // return `Ok(())` instead, which is the opposite verdict for the same + // call: any caller that branched on the result behaved oppositely on + // the two clients. + // + // The rules themselves cannot run on genesis either way: it carries no + // REMASC transaction, so the body rules would reject it for a reason + // that says nothing about whether it is the right genesis. Refusing to + // answer is the honest verdict, and it is rskj's. if number == 0 { - return Ok(()); + return Err(ValidationError::GenesisNotValidated); } self.validate_block_body_rules(block, parent)?; @@ -806,6 +813,25 @@ impl BlockProcessor { UNCLE_GENERATION_LIMIT, UNCLE_LIST_LIMIT, }; + // rskj runs `BlockUnclesHashValidationRule` inside + // `BlockUnclesValidationRule`, so the ommers hash is checked during + // *validation*. Rustock checked it only in `process_block_inner`, + // during execution, which agrees on every path that executes -- and + // differs on any that validates without executing, which is what snap + // and relay do. + // + // Still checked during execution too. The cost is one keccak over a + // list that holds at most ten headers, and a check that is cheap and + // in both places cannot be the one someone later moves to the wrong + // side of a branch. + let computed_ommers_hash = compute_ommers_hash(&block.ommers); + if !block.header.has_ommers_hash(computed_ommers_hash) { + return Err(ValidationError::OmmersHashMismatch { + header: block.header.ommers_hash, + computed: computed_ommers_hash, + }); + } + let ancestry = self.ancestry(); let header_rules = rsk_header_rules(self.chain_config.clone()); let parent_rules = rsk_parent_rules(self.chain_config.clone()); @@ -3483,6 +3509,52 @@ mod tests { } } + /// rskj runs `BlockUnclesHashValidationRule` inside + /// `BlockUnclesValidationRule`, so the ommers hash is checked during + /// validation. Rustock checked it only while executing, which agrees on + /// every path that executes and differs on any that validates without -- + /// snap and relay do exactly that. + #[test] + fn a_block_whose_ommers_hash_lies_is_refused_without_executing_it() { + let dir = tempfile::tempdir().unwrap(); + let block_store = Arc::new(BlockStore::open(dir.path()).unwrap()); + let processor = BlockProcessor::new(test_hardfork_cfg(), block_store.clone()) + .with_chain_config(uncle_config()); + + let mut genesis = dummy_header(0); + genesis.difficulty = U256::from(1); + let b1 = child_of(1, &genesis, 1_700_000_010); + let b2 = child_of(2, &b1, 1_700_000_030); + for header in [&genesis, &b1, &b2] { + block_store.put_header(header).unwrap(); + } + let uncle = child_of(2, &b1, 1_700_000_040); + + // The honest block passes the uncle rules: whatever else this test + // shows, it must not pass for want of a well-formed block. + let honest = naming(3, &b2, &uncle, &[]); + let before = processor.validate_uncles(&honest); + assert!( + !matches!(before, Err(ValidationError::OmmersHashMismatch { .. })), + "the control block must not fail the hash check: {before:?}" + ); + + // Now claim an ommers hash the list does not have, leaving everything + // else untouched. + let mut lying = honest.clone(); + lying.header.ommers_hash = B256::repeat_byte(0xAB); + let verdict = processor.validate_uncles(&lying); + assert!( + matches!( + verdict, + Err(ValidationError::OmmersHashMismatch { header, computed }) + if header == B256::repeat_byte(0xAB) + && computed == compute_ommers_hash(&lying.ommers) + ), + "validation must refuse it, not leave it to execution: {verdict:?}" + ); + } + /// The import path's uncle rule holds each uncle to rskj's rules. It used /// to check only an uncle's place in the chain, so a block could name one /// that did no work and have its difficulty counted all the same. @@ -3570,8 +3642,18 @@ mod tests { } // Newest first, from `tip` down, as the rule reads them. let data_from = |tip: usize| { - let view: Vec
= chain[..=tip].iter().rev().cloned().collect(); - calculate(&view).expect("449 headers to read") + // Exactly `REQUIRED_BLOCKS`, which is what `validate` asks its + // `MainchainView` for and what every implementation caps at. This + // used to hand over the whole chain and lean on the calculator + // taking the first 449 -- a shape no caller produces, and one + // rskj's `hasEnoughBlocksToCalculateForkDetectionData` refuses. + let view: Vec
= chain[..=tip] + .iter() + .rev() + .take(REQUIRED_BLOCKS as usize) + .cloned() + .collect(); + calculate(&view).expect("exactly REQUIRED_BLOCKS headers to read") }; let tip = chain.len() - 1; diff --git a/crates/execution/tests/mainnet_block_rules.rs b/crates/execution/tests/mainnet_block_rules.rs index 69979cfd..9e3ce2c5 100644 --- a/crates/execution/tests/mainnet_block_rules.rs +++ b/crates/execution/tests/mainnet_block_rules.rs @@ -29,6 +29,72 @@ fn db_path() -> Option { /// /// Dense rather than sampled around iris300, because the activation edge is /// where an off-by-one in the height comparison would show. +/// `HeaderVersionRule` against the chain itself. +/// +/// This rule *rejects* headers, so the risk it carries is the usual one for +/// this file: a required version that disagrees with what mainnet actually +/// carries would reject real blocks and halt the node. Mainnet has RSKIP-351 +/// unscheduled, so every header from genesis to the tip must answer version 0 +/// -- and that is a claim about 9.4 million real headers, not about the +/// config, which is why it is checked here rather than reasoned about. +/// +/// Dense at the start and the tip, sampled in between: a version byte appearing +/// anywhere would be a header built by something other than the clients that +/// built this chain. +#[test] +#[ignore = "requires a synced block store (RUSTOCK_BLOCKS_DB)"] +fn the_header_version_rule_accepts_every_sampled_mainnet_header() { + use rustock_core::config::ChainConfig; + use rustock_core::validation::{HeaderValidator, HeaderVersionRule}; + + let Some(path) = db_path() else { + eprintln!("RUSTOCK_BLOCKS_DB not set; skipping"); + return; + }; + let store = Arc::new(BlockStore::open_read_only(&path).expect("open block store")); + let head = store + .head() + .expect("head") + .and_then(|h| store.header(h).ok().flatten()) + .expect("head header"); + + let config = Arc::new(ChainConfig::mainnet()); + assert_eq!( + config.activation_heights.header_version(head.number), + 0, + "mainnet has RSKIP-351 unscheduled, so the required version is 0 everywhere; \ + if that has changed this test needs the activation height, not a new expectation" + ); + let rule = HeaderVersionRule { config }; + + let mut heights: Vec = (1..=head.number).step_by(10_000).collect(); + heights.extend(1..=200u64.min(head.number)); + heights.extend((head.number.saturating_sub(200))..=head.number); + heights.sort_unstable(); + heights.dedup(); + + let mut checked = 0usize; + let mut versioned: Vec<(u64, String)> = Vec::new(); + for number in heights { + let Some(hash) = store.canonical_hash(number).ok().flatten() else { continue }; + let Some(header) = store.header(hash).ok().flatten() else { continue }; + checked += 1; + if let Err(e) = rule.validate(&header) { + versioned.push((number, e.to_string())); + } + } + + assert!(checked > 100, "only {checked} headers read; is the store synced?"); + assert!( + versioned.is_empty(), + "the header-version rule rejects {} real mainnet header(s) out of {checked} -- a rule \ + stricter than the chain it must accept is a fork: {:?}", + versioned.len(), + &versioned[..versioned.len().min(10)] + ); + eprintln!("header version: {checked} mainnet headers, all version 0 as required"); +} + #[test] #[ignore = "requires a synced block store (RUSTOCK_BLOCKS_DB)"] fn rskip179_accepts_every_sampled_mainnet_block() {