diff --git a/crates/cli/examples/bridge_event_width.rs b/crates/cli/examples/bridge_event_width.rs new file mode 100644 index 00000000..55628b06 --- /dev/null +++ b/crates/cli/examples/bridge_event_width.rs @@ -0,0 +1,153 @@ +//! Did the bridge ever log an **empty** single dynamic field? +//! +//! The bridge encodes an event whose data is one dynamic `bytes`/`string` by +//! sizing the content as `((len - 1) / 32 + 1) * 32` in signed truncating +//! division (rskj `SolidityType.BytesType.encode`). At `len = 0` that is +//! `(-1 / 32 + 1) * 32 = 32`, so an empty field still emits one zero word and +//! the data is **96 octets** where the canonical ABI gives 64. +//! +//! Whether any caller ever produced it is a question about the chain, and the +//! evidence is in the **receipts** rather than in the execution -- so this needs +//! no replay. It is the cheapest measurement of its kind: a sequential read of +//! stored receipts. +//! +//! # Why "data is 96 octets" is the wrong test on its own +//! +//! The encoding is `offset(32) ++ length(32) ++ content`, and the content is +//! padded to a whole number of words. So a field of **1 to 32** octets also +//! encodes to exactly 96 -- legitimately, and commonly, since a 32-octet hash +//! is the ordinary case. Filtering on the total alone would report every one of +//! those as a hit. +//! +//! What distinguishes the quirk is the **length word**: 96 octets *and* a +//! declared length of zero. This reports both numbers, because the gap between +//! them is what shows the sharper test was needed. +//! +//! # What it reads +//! +//! Every log of every canonical block in the range, filtered to the bridge +//! address. Logs are what the chain recorded, which is what binds: an argument +//! from today's callers being non-empty is a fact about code, and can be +//! falsified by a version of that code nobody is reading. +//! +//! Read-only, and safe to run against a live node. +//! +//! ```text +//! bridge_event_width [--from N] [--to N] +//! ``` + +use anyhow::{Context, Result}; +use rustock_storage::BlockStore; +use std::time::Instant; + +/// rskj `PrecompiledContracts.BRIDGE_ADDR`. +const BRIDGE: &str = "0000000000000000000000000000000001000006"; + +fn flag(name: &str) -> Option { + let args: Vec = std::env::args().collect(); + args.windows(2).find(|w| w[0] == format!("--{name}")).map(|w| w[1].clone()) +} + +fn main() -> Result<()> { + let data_dir = std::env::args() + .nth(1) + .filter(|a| !a.starts_with("--")) + .context("usage: bridge_event_width [--from N] [--to N]")?; + let store = BlockStore::open_read_only(&data_dir) + .with_context(|| format!("opening {data_dir} read-only"))?; + let head = store + .head()? + .and_then(|h| store.header(h).ok().flatten()) + .context("no chain head")? + .number; + + let from: u64 = flag("from").and_then(|v| v.parse().ok()).unwrap_or(1); + let to: u64 = flag("to").and_then(|v| v.parse().ok()).unwrap_or(head).min(head); + let bridge: Vec = alloy_primitives::hex::decode(BRIDGE)?; + + println!("scanning receipts of #{from}..#{to} for bridge logs"); + + let (mut blocks, mut bridge_logs, mut width_96, mut empty_96) = (0u64, 0u64, 0u64, 0u64); + let mut hits: Vec<(u64, String)> = Vec::new(); + let started = Instant::now(); + let mut last_report = Instant::now(); + + for number in from..=to { + let Some(hash) = store.canonical_hash(number).ok().flatten() else { continue }; + let Some(receipts) = store.receipts(hash).ok().flatten() else { continue }; + blocks += 1; + for receipt in &receipts { + for log in &receipt.logs { + if log.address.as_slice() != bridge.as_slice() { + continue; + } + bridge_logs += 1; + if log.data.len() != 96 { + continue; + } + width_96 += 1; + // offset(32) ++ length(32) ++ content. A declared length of + // zero with a word of content present is the quirk; 1..=32 is + // an ordinary short field that happens to be the same width. + let declared = &log.data[32..64]; + if declared.iter().all(|b| *b == 0) { + empty_96 += 1; + let topic = log + .topics + .first() + .map(|t| format!("{t:?}")) + .unwrap_or_else(|| "(no topics)".into()); + if hits.len() < 50 { + hits.push((number, topic)); + } + } + } + } + if last_report.elapsed().as_secs() >= 15 { + let done = number - from + 1; + let rate = done as f64 / started.elapsed().as_secs_f64().max(0.001); + eprintln!( + " #{number}: {done} blocks ({rate:.0}/s), {bridge_logs} bridge logs, \ + {width_96} of 96 octets, {empty_96} of them empty" + ); + last_report = Instant::now(); + } + } + + println!(); + println!("blocks with receipts {blocks}"); + println!("bridge logs {bridge_logs}"); + println!(" of exactly 96 octets {width_96} <- what a width-only test would report"); + println!(" of those, length zero {empty_96} <- the 96-octet empty encoding"); + println!("elapsed {:.0}s", started.elapsed().as_secs_f64()); + + if !hits.is_empty() { + println!(); + println!("occurrences (block, topic0):"); + for (number, topic) in &hits { + println!(" #{number} {topic}"); + } + if empty_96 as usize > hits.len() { + println!(" ... and {} more", empty_96 as usize - hits.len()); + } + } + + println!(); + if empty_96 == 0 { + println!( + "NONE FOUND in #{from}..#{to}. No bridge log in this range carries the 96-octet \ + empty encoding, so as far as this chain's receipts go, no caller ever produced \ + an empty single dynamic field." + ); + } else { + println!( + "{empty_96} occurrence(s). The 96-octet encoding is in the chain's receipts, so \ + it is frozen into a receipts root and the behaviour is load-bearing." + ); + } + if blocks == 0 { + println!("but no receipts were read at all -- check the data directory and the range."); + std::process::exit(2); + } + Ok(()) +} diff --git a/crates/cli/examples/opcode_census.rs b/crates/cli/examples/opcode_census.rs index 97044317..8e832700 100644 --- a/crates/cli/examples/opcode_census.rs +++ b/crates/cli/examples/opcode_census.rs @@ -368,6 +368,29 @@ fn main() -> Result<()> { // judgement -- 443 of the first run's hits were the metadata trailer and // constant pools, and the only way to be sure of the survivors is to read // the bytes around them. + // Does an address exist as an account in the state trie? One lookup, no + // walk. Written to test a proposed screen for EVM-046 -- "no active + // precompile exists as an account, so no dirty-high-bits call ever landed" + // -- which needs the premise checked before it can be leaned on. + if let Some(hex) = flag("account") { + let node = TrieNode::from_message(&root_bytes, store.as_ref()); + for one in hex.split(',') { + let bytes = alloy_primitives::hex::decode(one.trim().trim_start_matches("0x")) + .context("--account takes comma-separated hex addresses")?; + let key = rustock_trie::account_key_from_bytes(&bytes); + let found = node.get(&rustock_trie::TrieKeySlice::from_key(&key), store.as_ref()); + println!( + " 0x{} {}", + one.trim().trim_start_matches("0x"), + match found { + Some(v) => format!("EXISTS ({} bytes of account state)", v.len()), + None => "absent".to_string(), + } + ); + } + return Ok(()); + } + if let Some(hex) = flag("dump") { let bytes = alloy_primitives::hex::decode(hex.trim_start_matches("0x")) .context("--dump takes a hex address")?; diff --git a/crates/cli/examples/reexec_all.rs b/crates/cli/examples/reexec_all.rs index 6a7c910a..a27a7d43 100644 --- a/crates/cli/examples/reexec_all.rs +++ b/crates/cli/examples/reexec_all.rs @@ -760,6 +760,63 @@ fn report_rsk_opcodes(done: u64, planned: u64) { "contracts deployed in this run: {created}, of which {headered} carried the RSK \ code header" ); + // The legacy-branch census. Printed as a table with each row's window, so + // a zero is always read against the range that produced it. + let census = rustock_execution::legacy_census::census(); + println!(); + println!("legacy branches taken in this run:"); + for (rule, what, window, hits) in &census { + println!(" {rule:<8} {hits:>10} {what} [{window}]"); + } + // A campaign that only ever returns zero has not been validated. The + // migration-end-age window is known occupied -- using the ordinary end age + // inside it diverged a real mainnet block -- so a zero there means the + // instrument is broken and every other zero in the table is worthless. + if rustock_execution::legacy_census::positive_control_fired() { + println!(" positive control fired: the counters are live, so the zeros above mean something."); + } else { + println!( + " POSITIVE CONTROL DID NOT FIRE. Either this run did not cover \ + #4,976,300..#5,468,000, or the counters are not wired to the branches they \ + name. Until that is resolved, treat every zero above as unproven." + ); + } + + let [staticcalls, with_value] = + rustock_execution::rsk_instructions::staticcall_value_counts(); + println!( + "seven-operand STATICCALLs (RSKIP-91 to RSKIP-103, #729,000..#1,052,700): \ + {staticcalls} executed, {with_value} carrying a non-zero value" + ); + if staticcalls > 0 && with_value == 0 { + println!( + " the form ran but was never passed a value, so nothing on this chain ever \ + moved funds through a static call." + ); + } else if staticcalls == 0 { + println!( + " the seven-operand form never ran in this range -- which for a range below \ + #729,000 means only that the window was not reached." + ); + } + + let [oversize, unpayable, largest] = + rustock_execution::rsk_instructions::empty_deploy_counts(); + println!( + "internal creations below RSKIP-453 that deployed empty instead of reverting: \ + {oversize} over the maximum code size, {unpayable} unable to pay the code deposit; \ + largest code any of them returned: {largest} octets" + ); + // The bound matters more than the counts. RSKIP-453 is #7,338,024 on + // mainnet, so a run that stops below that has only looked at part of the + // era where the quirk applies, and zero means "not here" rather than + // "never". + if oversize == 0 && unpayable == 0 { + println!( + " neither branch fired in this range. Both are dead guards below the highest \ + block this run reached -- not below #7,338,024, unless the run covered it." + ); + } if created > 0 && headered == 0 { println!( " no contract in this range was ever deployed with a header. A census of the \ diff --git a/crates/cli/examples/tx_signature_v.rs b/crates/cli/examples/tx_signature_v.rs new file mode 100644 index 00000000..6ab3243b --- /dev/null +++ b/crates/cli/examples/tx_signature_v.rs @@ -0,0 +1,282 @@ +//! What values of the signature octet `v` does this chain actually carry? +//! +//! `v` is one octet, decomposed as `recoveryId = 1 if v is even else 0` and +//! `chainId = (v - 35) / 2` with the subtraction **floored at zero**. The +//! accepted set is `27, 28, 34 … 255`; `29` through `33` are refused and the +//! signature is never taken (`EVM-073`). +//! +//! Two values are worth finding, and neither is EIP-155 behaviour: +//! +//! - **`v = 34`** is accepted and means exactly what `28` means: the floored +//! subtraction sends it to chain 0, and 34 being even gives recovery id 1 -- +//! the same pair. So two octets encode one signature meaning, and 34 is not a +//! value EIP-155 can produce. Narrowing the accepted set to `27, 28, 35 …` +//! would make it exactly EIP-155 plus the two legacy values, which is a +//! de-divergence rather than a special case moved elsewhere. +//! - **`v = 35`** names chain **0**, not chain 1. +//! +//! **A single `v = 34` kills that proposal outright**, because such a +//! transaction sits in a valid block whose sender was recovered from it: +//! refusing the octet later would make that block invalid. So this is a scan +//! whose value is entirely in the possibility of one hit. +//! +//! It needs no replay -- `v` is a stored field -- and no recipient to match, so +//! it is cheaper than a selector scan: a walk of transaction bodies testing one +//! integer. +//! +//! The whole histogram is reported rather than just the two values, because the +//! distribution is the context that makes a zero readable: a run that found no +//! `34` among a hundred transactions has shown nothing, and one that found none +//! among sixty million has. +//! +//! Read-only, and safe to run against a live node. +//! +//! ```text +//! tx_signature_v [--from N] [--to N] # canonical blocks, exact +//! tx_signature_v --screen # every stored body, faster +//! ``` +//! +//! `--screen` iterates the bodies column family sequentially, which skips the +//! canonical-hash lookup and the random read per block -- where the exact walk +//! spends its time. It covers non-canonical bodies too, so it is a superset: +//! nothing found settles the question, a hit needs the exact walk over the +//! range concerned. + +use alloy_rlp::{Decodable, Header as RlpHeader}; +use anyhow::{Context, Result}; +use rustock_core::Transaction; +use rustock_storage::BlockStore; +use std::collections::BTreeMap; +use std::time::Instant; + +fn flag(name: &str) -> Option { + let args: Vec = std::env::args().collect(); + args.windows(2).find(|w| w[0] == format!("--{name}")).map(|w| w[1].clone()) +} + +/// What `v` means under `EVM-073`, for the values worth naming in the report. +fn note(v: u64) -> &'static str { + match v { + 0 => "no signature", + 27 | 28 => "legacy, pre-EIP-155", + 29..=33 => "REFUSED by EVM-073 -- should be impossible in a block", + 34 => "ACCEPTED, means exactly what 28 means -- not an EIP-155 value", + 35 | 36 => "chain 0 (the floored subtraction)", + 95 | 96 => "chain 30, mainnet", + 97 | 98 => "chain 31, testnet", + _ => "", + } +} + +/// The `v` octets of one stored body, decoding only the transaction list. +/// +/// The ommers that follow need the store's own header reader, and nothing here +/// looks at them, so the decode stops once the transactions are out. +fn body_v_values(bytes: &[u8]) -> Result> { + let mut buf = bytes; + let outer = RlpHeader::decode(&mut buf)?; + let mut body = &buf[..outer.payload_length]; + let txs = RlpHeader::decode(&mut body)?; + let mut txs_buf = &body[..txs.payload_length]; + let mut out = Vec::new(); + while !txs_buf.is_empty() { + out.push(Transaction::decode(&mut txs_buf)?.v); + } + Ok(out) +} + +/// Sequential pass over the bodies column family: no canonical-hash lookup and +/// no random read per block, which is where the per-block walk spends its time. +/// +/// It is a **screen, not an answer**, and in one direction only. The column +/// family holds every body the node ever stored, canonical or not, so this is a +/// superset: finding nothing here settles the canonical question outright, +/// while a hit has to be followed up with the per-block walk, because a +/// transaction in an orphaned block invalidates nothing. +fn screen(data_dir: &str) -> Result<()> { + use rocksdb::{IteratorMode, Options, DB}; + + let mut opts = Options::default(); + opts.create_if_missing(false); + opts.set_max_open_files(256); + let cfs = [ + "headers", + "block_numbers", + "total_difficulty", + "block_bodies", + "receipts", + "tx_index", + "trie_nodes", + ]; + let db = DB::open_cf_for_read_only(&opts, data_dir, cfs, false) + .with_context(|| format!("opening {data_dir} read-only"))?; + let cf = db.cf_handle("block_bodies").context("no block_bodies column family")?; + + println!("screening every stored body sequentially (canonical and not)"); + let mut seen: BTreeMap = BTreeMap::new(); + let (mut bodies, mut txs, mut undecodable) = (0u64, 0u64, 0u64); + let started = Instant::now(); + let mut last_report = Instant::now(); + + for item in db.iterator_cf(cf, IteratorMode::Start) { + let (_, bytes) = item?; + bodies += 1; + match body_v_values(&bytes) { + Ok(values) => { + txs += values.len() as u64; + for v in values { + *seen.entry(v).or_default() += 1; + } + } + // Counted rather than ignored: a body this cannot read is a body + // whose `v` values were not inspected, and a screen that quietly + // skipped some would report a zero it has not earned. + Err(_) => undecodable += 1, + } + if last_report.elapsed().as_secs() >= 15 { + eprintln!( + " {bodies} bodies ({:.0}/s), {txs} transactions, {} distinct v, \ + {undecadable} unreadable", + bodies as f64 / started.elapsed().as_secs_f64().max(0.001), + seen.len(), + undecadable = undecodable, + ); + last_report = Instant::now(); + } + } + + println!(); + println!("bodies read {bodies}"); + println!("transactions {txs}"); + println!("unreadable bodies {undecodable}"); + println!("elapsed {:.0}s", started.elapsed().as_secs_f64()); + println!(); + println!(" v count meaning"); + for (v, count) in &seen { + println!("{v:>13} {count:>10} {}", note(*v)); + } + println!(); + let v34 = seen.get(&34).copied().unwrap_or(0); + if v34 == 0 && undecodable == 0 { + println!( + "SCREEN CLEAN: no v = 34 in any stored body, canonical or not, across {txs} \ + transactions. Since every canonical body is among these, the canonical answer \ + is zero and no per-block walk is needed." + ); + } else if v34 == 0 { + println!( + "No v = 34 found, but {undecodable} body/bodies could not be decoded, so the \ + screen is incomplete. Resolve those before treating this as a zero." + ); + std::process::exit(2); + } else { + println!( + "{v34} transaction(s) with v = 34 among stored bodies. This is a superset: run \ + the per-block walk over the ranges concerned to find whether any is in a \ + canonical block, which is what decides the question." + ); + } + Ok(()) +} + +fn main() -> Result<()> { + if std::env::args().any(|a| a == "--screen") { + let data_dir = std::env::args() + .nth(1) + .filter(|a| !a.starts_with("--")) + .context("usage: tx_signature_v --screen")?; + return screen(&data_dir); + } + let data_dir = std::env::args() + .nth(1) + .filter(|a| !a.starts_with("--")) + .context("usage: tx_signature_v [--from N] [--to N]")?; + let store = BlockStore::open_read_only(&data_dir) + .with_context(|| format!("opening {data_dir} read-only"))?; + let head = store + .head()? + .and_then(|h| store.header(h).ok().flatten()) + .context("no chain head")? + .number; + let from: u64 = flag("from").and_then(|v| v.parse().ok()).unwrap_or(1); + let to: u64 = flag("to").and_then(|v| v.parse().ok()).unwrap_or(head).min(head); + + println!("walking transaction bodies of #{from}..#{to}"); + + let mut seen: BTreeMap = BTreeMap::new(); + let mut txs = 0u64; + let mut blocks = 0u64; + // Where the interesting values turn up, so a hit can be investigated + // rather than merely counted. + let mut flagged: Vec<(u64, u64)> = Vec::new(); + let started = Instant::now(); + let mut last_report = Instant::now(); + + for number in from..=to { + let Some(hash) = store.canonical_hash(number).ok().flatten() else { continue }; + let Some((transactions, _)) = store.body(hash).ok().flatten() else { continue }; + blocks += 1; + for tx in &transactions { + txs += 1; + *seen.entry(tx.v).or_default() += 1; + if matches!(tx.v, 29..=34) && flagged.len() < 100 { + flagged.push((number, tx.v)); + } + } + if last_report.elapsed().as_secs() >= 15 { + let done = number - from + 1; + eprintln!( + " #{number}: {done} blocks ({:.0}/s), {txs} transactions, {} distinct v", + done as f64 / started.elapsed().as_secs_f64().max(0.001), + seen.len() + ); + last_report = Instant::now(); + } + } + + println!(); + println!("blocks read {blocks}"); + println!("transactions {txs}"); + println!("distinct v values {}", seen.len()); + println!(); + println!(" v count meaning"); + for (v, count) in &seen { + println!("{v:>13} {count:>10} {}", note(*v)); + } + + if !flagged.is_empty() { + println!(); + println!("occurrences of v in 29..=34 (block, v):"); + for (number, v) in &flagged { + println!(" #{number} v={v}"); + } + } + + println!(); + let v34 = seen.get(&34).copied().unwrap_or(0); + let refused: u64 = (29..=33).filter_map(|v| seen.get(&v)).sum(); + if refused > 0 { + println!( + "{refused} transaction(s) carry a v of 29..=33, which EVM-073 refuses. Such a \ + transaction should not be in a block at all, so this is a finding about the \ + store or the decoder before it is one about the chain." + ); + } + if v34 == 0 { + println!( + "NO v = 34 in #{from}..#{to}, across {txs} transactions. Narrowing the accepted \ + set to 27, 28, 35.. would change nothing for any transaction in this range." + ); + } else { + println!( + "{v34} transaction(s) carry v = 34. Each sits in a valid block whose sender was \ + recovered from it, so refusing the octet would make those blocks invalid: the \ + narrowing proposal is dead, and this is the fact that kills it." + ); + } + if txs == 0 { + println!("but no transactions were read at all -- check the data directory and range."); + std::process::exit(2); + } + Ok(()) +} diff --git a/crates/execution/src/bridge/mod.rs b/crates/execution/src/bridge/mod.rs index 5cef26a6..2488e165 100644 --- a/crates/execution/src/bridge/mod.rs +++ b/crates/execution/src/bridge/mod.rs @@ -594,6 +594,7 @@ pub fn execute_bridge( // or run. `Program.callToPrecompiledAddress` asks for the gas outside // every try, so the exception leaves the VM whatever the era. if from_contract && !hardfork_cfg.has_rskip88(block_number) { + crate::legacy_census::Legacy::InternalBridgeCallEndsCaller.hit(); return Err(PrecompileError::other(CALLER_ABORT_MARKER)); } @@ -612,6 +613,33 @@ pub fn execute_bridge( .filter(|m| abi_args_decode_ok(&input[4..], m.signature)), } .filter(|m| m.enabled.is_enabled(hardfork_cfg, block_number)); + if let Some(m) = parsed { + // Six methods were enabled from genesis and disabled at an activation. + // `parsed` is `Some` only when the method is enabled at this height, so + // reaching here with one of these signatures is the window being used. + // + // Counted here rather than by scanning transaction inputs because this + // sees an internal call from a contract too, and four of the six are + // local-only getters whose only on-chain caller is a contract. A + // selector scan of transaction data cannot see those at all. + const WINDOWED: [&str; 6] = [ + "addFederatorPublicKey(bytes)", + "getFederatorPublicKey(int256)", + "getRetiringFederatorPublicKey(int256)", + "getPendingFederatorPublicKey(int256)", + "addLockWhitelistAddress(string,int256)", + "getBtcBlockchainBlockLocator()", + ]; + if WINDOWED.contains(&m.signature) { + crate::legacy_census::Legacy::WindowedBridgeMethod.hit(); + tracing::warn!( + target: "rustock::rsk_opcodes", + "a windowed bridge method was invoked at #{block_number}: {} -- this one was \ + removed by a later activation, so the window it belongs to is occupied", + m.signature + ); + } + } let Some(method) = parsed else { // Which selector, and from where. A Bridge method that exists in rskj // and not here fails exactly like a malformed call, and the two are @@ -900,10 +928,20 @@ fn execute_method( "updateCollections" => (true, false), // receiveHeadersIsPublic() = RSKIP124 && !RSKIP200; restricted otherwise. #[allow(clippy::nonminimal_bool)] // mirrors the rskj formula above - "receiveHeaders" => ( - !(hardfork_cfg.has_rskip124(block_number) && !hardfork_cfg.has_rskip200(block_number)), - false, - ), + "receiveHeaders" => { + let public = + hardfork_cfg.has_rskip124(block_number) && !hardfork_cfg.has_rskip200(block_number); + if public { + // Deliberately an over-count: this fires for *any* call to + // receiveHeaders while the window is open, not only one from a + // caller the federation-only rule would have refused. An + // over-count that comes back zero is still a proof -- nobody + // called it at all -- and only a non-zero needs the finer + // question asked. + crate::legacy_census::Legacy::PublicReceiveHeaders.hit(); + } + (!public, false) + } // registerBtcTransactionIsPublic() = RSKIP199. "registerBtcTransaction" => (!hardfork_cfg.has_rskip199(block_number), false), "addSignature" => (true, true), diff --git a/crates/execution/src/bridge/peg.rs b/crates/execution/src/bridge/peg.rs index fc6cddc7..f383a1bb 100644 --- a/crates/execution/src/bridge/peg.rs +++ b/crates/execution/src/bridge/peg.rs @@ -4393,6 +4393,10 @@ fn process_funds_migration( let migration_age_end = if hardfork_cfg.has_rskip357(block_number) && !hardfork_cfg.has_rskip374(block_number) { + // The positive control for the whole legacy census: this window is + // known occupied, because using the ordinary end age inside it + // diverged a real mainnet block. + crate::legacy_census::Legacy::MigrationEndAge.hit(); config.special_case_funds_migration_age_end } else { config.funds_migration_age_end diff --git a/crates/execution/src/executor.rs b/crates/execution/src/executor.rs index 44ed5751..e64f329c 100644 --- a/crates/execution/src/executor.rs +++ b/crates/execution/src/executor.rs @@ -2700,10 +2700,16 @@ impl RskExecutor { /// transactions to the Bridge from the genesis federation or an /// authorized sender execute for free (zero gas). fn is_free_bridge_tx(&self, tx: &rustock_core::Transaction, sender: Address, block_number: u64) -> bool { - tx.to.len() == 20 + let free = tx.to.len() == 20 && tx.to.as_ref() == crate::precompiles::BRIDGE_ADDR.as_slice() && !self.hardfork_cfg.has_are_bridge_txs_paid(block_number) - && self.free_bridge_senders.contains(&sender) + && self.free_bridge_senders.contains(&sender); + if free { + // Expected non-zero: this exists because the bootstrap-era + // federation needed it, so it is the second positive control. + crate::legacy_census::Legacy::FreeBridgeTransaction.hit(); + } + free } /// For contract creation transactions, compute the created address from diff --git a/crates/execution/src/legacy_census.rs b/crates/execution/src/legacy_census.rs new file mode 100644 index 00000000..c4c0d7eb --- /dev/null +++ b/crates/execution/src/legacy_census.rs @@ -0,0 +1,169 @@ +//! Which branches of this chain's own behaviour were ever actually taken. +//! +//! Most rows here are deletion candidates. Every activation that *changes* +//! behaviour leaves a branch behind, guarded by a height test, and a branch +//! over a window that can never reopen can go -- but only if nothing in the +//! window ever took it, and that is a claim about history, not about the code. +//! +//! One row is not a deletion candidate at all. [`Legacy::HighBitAddressCall`] +//! is active at every height on every network, so it will never be removed; +//! its occupancy is worth knowing for a different reason, given with it. +//! +//! The expensive part of proving it is the replay. The counting is nearly free, +//! so a replay that answers one such question should answer all of them: one +//! relaxed atomic add where the branch is taken, and a line in the report. +//! +//! # What a zero means, and what it does not +//! +//! A zero here is evidence over **the range the run covered**, which is why the +//! report prints the block counts beside it. It is also only as good as the +//! instrument: a counter that cannot fire reports zero just as convincingly as +//! a branch nothing took. +//! +//! That is why [`Legacy::MigrationEndAge`] is in the first run. Its window is +//! **known occupied** -- using the ordinary end age inside it diverged a real +//! mainnet block -- so it is the positive control. If it reports zero, the +//! campaign has a bug and every other zero in the table is worthless. Measure a +//! row you know fires before trusting the rows you hope do not. +//! +//! # Removing a guard needs more than a zero +//! +//! Only a branch that makes the whole *block* invalid can be removed without +//! measurement, because no canonical block can contain one. Everything counted +//! here is the other kind: the branch yields a valid block with a different +//! result, so a client without the guard would compute a different state root +//! for a block that is on the chain. Those need this measurement, and a +//! removal still needs its own justification. + +use std::sync::atomic::{AtomicU64, Ordering}; + +/// Declares the catalogue once, so the counter, its index and its description +/// cannot drift apart. +macro_rules! legacy_guards { + ($($variant:ident => ($rule:expr, $what:expr, $window:expr $(,)?)),+ $(,)?) => { + /// A legacy branch worth knowing the occupancy of. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + #[repr(usize)] + pub enum Legacy { $($variant),+ } + + /// What each counter is about, in `Legacy`'s order. + pub const CATALOGUE: &[(&str, &str, &str)] = &[$(($rule, $what, $window)),+]; + + static HITS: [AtomicU64; CATALOGUE.len()] = + [const { AtomicU64::new(0) }; CATALOGUE.len()]; + }; +} + +legacy_guards! { + // The positive control. Known occupied: see the module note. + MigrationEndAge => ( + "BR-086", + "funds-migration end age is 172,800 blocks, not 10,585", + "mainnet #4,976,300..#5,468,000", + ), + WindowedBridgeMethod => ( + "BR-011a", + "a bridge method a later activation removed was invoked while it still existed \ + (addFederatorPublicKey, getFederatorPublicKey, getRetiringFederatorPublicKey, \ + getPendingFederatorPublicKey, addLockWhitelistAddress, getBtcBlockchainBlockLocator)", + "mainnet below #729,000 or #1,591,000 depending on the method", + ), + PublicReceiveHeaders => ( + "BR-015", + "receiveHeaders is public rather than federation-only", + "mainnet #1,591,000..#3,614,800", + ), + InternalBridgeCallEndsCaller => ( + "BR-030", + "an internal call to the bridge ends its caller, consuming its gas", + "mainnet below #729,000", + ), + CreatedContractLosesBalance => ( + "EVM-033", + "a contract created at an address holding a balance loses it", + "mainnet below #3,614,800", + ), + // Not a deletion candidate either: live at every height. Measured because + // only the *negative* half of the discontinuity needs proving, and a + // prospective close would remove it. + BlockHeaderDepthOutOfRange => ( + "PC-042", + "a block-header precompile call supplied a depth outside 0..32,767: a negative one \ + throws and costs the caller all its gas, while one past the 16-bit range answers \ + empty, so the outcome is not monotonic in the argument", + "all heights -- the negative half is what a prospective close would remove", + ), + // Not a deletion candidate: active at all heights, all networks. + HighBitAddressCall => ( + "EVM-046", + "a call whose address word has bits above its low 20 octets, and whose low 20 \ + octets name an active precompile, reaches the account rather than the precompile", + "all heights, all networks -- permanent, measured for divergence not deletion", + ), + InternalCreateNonceZero => ( + "EVM-034", + "an internally created contract's nonce is 0, not 1", + "mainnet below #1,591,000", + ), + FreeBridgeTransaction => ( + "EVM-024", + "a bridge transaction from a privileged sender executes free, gas limit may be 0", + "mainnet below #370,000", + ), +} + +impl Legacy { + /// Count one occurrence. One relaxed atomic add, on a branch that is + /// already behind a height test. + pub fn hit(self) { + HITS[self as usize].fetch_add(1, Ordering::Relaxed); + } + + pub fn count(self) -> u64 { + HITS[self as usize].load(Ordering::Relaxed) + } +} + +/// Every counter, as `(rule, what, window, hits)`, in catalogue order. +pub fn census() -> Vec<(&'static str, &'static str, &'static str, u64)> { + CATALOGUE + .iter() + .enumerate() + .map(|(i, (rule, what, window))| (*rule, *what, *window, HITS[i].load(Ordering::Relaxed))) + .collect() +} + +/// Whether the positive control fired. +/// +/// Its window is known occupied, so a run that covered it and reports zero has +/// a broken instrument, not a clean window. The caller prints this verdict +/// rather than leaving a reader to notice. +pub fn positive_control_fired() -> bool { + Legacy::MigrationEndAge.count() > 0 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_variant_has_its_own_counter() { + // The macro keeps the enum and the catalogue in step; this checks the + // indexing, which is what would silently mis-attribute a hit. + let before = census(); + Legacy::PublicReceiveHeaders.hit(); + let after = census(); + for (i, ((_, _, _, b), (_, _, _, a))) in before.iter().zip(after.iter()).enumerate() { + let expected = u64::from(i == Legacy::PublicReceiveHeaders as usize); + assert_eq!(a - b, expected, "counter {i} moved by {}", a - b); + } + } + + #[test] + fn the_catalogue_describes_every_counter() { + assert_eq!(CATALOGUE.len(), HITS.len()); + for (rule, what, window) in CATALOGUE { + assert!(!rule.is_empty() && !what.is_empty() && !window.is_empty()); + } + } +} diff --git a/crates/execution/src/lib.rs b/crates/execution/src/lib.rs index c8bc01d2..9c819ad8 100644 --- a/crates/execution/src/lib.rs +++ b/crates/execution/src/lib.rs @@ -8,6 +8,7 @@ pub mod executor; pub mod gas_estimator; pub mod hardfork; pub mod internal_tx; +pub mod legacy_census; pub mod mining; pub(crate) mod native; pub mod precompiles; diff --git a/crates/execution/src/native/block_header.rs b/crates/execution/src/native/block_header.rs index 92a0d194..eb55bb4c 100644 --- a/crates/execution/src/native/block_header.rs +++ b/crates/execution/src/native/block_header.rs @@ -115,9 +115,27 @@ impl NativeContract for BlockHeader<'_> { fn execute(&self, call: Call) -> Result, Failure> { // `BlockHeaderContractMethod.execute`: a depth no short holds names no // block, and neither does one `getBlock` finds nothing at. + // PC-042. The depth is narrowed to a signed 16-bit value *before* the + // sign test, so -1 throws and -40,000 does not. Only the negative half + // needs measuring: on the positive side 5,000 and 40,000 both answer + // empty, by two different routes, so the narrowing is already + // invisible there and removing it would change nothing. + // + // Counted here rather than from receipts because a contract-internal + // call's input is in no receipt. let block = match call.depth.short_value_exact() { - Some(depth) => self.block_at(depth)?, - None => None, + Some(depth) => { + if depth < 0 { + crate::legacy_census::Legacy::BlockHeaderDepthOutOfRange.hit(); + } + self.block_at(depth)? + } + None => { + // Outside the 16-bit range entirely. Also outside 0..32,767, + // so it is part of the same predicate. + crate::legacy_census::Legacy::BlockHeaderDepthOutOfRange.hit(); + None + } }; let Some((hash, header)) = block else { return Ok(encode_bytes(&[])); diff --git a/crates/execution/src/rsk_handler.rs b/crates/execution/src/rsk_handler.rs index f0f9ffd3..890b8c0e 100644 --- a/crates/execution/src/rsk_handler.rs +++ b/crates/execution/src/rsk_handler.rs @@ -928,6 +928,18 @@ where // account at those bytes (`call_without_code`). let to_account = past_an_address && callee.is_some_and(|c| self.active_precompiles.contains(&c)); + if to_account { + // EVM-046. Not a guard anyone can remove -- it holds at + // every height -- but an Ethereum-derived client + // truncates the word first and runs the precompile, so + // it diverges on exactly this call, in the returned + // data, the gas, and anything the precompile would have + // written. Whether the chain contains one is therefore + // worth knowing, and only a replay can say: the address + // is a runtime stack value, so no scan of code can find + // it. + crate::legacy_census::Legacy::HighBitAddressCall.hit(); + } let callee = callee.filter(|_| !to_account); let creates = matches!( init.frame_input, @@ -1015,7 +1027,12 @@ where // (wasabi) rskj's Program.createContract bumps the // created contract's nonce to 1; before, it is 0. let nonce = u64::from(self.rskip125_active); - set_created_contract_nonce(evm, nonce); + // A creation frame, below RSKIP125, is the legacy + // branch: an internally created contract's nonce + // stays 0 where it would otherwise be 1. + if set_created_contract_nonce(evm, nonce) && !self.rskip125_active { + crate::legacy_census::Legacy::InternalCreateNonceZero.hit(); + } begin_creation(evm); skip_code_header(evm); self.open_frame(evm, creates); @@ -1662,6 +1679,16 @@ fn rsk_return_create>( // Short-circuit keeps the deposit uncharged in the oversize case, like // rskj (the exception set by either check skips spendGas + saveCode). let unsaved = oversize || !interpreter_result.gas.record_cost(deposit); + // Observed, not altered: this function is only reached below RSKIP-453 and + // at depth > 0, so `unsaved` here is exactly the empty-deploy quirk firing. + // Whether anything on this chain ever reached it decides whether both + // branches are live rules or dead guards. + crate::rsk_instructions::record_internal_deploy( + code_len, + cfg.max_code_size(), + unsaved, + oversize, + ); if unsaved { interpreter_result.output = Bytes::new(); } @@ -1903,7 +1930,9 @@ where /// If the top (just-initialized) frame is a CREATE frame, reset the created /// account's nonce to 0. On revert the AccountCreated journal entry discards /// the account wholesale, so no extra journaling is needed. -fn set_created_contract_nonce(evm: &mut EVM, nonce: u64) +/// Returns whether this was a creation frame, so a caller can tell a create +/// from a call without repeating the frame inspection. +fn set_created_contract_nonce(evm: &mut EVM, nonce: u64) -> bool where EVM: EvmTr< Context: ContextTr>, @@ -1911,11 +1940,12 @@ where >, { let FrameData::Create(CreateFrame { created_address }) = evm.frame_stack().get().data else { - return; + return false; }; if let Ok(mut acc) = evm.ctx().journal_mut().load_account_mut(created_address) { acc.set_nonce(nonce); } + true } /// A creation's frame has opened (the top one): its contract has no code @@ -1951,6 +1981,13 @@ where }; let sent = evm.ctx().tx().value(); if let Ok(mut account) = evm.ctx().journal_mut().load_account_mut(created_address) { + // Only when something is actually lost. Without this branch the + // balance would be what was there plus what was sent, so the outcome + // differs exactly when the address already held funds -- counting + // every creation instead would report a number that says nothing. + if !account.balance().is_zero() { + crate::legacy_census::Legacy::CreatedContractLosesBalance.hit(); + } account.set_balance(sent); } } diff --git a/crates/execution/src/rsk_instructions.rs b/crates/execution/src/rsk_instructions.rs index 328bf499..2850e25b 100644 --- a/crates/execution/src/rsk_instructions.rs +++ b/crates/execution/src/rsk_instructions.rs @@ -1083,6 +1083,60 @@ pub fn record_contract_created(code: &[u8]) { } } +/// The two ways an internal creation below RSKIP-453 deploys empty instead of +/// reverting, and the largest code any such creation returned. +/// +/// `[oversize, unpayable deposit, largest returned length]`. +/// +/// Before RSKIP-453 (lovell700, #7,338,024 on mainnet), an internal create +/// whose returned code exceeds the maximum, or whose frame cannot pay the code +/// deposit, does **not** revert: rskj's `Program.finalizeContractCreation` +/// deploys an empty contract, keeps the constructor's state changes and +/// returns the address. From RSKIP-453 it fails like EIP-2. +/// +/// Both branches are guards for behaviour nothing may ever have exercised. If +/// no internal creation below #7,338,024 ever returned oversize code or ran +/// out of gas for its deposit, the quirk is unreachable on this chain and the +/// guards can go. That is a claim about 7.3 million blocks, so it is counted +/// rather than argued -- and counted *here*, because this function is reached +/// only when the quirk applies: below RSKIP-453 and at depth > 0. +/// +/// `largest returned length` is the useful negative evidence. A maximum well +/// under the 24,576-octet limit says the oversize branch was never close to +/// firing, which is stronger than "it did not fire". +pub static EMPTY_DEPLOY: [AtomicU64; 3] = + [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]; + +/// Record an internal creation below RSKIP-453. +/// +/// `unsaved` is the quirk firing; `oversize` says which of the two branches, +/// since the deposit is never charged once the size check has failed. +pub fn record_internal_deploy(code_len: usize, max_code_size: usize, unsaved: bool, oversize: bool) { + EMPTY_DEPLOY[2].fetch_max(code_len as u64, Ordering::Relaxed); + if !unsaved { + return; + } + let which = usize::from(!oversize); + let n = EMPTY_DEPLOY[which].fetch_add(1, Ordering::Relaxed) + 1; + if n <= 16 { + tracing::warn!( + target: "rustock::rsk_opcodes", + "an internal creation below RSKIP-453 deployed EMPTY instead of reverting: {} \ + ({code_len} octets returned, maximum {max_code_size}), occurrence {n}", + if oversize { "code over the maximum size" } else { "the code deposit was unpayable" } + ); + } +} + +/// `[oversize, unpayable deposit, largest code an internal create returned]`. +pub fn empty_deploy_counts() -> [u64; 3] { + [ + EMPTY_DEPLOY[0].load(Ordering::Relaxed), + EMPTY_DEPLOY[1].load(Ordering::Relaxed), + EMPTY_DEPLOY[2].load(Ordering::Relaxed), + ] +} + /// `[contracts created, of those carrying the code header]`. pub fn contracts_created() -> [u64; 2] { [ @@ -1878,6 +1932,52 @@ pub fn rsk_static_call( /// `Program.callToAddress` moves it to the callee, which runs static. Only /// CALL refuses a value inside a static call, and only CALL pays for an /// account it creates. +/// Seven-operand `STATICCALL`s, and how many carried a non-zero value. +/// +/// `[executed, with a non-zero value]`. +/// +/// Between RSKIP-91 and RSKIP-103 -- mainnet #729,000 to #1,052,700, 323,700 +/// blocks -- rskj's `calculateCallValue` excepted only `DELEGATECALL`, so +/// `STATICCALL` took seven operands and *transferred* the value it was given +/// (`CallValue::Transfer` below). For that window, "a static call cannot +/// change state" was false on this chain. +/// +/// Whether any transaction ever used it is a different question from whether +/// the rule existed, and only the chain answers it. Zero over the whole window +/// means the seven-operand form was never passed a value, and the transfer +/// branch is a rule nothing ever exercised. +/// +/// Counted where the operands have been read, so a call that later fails for +/// gas still counts: the question is what the opcode was *passed*, not what +/// came of it. +pub static STATICCALL_SEVEN_OPERAND: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; + +/// Count a seven-operand `STATICCALL` and, if it carries value, say so. +fn record_staticcall_value(to: Address, value: U256) { + STATICCALL_SEVEN_OPERAND[0].fetch_add(1, Ordering::Relaxed); + if value.is_zero() { + return; + } + let n = STATICCALL_SEVEN_OPERAND[1].fetch_add(1, Ordering::Relaxed) + 1; + // Every one of these earns a line: the expectation is zero, and if it is + // wrong the value and the target are the whole finding. + tracing::warn!( + target: "rustock::rsk_opcodes", + "STATICCALL carried a non-zero value of {value} to {to} -- a static call moving \ + funds, which this chain allowed between RSKIP-91 and RSKIP-103. Occurrence {n}, \ + transaction index {} of its block.", + TX_INDEX.with(|i| i.get()) + ); +} + +/// `[seven-operand STATICCALLs executed, of those carrying a non-zero value]`. +pub fn staticcall_value_counts() -> [u64; 2] { + [ + STATICCALL_SEVEN_OPERAND[0].load(Ordering::Relaxed), + STATICCALL_SEVEN_OPERAND[1].load(Ordering::Relaxed), + ] +} + pub fn rsk_static_call_with_value( mut context: InstructionContext<'_, H, WIRE>, ) { @@ -1888,6 +1988,7 @@ pub fn rsk_static_call_with_value( let past = past_an_address(to); let to = Address::from_word(B256::from(to)); let local_gas_limit = u64::try_from(local_gas_limit).unwrap_or(u64::MAX); + record_staticcall_value(to, value); let Some((input, return_memory_offset)) = rsk_memory_input_and_out_ranges(context.interpreter, context.host.gas_params()) diff --git a/docs/retroactive-guard-measurements.md b/docs/retroactive-guard-measurements.md new file mode 100644 index 00000000..5703aeab --- /dev/null +++ b/docs/retroactive-guard-measurements.md @@ -0,0 +1,277 @@ +# Measuring whether a guard can be removed + +A guard over a window that can never reopen is a candidate for deletion. The +condition is not that the window is closed — it is that **nothing in the window +ever took the branch**, which is a claim about this chain's history and not +about the code. Removing a guard on reasoning alone changes the state root this +node computes for blocks that are already on the chain. + +This document records what has been measured, with the exact command for each +and how to widen it. It is a draft: most rows are instrumented and unrun, and +the two results that exist are marked as such. + +## The rule that decides what needs measuring + +A guard may be removed **without** measurement only if the branch it guards +makes the whole *block* invalid, because then no canonical block can contain +one. Every other kind needs the measurement — an opcode "not available at this +height" halts the frame and consumes its gas, and the block is valid and in the +chain; a bridge method a caller is not permitted to call throws and charges the +whole gas limit, and the block is valid and in the chain. Per `BR-031` a direct +bridge failure is not even marked in the receipt, so the only historical trace +is a gas figure. + +Three classes follow. **A** — the branch invalidates the block; removable with +no measurement. **B** — the branch yields a valid block with a different +result; removable only if measured. **C** — the window is empty on a given +network, so there is nothing to measure and the code stays for the networks +where it is not. + +## What has actually been run + +### `EVM-073` — is `v = 34` anywhere in the chain? + +`v` is one octet, decomposed as `chainId = (v - 35) / 2` with the subtraction +floored at zero, accepted set `27, 28, 34 … 255`. `v = 34` is accepted and means +exactly what `28` means, and is not a value EIP-155 can produce. Narrowing the +set to `27, 28, 35 …` would be a de-divergence. Class **B**: a single `v = 34` +kills the proposal, because such a transaction sits in a valid block whose +sender was recovered from it. + +**Result: settled for mainnet. No `v = 34` anywhere**, across every body this +node has stored — 12,799,779 of them, 31,210,944 transactions, none +undecodable, 219 seconds. + +``` + v count meaning + 0 12,799,778 no signature + 27 951,612 legacy, pre-EIP-155 + 28 951,791 legacy, pre-EIP-155 + 95 8,251,088 chain 30, mainnet + 96 8,256,675 chain 30, mainnet +``` + +Exactly five distinct values. Three things in that table are worth keeping: + +- The `v = 0` count is one per body but for a single exception, which is REMASC + appearing in every block. It is the check that the instrument read real + transactions rather than finding nothing because it was broken. +- **1.9 million transactions are pre-EIP-155**, signed with 27 or 28 — not a + handful of early curiosities. An exact walk of #1..#150,000 found only nine of + them, so they belong to later eras, and anything that assumes a chain id can + be recovered from `v` is wrong for 6% of this chain. +- No value in `29..=33` appears. Those are refused by `EVM-073`, so one would + have been a finding about the store or the decoder before it was one about the + chain. + +12,799,779 bodies against 9.43 million canonical blocks means roughly 3.37 +million stored bodies are not on the chain — which is why the screen is a +superset, and why a clean screen is worth more than a clean canonical walk: it +rules out the value in blocks the chain abandoned as well. + +```sh +# exact, canonical blocks only -- about 370 blocks/s +cargo run --release -p rustock-cli --example tx_signature_v -- \ + /var/lib/rustock --from 1 --to 150000 + +# screen: every stored body, canonical or not -- about 57,000 bodies/s +cargo run --release -p rustock-cli --example tx_signature_v -- \ + /var/lib/rustock --screen +``` + +**Widen the range** with `--from` and `--to`; omitted, they are genesis and the +node's head. The screen always covers everything the node stored, so for this +rule there is nothing left to widen on mainnet — only testnet remains. + +**The screen is 160x faster and one-directional.** Measured: 58,800 bodies/s +against 370 blocks/s for the exact walk, so the whole chain takes under four +minutes rather than seven hours. It iterates the bodies +column family sequentially, skipping the canonical-hash lookup and random read +per block, and so covers non-canonical bodies too. Nothing found settles the +canonical question outright; a hit must be followed with the exact walk over the +range concerned, because a transaction in an orphaned block invalidates nothing. +It counts bodies it cannot decode and refuses to report a clean screen while any +remain, since a pass that silently skipped some would report a zero it has not +earned. + +### `EVM-045` — are `DUPN`, `SWAPN`, `TXINDEX` reachable? + +Valid opcodes from genesis until RSKIP-191 at `iris300` (#3,614,800). Class +**B**. + +**Result at #3,614,799, reachability census:** `0xa8` and `0xa9` reachable in no +contract; `0xaa` surviving in three contracts, all three the same string +constant (`CROWDFUNDING_AUTH_FA…` follows it, and the 24 bytes before it are +identical across all three). 9,130 contracts, 24 MB of code, 2.94M trie nodes, +17 minutes, **no unresolved references** — a missing node would void the result, +so they are counted and a non-zero count fails the run. + +A byte scan would have reported 10,525 occurrences of `0xa8`. The difference is +the decode: a byte inside a `PUSH` immediate cannot execute, because jumpdest +analysis runs over the same linear decode, so there is exactly one instruction +set per contract. The census also excludes solc's metadata trailer (CBOR map +headers are `0xa1..0xb7`, so a trailer can begin with the bytes being hunted), +dead regions after a terminator until the next `JUMPDEST`, and honours RSK's +`0xfc` code header, which moves the offset every instruction is decoded from. + +**It also found the code header was never used** by any contract alive at that +height. + +```sh +cargo run --release -p rustock-cli --example opcode_census -- \ + /var/lib/rustock /mnt/import/rustock-trie --block 3614799 --threads 3 +``` + +**Widen** with `--block` (any height an archive can serve — `archive_bound` +says how high yours reaches; ours is #9,238,111) and `--ops` (any comma-separated +bytes). To cover a different era, re-run at that era's height. + +**What it cannot cover:** a contract created and destroyed before the block +scanned is in no state at all, and neither is code a contract computed at +runtime. Those need the replay. + +### `EVM-046` — the proposed state screen does not work + +The screen was: such a call touches the account at the precompile address, a +touched account is materialised, and no ordinary path materialises a precompile +address — so an absent account would prove non-occurrence in seconds. + +**Result: the premise is false.** All seven tested precompile addresses exist as +accounts in mainnet state at #9,238,111, because +`BlockExecutor.maintainPrecompiledContractStorageRoots` creates every genesis +precompile at the RSKIP-126 activation and re-creates each consensus-enabled one +at its own. The screen reports "materialised" whatever the history, and a reader +taking that as evidence toward occurrence would conclude the opposite of the +truth. + +```sh +cargo run --release -p rustock-cli --example opcode_census -- \ + /var/lib/rustock /mnt/import/rustock-trie --block 9238111 \ + --account 0000000000000000000000000000000000000001,…,0000000000000000000000000000000001000016 +``` + +A second hole would have remained even had the premise held: +`call_without_code` touches the callee only under `CallValue::Transfer`. A +zero-value transfer does touch — revm's `transfer_loaded` calls `touch_account` +before returning — so `STATICCALL` would have been covered, but `DELEGATECALL` +passes `CallValue::Apparent`, never enters that branch, and leaves no trace. + +**So `EVM-046` needs the replay counter**, which is wired. It is not a deletion +candidate in any case: the spec records it active at all heights on all +networks, and it is measured to learn whether this chain holds a block an +Ethereum-derived client would get wrong. + +## Instrumented, not yet run + +These need one historical replay. The counters cost one relaxed atomic add on a +branch already behind a height test, so one replay measures all of them. + +| Rule | Branch | Window (mainnet) | +|---|---|---| +| `BR-086` | funds-migration end age is 172,800 blocks, not 10,585 | #4,976,300–#5,468,000 | +| `EVM-024` | a bridge transaction from a privileged sender executes free | below #370,000 | +| `BR-015` | `receiveHeaders` is public rather than federation-only | #1,591,000–#3,614,800 | +| `BR-030` | an internal call to the bridge ends its caller | below #729,000 | +| `BR-011a` | a bridge method a later activation removed was invoked while it existed | below #729,000 or #1,591,000 | +| `EVM-033` | a contract created at a funded address loses that balance | below #3,614,800 | +| `EVM-034` | an internally created contract's nonce is 0, not 1 | below #1,591,000 | +| `EVM-046` | a dirty-high-bits address reaches the account, not the precompile | all heights | +| `PC-042` | a block-header depth outside `0..32,767` | all heights | + +Three more have their own counters, because each carries a quantity a hit count +would lose: seven-operand `STATICCALL` (`EVM-041b`, #729,000–#1,052,700), +executions and those carrying a non-zero value; the two empty-deploy branches +below RSKIP-453 (`EVM-037`, below #7,338,024) with the largest code any internal +creation returned; and contracts deployed, with how many carried the `0xFC` +header (`EVM-032`). + +```sh +# whole chain, about 13 h at two workers -- needs the node stopped +SCOPE=all BUDGET_MB=6000 bash /mnt/import/paseo/tmp/night-reexec.sh +``` + +**Widen or narrow the range** with `SCOPE`: `iris300` (#1..#3,620,064, ~4.5 h), +`rskip453` (#1..#7,338,024, ~10 h) or `all`. The scoping works by pre-seeding +`reexec_all`'s state file with the segments above the bound, which it skips as +already done — no code change, and the plan is printed by `--dry` before +anything executes. To inspect blocks close to a particular activation, set the +bound just above it; the segment that straddles the bound runs in full, so the +covered range always ends at a segment boundary rather than exactly at the +height. + +### Two positive controls, and why the report leads with them + +**A campaign that only ever returns zero has not been validated.** A counter +that cannot fire reports zero exactly as convincingly as a branch nothing took. + +`BR-086`'s window is known occupied — using the ordinary end age inside it +diverged a real mainnet block — so `reexec_all` prints a verdict naming it, and +says that until it fires every other zero in the table is unproven. `EVM-024` is +the second control: it exists because the bootstrap-era federation needed it. + +Read that line before any of the zeros. + +## Instrumented separately: `BR-134` + +The bridge sizes a single dynamic event field as `((len - 1) / 32 + 1) * 32` in +signed truncating division, so an empty field emits one zero word and the data +is 96 octets where the canonical ABI gives 64. The evidence is in the +**receipts** rather than the execution, so this needs no replay. + +"Data is exactly 96 octets" is not the test: the encoding is +`offset(32) ++ length(32) ++ content` padded to whole words, so a field of 1 to +32 octets is also exactly 96 — legitimately, a 32-octet hash being the ordinary +case. The test is 96 octets **and a declared length of zero**, and the tool +reports both numbers so the gap is visible. + +```sh +# whole chain, about 3.1 h at 840 blocks/s +cargo run --release -p rustock-cli --example bridge_event_width -- /var/lib/rustock +``` + +**Widen** with `--from` and `--to`. A probe over #1..#120,000 read 5,158 bridge +logs and found none at 96 octets. + +## What cannot be removed whatever the measurement says + +Worth stating, because three of the rows above are in this list and their zeros +are evidence of divergence rather than licence to delete. + +- **Live at every height, so no window to close.** `EVM-046`; `PC-042` (whose + negative half could be closed *prospectively*, with an activation, but not + retroactively); `BR-134`, whose encoder is shared, so removing the quirk + changes a rule rather than deleting a dead branch. +- **Needed to replay history regardless.** The lock whitelist, lifted by + transaction at #2,475,088 — replaying any block below it needs the guard. The + locking cap, raised past relevance rather than withdrawn; its path runs on + every peg-in forever. +- **Rejected on their merits.** `EVM-047` — deployed contracts guard on + `extcodesize(precompile) != 0`, so a restriction breaks working code. + `EVM-012` — the account is already in use and the answer is disclosure. + `EVM-060`–`EVM-065` — exercised by essentially every transaction. +- **Class C.** Seven-operand `STATICCALL`, fallback mining and every + `orchid`/`wasabi100`-bounded branch have empty windows on testnet and regtest, + so the code stays for mainnet; RSKIP-144/351 parallel execution has never run + on **mainnet** but is needed on testnet. + +The only free deletions in the catalogue are four class-**A** rows: `BLAKE2F` +with an empty data field, a header with no `ummRoot`, a header with no +version/edges, and a block with no execution sublists. Even then the guard keeps +one job — refusing a malformed block from a stranger — which is a decision about +what a node owes a peer rather than about replay. + +## Limits of everything above + +**Mainnet only.** Every result here is half the claim: several windows are empty +on testnet rather than unoccupied, and a removal needs both networks covered, +each below its own heights. + +**A zero is bounded by the range that produced it.** Every tool prints the +blocks or transactions it actually read, for that reason. + +**Nothing here licenses a removal by itself.** A measurement result belongs in a +proposal alongside the height ranges and the tooling; a class-A removal should +not be bundled with a class-B one, so that withdrawing one does not drag the +other; and a removal over a closed window needs no activation height, because a +node that applies it and a node that does not agree on every block either has +ever seen. diff --git a/docs/tools.md b/docs/tools.md index 89f8d669..43bb0ae2 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -100,6 +100,7 @@ does and does not hold. | [`archive_bound`](../crates/cli/examples/archive_bound.rs) | How high does an archive trie actually reach? | | [`refilter_segment`](../crates/cli/examples/refilter_segment.rs) **(writes)** | Rewrite a segment's SSTs with a bloom policy. The measurement behind §6.9a's negative result. | | [`key_shape`](../crates/cli/examples/key_shape.rs) | Key and value shape of a trie store: fixed-length keys, and how large do values get? | +| [`bridge_event_width`](../crates/cli/examples/bridge_event_width.rs) | Did the bridge ever log an **empty** single dynamic field? Reads stored receipts, not execution, and separates the 96-octet width from a declared length of zero -- a field of 1 to 32 octets is the same width, legitimately. | | [`opcode_census`](../crates/cli/examples/opcode_census.rs) | Can any contract alive at a block reach a given opcode? Decodes every contract's code, so a byte inside a `PUSH` immediate, the metadata trailer or a dead region does not count. The cheap half of "is this rule change dead code?" | ## The pre-RSKIP126 root baseline