From ba7fb054eba232ed3eceb0e8a38a94d3bd8618c8 Mon Sep 17 00:00:00 2001 From: Sergio Demian Lerner Date: Mon, 23 Nov 2026 16:27:22 +0000 Subject: [PATCH 1/9] Correct the hardfork table: STATICCALL and the shift opcodes were misplaced The doc comment credited BYZANTIUM with STATICCALL from genesis and put the shift opcodes and CREATE2 at papyrus200. Both are contradicted by the code in the same file: rsk_instructions::install replaces STATICCALL with the invalid-opcode handler below orchid under RSKIP-91, and upgrade_to_spec_id maps wasabi100 onward to PETERSBURG precisely because wasabi enables the RSKIP-120 shifts and RSKIP-125 CREATE2. Wrong in the direction a re-implementer would copy, which is why it is worth fixing rather than deleting: the table reads as a specification of what is available at each height. It now says the SpecId is an aside and the RSKIP gates are what bind, and records what the table used to claim so the next reader does not re-derive it. Reported as D-003 against the specification project. Co-Authored-By: Claude Opus 5 --- crates/execution/src/hardfork.rs | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/crates/execution/src/hardfork.rs b/crates/execution/src/hardfork.rs index 95020e99..4d444fa4 100644 --- a/crates/execution/src/hardfork.rs +++ b/crates/execution/src/hardfork.rs @@ -4,12 +4,24 @@ /// them into Ethereum-style hardforks. We map each RSK network upgrade to /// the closest Ethereum SpecId that captures the same EVM semantics: /// -/// | RSK Upgrade | Height | Closest SpecId | Key changes | +/// **The SpecId is an aside, not the rule.** Rootstock gates each opcode on its +/// own RSKIP, so the Ethereum fork label never decides what is available: the +/// column below records which gates fire, and `upgrade_to_spec_id` and +/// `rsk_instructions::install` are what actually bind. +/// +/// This table previously credited BYZANTIUM with `STATICCALL` from genesis and +/// put the shift opcodes and `CREATE2` at `papyrus200`. Both were wrong, and +/// wrong in the direction a re-implementer would copy -- `STATICCALL` is +/// replaced by the invalid-opcode handler below `orchid` (RSKIP-91), and the +/// shifts and `CREATE2` arrive at `wasabi100` (RSKIP-120/125), which is also +/// where PETERSBURG begins. +/// +/// | RSK Upgrade | Height | Closest SpecId | Gates that fire here | /// |------------------|-----------|-------------------|--------------------------------------| -/// | genesis–orchid | 0–728999 | BYZANTIUM | REVERT, STATICCALL, RETURNDATASIZE | -/// | orchid | 729000 | BYZANTIUM | (RSK-specific fixes) | -/// | wasabi100 | 1591000 | BYZANTIUM | (RSK-specific fixes) | -/// | papyrus200 | 2392700 | PETERSBURG | SHL/SHR/SAR, CHAINID, CREATE2 | +/// | genesis–orchid | 0–728999 | BYZANTIUM | REVERT, RETURNDATASIZE. NO STATICCALL | +/// | orchid | 729000 | BYZANTIUM | STATICCALL (RSKIP-91), 7 operands until orchid060 | +/// | wasabi100 | 1591000 | PETERSBURG | SHL/SHR/SAR (RSKIP-120), CREATE2 (RSKIP-125) | +/// | papyrus200 | 2392700 | PETERSBURG | EXTCODEHASH (RSKIP-140), CHAINID/SELFBALANCE (RSKIP-152/151) | /// | iris300 | 3614800 | PETERSBURG | (RSK-specific fixes) | /// | hop400 | 4598500 | PETERSBURG | (RSK-specific fixes) | /// | fingerroot500 | 5468000 | PETERSBURG | (RSK-specific fixes) | From 0ab74ab973636d89e4fb4703809000d0f33dd1dd Mon Sep 17 00:00:00 2001 From: Sergio Demian Lerner Date: Mon, 23 Nov 2026 16:27:22 +0000 Subject: [PATCH 2/9] Give segbuild its own BTC block cache, and clear it at each segment A segment must contain every trie node a cold replay of its range reads. segbuild shared the node's BtcBlockCache, so the Bridge's deep walks -- a peg-in's confirmation count, a pegout's UTXO selection -- were served from a cache warmed by earlier segments. Those nodes were never read, never promoted into the window store, and never sealed. The segment was complete only for a reader whose cache happened to be warm the same way; a cold reader got None for a node the chain has, which is the 6.9d hazard and the cause of #374's false divergence report. Measured over the whole chain: 510,219 reads a segment could not serve, across 77 of 106 segments, in 133 blocks, every one of them a deep Bridge walk. Private rather than merely cleared, because clear() on the shared Arc would wipe the live node's cache at every segment boundary while it syncs. ~2 MB at the default 10,000 entries. Clearing rather than disabling, because the cache still pays for itself within a range and a disabled cache would make the build read a superset of what any replay needs. The nodes this adds are exactly the ones the measurement found missing: ~6,486 per affected segment, ~48.6 MB over the set, 0.029% of 161 GB. It does not grow as segments get shorter -- the cost attaches to blocks, not to segments. Existing segments are not repaired by this. Validation is a replay with no fallback: one with a fallback cannot test it, because the archive silently covers every hole. Refs #410 Co-Authored-By: Claude Opus 5 --- crates/cli/src/main.rs | 19 +++++++++++++++++-- crates/execution/src/segment_build.rs | 16 ++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 53a3e321..8d4e66ba 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -3584,8 +3584,23 @@ async fn run(local_offset: Option) -> Result<()> { // re-executes blocks whose peg events have already been recorded, and // recording them again would double every entry. let mut segbuild_processor = rule_keeping_processor(&hardfork_cfg, &store, &config); - if let Some(cache) = &btc_block_cache { - segbuild_processor = segbuild_processor.with_btc_block_cache(cache.clone()); + // A PRIVATE BTC block cache, not a clone of the node's. + // + // Sharing it was the cause of the segment holes found on 2026-11-22. + // The builder's deep Bridge walks -- a peg-in's confirmation count, a + // pegout's UTXO selection -- were served from a cache warmed by earlier + // segments, so those nodes were never read from the trie, never + // promoted into the window, and never sealed into the segment. A cold + // replay then could not find them: 510,219 such reads over the chain, + // across 77 of 106 segments. + // + // Private rather than simply cleared, because `clear()` on the shared + // Arc would also wipe the live node's cache at every segment boundary + // while it syncs. The copy costs ~2 MB at the default 10,000 entries. + if btc_block_cache.is_some() { + segbuild_processor = segbuild_processor.with_btc_block_cache(std::sync::Arc::new( + rustock_execution::BtcBlockCache::new(args.btc_block_cache_entries), + )); } if let Some(cache) = &sender_cache { segbuild_processor = segbuild_processor.with_sender_cache(cache.clone()); diff --git a/crates/execution/src/segment_build.rs b/crates/execution/src/segment_build.rs index a143faaf..449d2fae 100644 --- a/crates/execution/src/segment_build.rs +++ b/crates/execution/src/segment_build.rs @@ -274,6 +274,22 @@ pub fn build_range( if start > end { bail!("range #{start}..#{end} is not a range"); } + // Empty the BTC block cache before replaying this range. + // + // A segment must contain every node a *cold* replay of its range reads. A + // cache carried in from the previous segment serves some of those reads + // from memory, so the nodes never enter the window and the segment is + // complete only for a reader whose cache happens to be warm the same way. + // Clearing here makes the build's read set match a replay that starts cold + // at the same boundary. + // + // Clearing rather than disabling is deliberate: the cache still pays for + // itself *within* a range, and a disabled cache would make the build read a + // superset of what any replay needs. See `docs/trie-segments-design.md` + // 6.9d and the 2026-11-22 measurement. + if let Some(cache) = processor.btc_block_cache() { + cache.clear(); + } if start < UNITRIE_FROM { bail!( "refusing to build #{start}..#{end}: below #{UNITRIE_FROM} a header declares an \ From de5a847cd151510f3ef33c506abe065d1e76f3f4 Mon Sep 17 00:00:00 2001 From: Sergio Demian Lerner Date: Mon, 23 Nov 2026 16:27:39 +0000 Subject: [PATCH 3/9] Count nineteen more legacy branches, and the chain's high-water marks The census moves from rustock-execution to rustock-core, because the BV-* and BP-* rows live in core's validation code and core cannot depend on execution. Re-exported from execution, so existing paths resolve unchanged. Nineteen rows added, taking the registry from 9 to 28. Two groups matter: - all eight of the overflow-and-narrowing guards (BV-110, BV-125, BV-173, BR-061, BR-112, PC-042, EVM-062, PC-051). Unlike the rest these are monitoring rather than measurement: a non-zero is a live incident, and the specification is explicit that they should outlive the campaign. - EVM-023a, a second positive control. BR-086 proves a bridge counter can fire; this one names a single block and the exact figures it must produce (mainnet #3,307, 31,280 gas against a 30,000 limit), so it is the sharper test. It is asserted in the existing #3,307 regression rather than left to be discovered after an eleven-hour replay. Several rows needed care about *where* rather than whether. BR-055 goes through a counting wrapper so short-circuit evaluation attributes a marking to the window only when the window caused it; EVM-043 counts the one arm that actually differs from the standard rule; BR-097 counts both the singular and plural receive paths, since batched submission is the normal case; EVM-023a is counted on all four precompile arms, not just the Bridge's, because OutOfGas fires only when required > limit and the rest are overcharged identically. BR-063 and BR-083 are deliberately NOT counted. The obvious site in each is not where the legacy behaviour is applied -- BR-063's else branch yields no reject reason at all, and BR-083's is an early return guarding the new format -- so a counter there would report a confident zero that means nothing. vm_extremes records maxima rather than counts: deepest CALL-family frame, most EVM memory expanded, largest RETURN payload. Each is packed with the block that set it into one atomic, so a single fetch_max orders by value and carries the block with no lock and no torn pair. Every quantity fits in 32 bits, and values at or above 2^32 clamp rather than wrap so a clamp is obvious. Both are off by default and switched on by the measuring tool, so a node carries the call sites and none of the work. Runtime rather than a cargo feature on purpose: features unify across a workspace build, so an example asking for `census` would silently switch it on in the node binary built beside it. Co-Authored-By: Claude Opus 5 --- crates/core/src/legacy_census.rs | 384 +++++++++++++++++++ crates/core/src/lib.rs | 2 + crates/core/src/validation/difficulty.rs | 10 + crates/core/src/validation/fork_detection.rs | 12 + crates/core/src/validation/header_rules.rs | 8 + crates/core/src/vm_extremes.rs | 164 ++++++++ crates/execution/src/bridge/btc_chain.rs | 6 + crates/execution/src/bridge/governance.rs | 3 +- crates/execution/src/bridge/peg.rs | 44 ++- crates/execution/src/executor.rs | 91 ++++- crates/execution/src/lib.rs | 2 +- crates/execution/src/precompiles.rs | 8 + crates/execution/src/rsk_handler.rs | 108 +++++- crates/execution/src/rsk_instructions.rs | 68 +++- 14 files changed, 883 insertions(+), 27 deletions(-) create mode 100644 crates/core/src/legacy_census.rs create mode 100644 crates/core/src/vm_extremes.rs diff --git a/crates/core/src/legacy_census.rs b/crates/core/src/legacy_census.rs new file mode 100644 index 00000000..9ccb7f3d --- /dev/null +++ b/crates/core/src/legacy_census.rs @@ -0,0 +1,384 @@ +//! 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::{AtomicBool, AtomicU64, Ordering}; + +/// Whether the counters record anything. +/// +/// Off by default, so a node carries the call sites and none of the work: a +/// disabled `hit` is one relaxed load of a never-written flag, which predicts +/// perfectly and costs nothing measurable. A measurement run turns it on. +/// +/// Runtime rather than a cargo feature on purpose. Features unify across a +/// workspace build, so an example that asked for `census` would silently switch +/// it on in the node binary built beside it -- the opposite of what a build-time +/// switch is for. +static ENABLED: AtomicBool = AtomicBool::new(false); + +/// Start recording. Idempotent, and there is deliberately no way to stop: +/// a run that counted half of something would report it as a whole. +pub fn enable() { + ENABLED.store(true, Ordering::Relaxed); +} + +/// Whether [`enable`] has been called. A report should say so -- all-zero +/// counters mean something very different when nothing was recording. +pub fn is_enabled() -> bool { + ENABLED.load(Ordering::Relaxed) +} + +/// 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", + ), + // The second positive control, and a sharper one than BR-086: a single + // named block with exact figures to match. notes/bounded-windows.md §7 is + // explicit -- "a counter that reports zero for this one is broken". + PrecompileTxGasExceedsLimit => ( + "EVM-023a", + "a transaction sent straight to a precompile is tested against the precompile cost \ + alone but charged that plus the intrinsic cost, so gas used exceeds the gas limit \ + and the remainder goes negative (RSKIP-136; mainnet #3,307 used 31,280 of 30,000)", + "mainnet below #3,397", + ), + EcrecoverDirtyVWord => ( + "PC-051", + "ECRECOVER read octet 63 of the 32-octet v word and ignored the other 31, so a call \ + Ethereum refuses succeeded here", + "all heights, all networks -- tightening needs an activation, not a retroactive close", + ), + UncleCountWrapsDifficulty => ( + "BV-125", + "the uncle count entered the difficulty through 32-bit wrapping arithmetic and the \ + product actually wrapped, so the narrowed value differed from the wide one", + "all heights -- a non-zero count is a live incident, not a historical curiosity", + ), + CommitFederationHandsOverImmediately => ( + "BR-125", + "commitFederation rotated the federations immediately, with no SVP: the legacy \ + handover moved the active federation's UTXOs to the old set there and then", + "mainnet below #7,338,024 (RSKIP-419)", + ), + AddSignatureTopicUsesBtcKey => ( + "BR-136", + "addSignature's log topic carried the federator's BTC key rather than its RSK key", + "mainnet below arrowhead600 (RSKIP-415); identical for legacy single-key members, \ + so a count is the legacy path being taken, not necessarily a differing topic", + ), + BtcHeaderRefusedForChainWork => ( + "BR-097", + "the bridge refused a Bitcoin header because bitcoinj's 12-octet chain-work field \ + overflows at BTC mainnet #849,138 -- receiveHeader answers -99, receiveHeaders \ + stops its loop", + "BTC #849,138 up to arrowhead631 #6,549,300; mainnet only, and on testnet the \ + guard never lifts", + ), + ExtcodehashByTrieExistence => ( + "EVM-043", + "EXTCODEHASH answered from the trie-existence marker rather than the empty-account \ + test, and the two differed: zero where the standard rule gives the empty-code hash", + "mainnet #2,392,700..#3,614,800", + ), + RejectedPeginMarkedProcessed => ( + "BR-055", + "a rejected, unrefundable peg-in was marked processed -- a true window, opened by \ + RSKIP-459 and closed again by RSKIP-551", + "mainnet #7,338,024..#8,804,200", + ), + GasLimitNarrowedToSignedLong => ( + "BV-110", + "a header's gas limit held 2^63 or more, so reading it as a low signed long gave a \ + negative bound that no gas used satisfies -- the narrowed value differed from the \ + whole one", + "all heights -- such a header is invalid, so a canonical replay should report zero", + ), + PegoutAmountSignedLong => ( + "BR-061", + "a releaseBtc request's satoshi amount did not fit a signed 64-bit long, so the \ + low-64-bit signed read differed from the wide value (a negative long is below \ + every minimum and is refunded as it is)", + "all heights -- unreachable on mainnet/testnet balances, reachable on regtest", + ), + FlyoverCodeSignExtended => ( + "BR-112", + "a flyover response code was negative and so was encoded sign-extended across the \ + full 256 bits rather than at a narrower width", + "from iris300 -- known occupied: a mainnet transaction depends on the full width", + ), + UncleSumWraps => ( + "BV-173", + "the uncle-count sum over the 32 newest headers wrapped in 32-bit arithmetic, so \ + the narrowed sum differed from the wide one", + "all heights -- the counts are the miners' to choose, so this is monitoring", + ), + StipendSumOverflows => ( + "EVM-062", + "a call's requested gas was within the 2,300 stipend of 2^63-1, so the signed \ + 64-bit sum went negative and the calling frame failed with all its gas", + "mainnet below #2,018,000 (RSKIP-150)", + ), + StaticcallNotAnOpcode => ( + "EVM-041a", + "STATICCALL was reached before RSKIP-91 made it an opcode, so the frame halted and \ + consumed all its gas", + "mainnet below #729,000. NOTE: covers the STATICCALL half only -- the shift opcodes \ + and CREATE2 below wasabi100 come from the spec selection, not from a branch here, \ + so they need the reachability census instead", + ), + PrecompileThrowBurnsCallerGas => ( + "EVM-023", + "a precompile's exception left the VM and failed the calling contract with all of \ + its gas, rather than being handled", + "mainnet below #3,614,800 (RSKIP-197); known occupied on TESTNET at #808,484, so a \ + mainnet zero says nothing about the branch being dead", + ), + PrecompileOutputPastDeclaredRegion => ( + "EVM-100", + "a successful precompile call wrote its whole output past the output region the \ + caller declared", + "mainnet below #2,018,000 (RSKIP-150)", + ), + PrecompileCallKeepsReturnData => ( + "EVM-101", + "a successful precompile call did not reset the caller's return-data buffer \ + (case 1 of three)", + "mainnet below #729,000 (RSKIP-90)", + ), + EmptyCallKeepsReturnData => ( + "EVM-101", + "a call that ran nothing did not reset the caller's return-data buffer \ + (case 2 of three)", + "mainnet below #3,614,800 (RSKIP-171)", + ), + RefusedCreateKeepsReturnData => ( + "EVM-101", + "a CREATE refused for depth, funds or an address collision left the caller's \ + return-data buffer holding an earlier call's output", + "all heights -- RSKIP-171 cleared the call paths only, so this third case is live", + ), +} + +impl Legacy { + /// Count one occurrence. One relaxed atomic add, on a branch that is + /// already behind a height test. + pub fn hit(self) { + if !is_enabled() { + return; + } + HITS[self as usize].fetch_add(1, Ordering::Relaxed); + } + + pub fn count(self) -> u64 { + HITS[self as usize].load(Ordering::Relaxed) + } +} + +/// Every counter's value, in catalogue order, for persisting mid-run. +/// +/// A long replay must be stoppable and resumable, and a counter that lives +/// only in memory makes the resumed half report its own totals as the whole +/// chain's -- which would read as a clean window rather than as a partial run. +pub fn snapshot() -> Vec { + HITS.iter().map(|h| h.load(Ordering::Relaxed)).collect() +} + +/// Reload counters saved by [`snapshot`]. +/// +/// Ignores a snapshot of the wrong length: that means the catalogue changed +/// between runs, and carrying old numbers under new names would be worse than +/// starting the counters at zero. The caller is told so it can say so. +#[must_use] +pub fn restore(values: &[u64]) -> bool { + if values.len() != CATALOGUE.len() { + return false; + } + for (h, v) in HITS.iter().zip(values) { + h.store(*v, Ordering::Relaxed); + } + true +} + +/// 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 && Legacy::PrecompileTxGasExceedsLimit.count() > 0 +} + +/// The controls, named, so a report can say *which* one failed rather than +/// that "the campaign" did. +/// +/// Two of them, deliberately. `BR-086` proves a bridge-side counter can fire; +/// `EVM-023a` is sharper, because it names one block and the exact figures it +/// must produce -- mainnet #3,307, 31,280 gas against a 30,000 limit. A run +/// that covered #3,307 and reports zero here has a broken instrument. +pub fn positive_controls() -> [(&'static str, u64); 2] { + [ + ("BR-086", Legacy::MigrationEndAge.count()), + ("EVM-023a", Legacy::PrecompileTxGasExceedsLimit.count()), + ] +} + +#[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. + enable(); + 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); + } + } + + /// The switch is the new way for a campaign to report nothing, so it gets + /// its own test: a disabled counter must not move, and `is_enabled` must + /// tell a report which case it is looking at. + #[test] + fn a_disabled_counter_records_nothing_and_says_so() { + // Deliberately not calling `enable` first. Other tests in this binary + // may already have, so assert the relationship rather than the state. + if !is_enabled() { + let before = Legacy::FreeBridgeTransaction.count(); + Legacy::FreeBridgeTransaction.hit(); + assert_eq!( + Legacy::FreeBridgeTransaction.count(), + before, + "a disabled counter moved" + ); + } + enable(); + assert!(is_enabled()); + let before = Legacy::FreeBridgeTransaction.count(); + Legacy::FreeBridgeTransaction.hit(); + assert_eq!(Legacy::FreeBridgeTransaction.count(), before + 1); + } + + #[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/core/src/lib.rs b/crates/core/src/lib.rs index 5136553c..bcdea7fd 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -1,3 +1,5 @@ +pub mod vm_extremes; +pub mod legacy_census; pub mod checkpoint; pub mod bloom; pub mod events; diff --git a/crates/core/src/validation/difficulty.rs b/crates/core/src/validation/difficulty.rs index 7532ccdb..3bb516d9 100644 --- a/crates/core/src/validation/difficulty.rs +++ b/crates/core/src/validation/difficulty.rs @@ -90,6 +90,16 @@ impl DifficultyRule { 1i32.wrapping_add(header.uncle_count as i32) .wrapping_mul(self.config.duration_limit as i32), ); + // BV-125: the same product without the narrowing. A difference means + // the 32-bit wrap changed the value that decides the difficulty, which + // is a live incident rather than a historical curiosity -- so this + // counter is monitoring, not a measurement to be removed afterwards. + let wide = (1i128 + i128::from(header.uncle_count)) + * i128::from(self.config.duration_limit); + if wide != i128::from(calc_dur) { + crate::legacy_census::Legacy::UncleCountWrapsDifficulty.hit(); + } + let delta = delta as i64; let sign = if calc_dur > delta { diff --git a/crates/core/src/validation/fork_detection.rs b/crates/core/src/validation/fork_detection.rs index 536f7d2c..0bd10283 100644 --- a/crates/core/src/validation/fork_detection.rs +++ b/crates/core/src/validation/fork_detection.rs @@ -86,6 +86,18 @@ pub fn uncle_sum(headers: &[Header]) -> Result { .fold(0i32, |sum, header| { sum.wrapping_add(header.uncle_count as i32) }); + // BV-173: the same sum without the 32-bit narrowing. A difference means + // the wrap changed the value, which is a live incident rather than a + // historical curiosity -- the counts are the miners' to choose, so this + // counter is monitoring and should outlive the measurement. + let wide: i64 = headers + .iter() + .take(NUMBER_OF_UNCLES) + .map(|h| i64::from(h.uncle_count as u32)) + .sum(); + if wide != i64::from(sum) { + crate::legacy_census::Legacy::UncleSumWraps.hit(); + } if sum < 0 { return Err(ValidationError::UncleCountsSumBelowZero { sum }); } diff --git a/crates/core/src/validation/header_rules.rs b/crates/core/src/validation/header_rules.rs index 11164729..371f6964 100644 --- a/crates/core/src/validation/header_rules.rs +++ b/crates/core/src/validation/header_rules.rs @@ -119,6 +119,14 @@ pub struct GasUsedRule; impl HeaderValidator for GasUsedRule { fn validate(&self, header: &Header) -> Result<(), ValidationError> { let limit = header.gas_limit_low_long(); + // BV-110: the narrowed bound against the whole value. A header whose + // limit holds 2^63 or more reads negative here, and no gas used fits + // under it -- so such a header is invalid and a canonical replay + // should report zero. A non-zero count means a block we accepted + // carried one, which is a finding about the decoder, not the chain. + if header.gas_limit_value() > num_bigint::BigUint::from(i64::MAX as u64) { + crate::legacy_census::Legacy::GasLimitNarrowedToSignedLong.hit(); + } // rskj reads the gas used exactly, so it is a `long` and never // negative. if i64::try_from(header.gas_used) diff --git a/crates/core/src/vm_extremes.rs b/crates/core/src/vm_extremes.rs new file mode 100644 index 00000000..bf8f8024 --- /dev/null +++ b/crates/core/src/vm_extremes.rs @@ -0,0 +1,164 @@ +//! The largest thing the chain ever did, rather than how often it did it. +//! +//! The census next door ([`crate::legacy_census`]) answers "was this branch +//! ever taken". These answer "how far did it ever go" -- the deepest call +//! stack, the most EVM memory a transaction expanded, the largest `RETURN` +//! payload. Different question, so a different instrument: a maximum, not a +//! counter. +//! +//! # Why a packed `u64` rather than a value and a block side by side +//! +//! A maximum is worth little without the block that set it: "4,183 octets" is +//! a fact, "4,183 octets at #7,912,004" is something you can go and look at. +//! Two separate atomics would race -- one thread could win the value while +//! another overwrote the block -- and a mutex on a path that runs per frame is +//! too expensive. +//! +//! So each extreme is one `AtomicU64` holding `value << 32 | block`. A single +//! `fetch_max` then orders by value and carries the block with it, with no +//! lock and no torn pair. Where two blocks reach the same maximum the higher +//! one wins the tie, so the block reported is the **last** to reach it, not +//! the first -- which is what the report must say. Every quantity here fits comfortably in 32 bits: a +//! call depth is bounded by 1,024, a `RETURN` by the memory a block's gas can +//! buy, and the chain's height is under 2^24. +//! +//! Values at or above 2^32 are clamped rather than wrapped, so a hit on the +//! clamp reads as `4294967295` and is obviously a clamp rather than quietly +//! aliasing a small number. + +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +/// Whether the high-water marks record anything. See +/// [`crate::legacy_census::enable`] for why this is runtime and not a feature. +static ENABLED: AtomicBool = AtomicBool::new(false); + +/// Start recording. +pub fn enable() { + ENABLED.store(true, Ordering::Relaxed); +} + +/// Whether [`enable`] has been called. +pub fn is_enabled() -> bool { + ENABLED.load(Ordering::Relaxed) +} + +thread_local! { + /// The block each worker thread is replaying. + /// + /// Thread-local because a replay runs several segments at once, on + /// different heights; a global would attribute one worker's extreme to + /// another's block. The extremes themselves stay global -- the chain-wide + /// maximum is the point. + static CURRENT_BLOCK: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Called once per block by whatever is driving execution. +pub fn set_block(number: u64) { + if !is_enabled() { + return; + } + CURRENT_BLOCK.with(|b| b.set(number)); +} + +static MAX_CALL_DEPTH: AtomicU64 = AtomicU64::new(0); +static MAX_MEMORY_BYTES: AtomicU64 = AtomicU64::new(0); +static MAX_RETURN_BYTES: AtomicU64 = AtomicU64::new(0); + +/// Returns whether this raised the maximum, so the caller can journal the +/// contract responsible -- which the packed value has no room for, and which +/// is the thing you actually want when a mark turns out to be interesting. +fn note(slot: &AtomicU64, value: u64) -> bool { + if !is_enabled() { + return false; + } + let clamped = value.min(u64::from(u32::MAX)); + let block = CURRENT_BLOCK.with(|b| b.get()).min(u64::from(u32::MAX)); + let packed = (clamped << 32) | block; + let previous = slot.fetch_max(packed, Ordering::Relaxed); + // Compare values, not packed words: a new block with an equal value raises + // the packed word but is not a new maximum worth journalling. + (previous >> 32) < clamped +} + +fn read(slot: &AtomicU64) -> (u64, u64) { + let packed = slot.load(Ordering::Relaxed); + (packed >> 32, packed & 0xffff_ffff) +} + +/// The depth of a frame a CALL-family opcode opened. +#[must_use] +pub fn note_call_depth(depth: u64) -> bool { + note(&MAX_CALL_DEPTH, depth) +} + +/// EVM memory expanded, in octets, sampled as a frame ends. +#[must_use] +pub fn note_memory_bytes(bytes: u64) -> bool { + note(&MAX_MEMORY_BYTES, bytes) +} + +/// The length of a `RETURN`'s payload, in octets. +#[must_use] +pub fn note_return_bytes(bytes: u64) -> bool { + note(&MAX_RETURN_BYTES, bytes) +} + +/// The three packed extremes, for persisting mid-run. See +/// [`crate::legacy_census::snapshot`] for why. +pub fn snapshot() -> [u64; 3] { + [ + MAX_CALL_DEPTH.load(Ordering::Relaxed), + MAX_MEMORY_BYTES.load(Ordering::Relaxed), + MAX_RETURN_BYTES.load(Ordering::Relaxed), + ] +} + +/// Reload extremes saved by [`snapshot`]. +/// +/// `fetch_max` rather than `store`, so reloading can only raise a maximum -- +/// a stale or duplicated snapshot cannot lower one that this run already set. +pub fn restore(values: &[u64; 3]) { + MAX_CALL_DEPTH.fetch_max(values[0], Ordering::Relaxed); + MAX_MEMORY_BYTES.fetch_max(values[1], Ordering::Relaxed); + MAX_RETURN_BYTES.fetch_max(values[2], Ordering::Relaxed); +} + +/// `(what, value, block)` for each extreme, for a report. +pub fn extremes() -> [(&'static str, u64, u64); 3] { + let (d, db) = read(&MAX_CALL_DEPTH); + let (m, mb) = read(&MAX_MEMORY_BYTES); + let (r, rb) = read(&MAX_RETURN_BYTES); + [ + ("deepest CALL-family frame", d, db), + ("most EVM memory expanded (octets)", m, mb), + ("largest RETURN payload (octets)", r, rb), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_maximum_keeps_the_block_that_set_it() { + enable(); + let slot = AtomicU64::new(0); + set_block(100); + note(&slot, 7); + set_block(200); + note(&slot, 3); // smaller: must not displace the larger + assert_eq!(read(&slot), (7, 100)); + set_block(300); + note(&slot, 9); + assert_eq!(read(&slot), (9, 300)); + } + + #[test] + fn an_oversized_value_clamps_rather_than_wrapping() { + enable(); + let slot = AtomicU64::new(0); + set_block(1); + note(&slot, u64::from(u32::MAX) + 5_000); + assert_eq!(read(&slot).0, u64::from(u32::MAX)); + } +} diff --git a/crates/execution/src/bridge/btc_chain.rs b/crates/execution/src/bridge/btc_chain.rs index 9bded8d1..1d40df69 100644 --- a/crates/execution/src/bridge/btc_chain.rs +++ b/crates/execution/src/bridge/btc_chain.rs @@ -133,6 +133,8 @@ pub fn receive_header( && is_mainnet && !hardfork_cfg.has_rskip434(block_number) { + // BR-097, the singular `receiveHeader` arm. + crate::legacy_census::Legacy::BtcHeaderRefusedForChainWork.hit(); return Ok(encode_int_result(gas_cost, ERR_UNEXPECTED_EXCEPTION)); } @@ -609,6 +611,10 @@ pub fn receive_headers( && is_mainnet && !rskip434 { + // BR-097, the plural `receiveHeaders` arm. Counted here too: the + // window is the same one, and a count from either arm means a + // header was actually refused for chain work. + crate::legacy_census::Legacy::BtcHeaderRefusedForChainWork.hit(); break; } // `btcBlockChain.add`, which takes a header already stored as it is. diff --git a/crates/execution/src/bridge/governance.rs b/crates/execution/src/bridge/governance.rs index b983b74b..05c3c73d 100644 --- a/crates/execution/src/bridge/governance.rs +++ b/crates/execution/src/bridge/governance.rs @@ -762,7 +762,8 @@ fn commit_pending_federation( ); store_pending_federation(ctx, None, multikey); } else { - // Legacy handover. Move active-federation UTXOs to the old set. + // BR-125. Legacy handover. Move active-federation UTXOs to the old set. + crate::legacy_census::Legacy::CommitFederationHandsOverImmediately.hit(); let active_utxos = load_federation_utxos(ctx, hardfork_cfg, block_number); store_federation_utxos(ctx, hardfork_cfg, block_number, &[]); super::storage::store_old_federation_utxos(ctx, &active_utxos); diff --git a/crates/execution/src/bridge/peg.rs b/crates/execution/src/bridge/peg.rs index f383a1bb..3e1e92e7 100644 --- a/crates/execution/src/bridge/peg.rs +++ b/crates/execution/src/bridge/peg.rs @@ -84,6 +84,27 @@ fn should_mark_rejected_pegin_as_processed(cfg: &RskHardforkConfig, block_number cfg.has_rskip459(block_number) && !cfg.has_rskip551(block_number) } +/// The same predicate, counted (`BR-055`). +/// +/// Every production caller goes through this rather than the bare predicate, +/// and the counting is exact because of where the call sites sit. Two are +/// `if marks(..) { set_btc_tx_processed(..) }`, so a count is a marking. The +/// third is guarded by `evaluated &&`, which short-circuits before this is +/// reached when nothing was evaluated. The fourth is the right arm of +/// `!rskip379 || marks(..)` -- so when the marking happens *because* RSKIP-379 +/// is inactive, this is never evaluated and nothing is counted, which is +/// correct: that marking is not the window's doing. +/// +/// The bare predicate is left uncounted so its unit tests can probe the window +/// edges without moving the counter. +fn marks_rejected_pegin_as_processed(cfg: &RskHardforkConfig, block_number: u64) -> bool { + let yes = should_mark_rejected_pegin_as_processed(cfg, block_number); + if yes { + crate::legacy_census::Legacy::RejectedPeginMarkedProcessed.hit(); + } + yes +} + /// rskj `PegUtilsLegacy.isValidPegInTx` minimum gate over the live-federations /// outputs. Under RSKIP293 each UTXO must be at least `min` /// (`isAnyUTXOAmountBelowMinimum`); before it, the *total* sent must be @@ -671,7 +692,7 @@ pub fn register_btc_transaction( super::events::log_rejected_pegin(ctx, &hash, 5); super::events::log_unrefundable_pegin(ctx, &hash, 3); } - if evaluated && should_mark_rejected_pegin_as_processed(hardfork_cfg, rsk_height) { + if evaluated && marks_rejected_pegin_as_processed(hardfork_cfg, rsk_height) { set_btc_tx_processed(ctx, &legacy_txid, rsk_height, hardfork_cfg.has_rskip134(rsk_height)); } return Ok(PrecompileOutput::new(gas_cost, Bytes::new())); @@ -782,7 +803,7 @@ pub fn register_btc_transaction( if logs { super::events::log_unrefundable_pegin(ctx, &hash, 1); } - !rskip379 || should_mark_rejected_pegin_as_processed(hardfork_cfg, rsk_height) + !rskip379 || marks_rejected_pegin_as_processed(hardfork_cfg, rsk_height) } }; if mark { @@ -951,7 +972,7 @@ pub fn register_btc_transaction( let hash = btc_txid_event_bytes(&btc_tx); super::events::log_rejected_pegin(ctx, &hash, 3); super::events::log_unrefundable_pegin(ctx, &hash, 1); - if should_mark_rejected_pegin_as_processed(hardfork_cfg, rsk_height) { + if marks_rejected_pegin_as_processed(hardfork_cfg, rsk_height) { set_btc_tx_processed(ctx, &legacy_txid, rsk_height, hardfork_cfg.has_rskip134(rsk_height)); } } else if hardfork_cfg.has_rskip170(rsk_height) { @@ -1038,7 +1059,7 @@ pub fn register_btc_transaction( let hash = btc_txid_event_bytes(&btc_tx); super::events::log_rejected_pegin(ctx, &hash, 2); super::events::log_unrefundable_pegin(ctx, &hash, 4); - if should_mark_rejected_pegin_as_processed(hardfork_cfg, rsk_height) { + if marks_rejected_pegin_as_processed(hardfork_cfg, rsk_height) { set_btc_tx_processed(ctx, &legacy_txid, rsk_height, hardfork_cfg.has_rskip134(rsk_height)); } return Ok(PrecompileOutput::new(gas_cost, Bytes::new())); @@ -1888,6 +1909,12 @@ mod flyover_codes { /// (mainnet #5,967,453: GENERIC_ERROR -900 mis-encoded as `2^128-900`). fn flyover_code_output(code: i64) -> Bytes { let value = if code < 0 { + // BR-112: the full-width encoding is load-bearing -- a mainnet + // transaction depends on the wrap being at bit 256, and a 128-bit-wide + // encoding of -900 diverged it. So this branch is known occupied, and + // a zero here would mean the counter is wrong rather than the branch + // unused. + crate::legacy_census::Legacy::FlyoverCodeSignExtended.hit(); // Full 256-bit two's complement: 2^256 - |code|. U256::ZERO.wrapping_sub(U256::from(code.unsigned_abs())) } else { @@ -2923,6 +2950,13 @@ pub fn release_btc( // comes near 2^63 satoshis, but regtest's genesis funds accounts with // 10^30 wei, which wrap, and wrap negative past 2^63: a negative long is // below every minimum, and rskj logs and refunds it as it is. + // BR-061: the low 64 bits as a signed long. Where the wide value does not + // fit, this read differs from it -- and a negative long is below every + // minimum and is refunded as it stands. Counting the divergence is the + // §6d predicate, and it is monitoring rather than a one-shot measurement. + if amount_satoshis_u256 > U256::from(i64::MAX as u64) { + crate::legacy_census::Legacy::PegoutAmountSignedLong.hit(); + } let satoshis = amount_satoshis_u256.as_limbs()[0] as i64; // The amount the events carry before RSKIP427. let satoshis_word = long_word(satoshis); @@ -5211,6 +5245,8 @@ pub fn add_signature( .map(|k| super::federation::key_encoding(&k).to_vec()) .unwrap_or_else(|| fed_key.clone()) } else { + // BR-136: the legacy topic key. + crate::legacy_census::Legacy::AddSignatureTopicUsesBtcKey.hit(); fed_key.clone() }; let emit_add_signature = |ctx: &mut CTX, btc_tx: &BtcTransaction| { diff --git a/crates/execution/src/executor.rs b/crates/execution/src/executor.rs index e64f329c..1aec557e 100644 --- a/crates/execution/src/executor.rs +++ b/crates/execution/src/executor.rs @@ -994,6 +994,10 @@ impl RskExecutor { state_root: &TrieNode, trie_store: Arc, ) -> Result { + // Attributes any extreme recorded while this block runs. Thread-local, + // so two workers replaying different heights cannot credit each other. + rustock_core::vm_extremes::set_block(header.number); + crate::rsk_instructions::set_block_number(header.number); // A tracer with a zero cap, and `trace_index: None` so `run` is used // for every transaction -- the inspector is never invoked. self.execute_block_with( @@ -2106,6 +2110,18 @@ impl RskExecutor { let _ = evm.ctx.journal_mut().load_account(callee); let mut invisible_exception = false; + // EVM-023a / RSKIP-136, the non-Bridge half. `Outcome::OutOfGas` + // is raised only when `required > tx_gas`, so a limit in + // `[required, required + basic)` reaches the arms below and is + // charged past what it bought, exactly as the Bridge arm is. + // Counting only the Bridge would undercount the control. + let charge = |gas: u64| -> u64 { + let used = gas.saturating_add(basic); + if used > tx_gas { + crate::legacy_census::Legacy::PrecompileTxGasExceedsLimit.hit(); + } + used + }; let (gas_used, success, output, logs) = match pre136_outcome { // What `getGasForData` asked for came to more than the whole // limit: rskj's execError, all the gas used and nothing run. @@ -2115,7 +2131,7 @@ impl RskExecutor { Some(Outcome::Threw { gas, reason }) => { debug!(tx_index = i, %reason, "direct precompile call threw"); invisible_exception = true; - (gas.saturating_add(basic), true, Vec::new(), Vec::new()) + (charge(gas), true, Vec::new(), Vec::new()) } Some(Outcome::Fatal(reason)) => return Err(ExecutionError::Evm(reason)), // It returned, or returned rskj's null, which is no output. @@ -2127,14 +2143,14 @@ impl RskExecutor { if !markers.precompiles.contains(&callee) { markers.precompiles.push(callee); } - (gas.saturating_add(basic), true, output.to_vec(), Vec::new()) + (charge(gas), true, output.to_vec(), Vec::new()) } Some(Outcome::Null { gas }) => { let _ = evm.ctx.journal_mut().transfer(*sender, callee, tx.value); if !markers.precompiles.contains(&callee) { markers.precompiles.push(callee); } - (gas.saturating_add(basic), true, Vec::new(), Vec::new()) + (charge(gas), true, Vec::new(), Vec::new()) } // The Bridge, whose price depends on what its storage holds. None => { @@ -2152,7 +2168,26 @@ impl RskExecutor { let limit = tx_gas; if limit >= required { // gasUsed may exceed the limit; that is consensus here. - (required.saturating_add(basic), true) + let used = required.saturating_add(basic); + // EVM-023a / RSKIP-136. The test above is + // `limit >= required`; the charge is + // `required + basic`. A limit in + // `[required, required + basic)` therefore + // passes a test it cannot afford, the + // remainder goes negative, and the miner is + // credited wei no account was debited. + // + // This is the campaign's second positive + // control: a run covering mainnet #3,307 must + // report a non-zero count here (31,280 used + // against a 30,000 limit). A zero means the + // instrument is broken, not that the window + // is clean. + if used > limit { + crate::legacy_census::Legacy::PrecompileTxGasExceedsLimit + .hit(); + } + (used, true) } else { // rskj execError: all gas consumed, nothing executed. (limit, false) @@ -6933,6 +6968,42 @@ mod tests { /// succeeded, that slot (2 after a call that succeeded, 1 after one that /// failed, 0 where the contract never got to store it), and how many logs /// the transaction left. + /// The `vm_extremes` hooks are wired to live code, not merely compiled. + /// + /// This is the lesson of the whole-chain run that reported one SWAPN and + /// could not say where: an instrument whose liveness is unknown reports + /// zero exactly as convincingly as a behaviour that never happened. The + /// fixture below runs a contract that CODECOPYs its input (expanding + /// memory) and then CALLs a precompile (opening a frame), so all three + /// hooks must move. Maxima are process-global and tests run in parallel, + /// so this asserts movement rather than absolute figures. + #[test] + fn the_vm_extreme_hooks_are_reached_by_real_execution() { + use rustock_core::vm_extremes; + vm_extremes::enable(); + let before = vm_extremes::extremes().map(|(_, v, _)| v); + + let block_store = Arc::new(BlockStore::open(tempfile::tempdir().unwrap().path()).unwrap()); + let header = dummy_header(2_100_000); + let _ = a_precompile_called_from_a_contract( + block_store, + &header, + crate::precompiles::BLOCK_HEADER_ADDR, + 0xf1, + &[0u8; 32], + ); + + let after = vm_extremes::extremes().map(|(_, v, _)| v); + assert!( + after[0] >= before[0] && after[0] > 0, + "call-depth hook never fired: a CALL opened no frame the hook saw" + ); + assert!( + after[1] >= before[1] && after[1] > 0, + "memory hook never fired: the contract CODECOPYs, so memory did expand" + ); + } + fn a_precompile_called_from_a_contract( block_store: Arc, header: &Header, @@ -13461,9 +13532,21 @@ bf09f6e52420834e8e0e0b1a6df563aba550cf7f99e9724264187c45dcf3d73e8585a0e35196\ }; let executor = RskExecutor::new(RskHardforkConfig::mainnet(), block_store); + // The EVM-023a counter is this campaign's second positive control, so + // it is validated here rather than after an eleven-hour replay. The + // counters are process-global and tests run in parallel, so the test + // is `after > before` rather than an absolute count. + crate::legacy_census::enable(); + let before = crate::legacy_census::Legacy::PrecompileTxGasExceedsLimit.count(); let result = executor.execute_block(&header, &[(tx, sender)], &root, store).unwrap(); assert!(result.tx_results[0].success); assert_eq!(result.tx_results[0].gas_used, 31_600, "gasUsed exceeds the tx gas limit pre-RSKIP136"); + assert!( + crate::legacy_census::Legacy::PrecompileTxGasExceedsLimit.count() > before, + "EVM-023a is a positive control: this is the exact shape of mainnet #3,307, \ + so a counter that does not fire here will report a false zero over the \ + whole chain" + ); } /// getCoinbaseAddress at depth 1 returns the grandparent's coinbase. diff --git a/crates/execution/src/lib.rs b/crates/execution/src/lib.rs index 9c819ad8..ac758066 100644 --- a/crates/execution/src/lib.rs +++ b/crates/execution/src/lib.rs @@ -8,7 +8,7 @@ pub mod executor; pub mod gas_estimator; pub mod hardfork; pub mod internal_tx; -pub mod legacy_census; +pub use rustock_core::legacy_census; pub mod mining; pub(crate) mod native; pub mod precompiles; diff --git a/crates/execution/src/precompiles.rs b/crates/execution/src/precompiles.rs index 003a1282..f5cd798f 100644 --- a/crates/execution/src/precompiles.rs +++ b/crates/execution/src/precompiles.rs @@ -169,6 +169,13 @@ fn ecrecover(input: &[u8]) -> Option<[u8; 32]> { if input.len() < 96 { return None; } + // PC-051: only octet 63 of the 32-octet `v` word is read, so a word + // Ethereum refuses outright is accepted here. Count the calls that + // actually carried information in the 31 octets this ignores -- that + // count is the whole proof obligation for tightening the rule. + if input[32..63].iter().any(|&b| b != 0) { + crate::legacy_census::Legacy::EcrecoverDirtyVWord.hit(); + } let v = input[63]; if v != 27 && v != 28 { return None; @@ -1015,6 +1022,7 @@ impl RskPrecompileProvider { // and revert so the caller refunds the forwarded leftover. if let Some(spent) = crate::bridge::internal_throw_gas(e) { if !self.rskip197_active(context) { + crate::legacy_census::Legacy::PrecompileThrowBurnsCallerGas.hit(); // Before RSKIP197 (iris300) `Program.executePrecompiled` // has no error handling: the throw leaves the VM and fails // the contract that made the call, with all its gas, which diff --git a/crates/execution/src/rsk_handler.rs b/crates/execution/src/rsk_handler.rs index 890b8c0e..0f6fc564 100644 --- a/crates/execution/src/rsk_handler.rs +++ b/crates/execution/src/rsk_handler.rs @@ -945,6 +945,21 @@ where init.frame_input, revm::interpreter::interpreter_action::FrameInput::Create(_) ); + // The deepest frame a CALL-family opcode ever opened. + // Recorded at the open, before the depth cap can refuse it, + // so the figure is the depth actually reached rather than + // the depth that survived. Creates are excluded: the ask + // was about the CALL opcodes. + if !creates + && rustock_core::vm_extremes::note_call_depth(init.depth as u64) + { + tracing::warn!( + target: "rustock::vm_extremes", + "new deepest CALL frame: depth {} opened by {:?}", + init.depth, + callee + ); + } // Before anything can refuse the call (`note_call`). if let Some(callee) = callee { self.note_call(callee); @@ -1084,6 +1099,14 @@ where && outcome.instruction_result().is_ok() && outcome.result.output.len() > outcome.memory_length() { + // EVM-100: the output genuinely exceeded + // the declared region, so the legacy write + // past it is about to happen. Counting the + // enclosing `if let` instead would count + // every pre-RSKIP150 precompile call. + crate::legacy_census::Legacy + ::PrecompileOutputPastDeclaredRegion + .hit(); unbounded_output = Some(( outcome.memory_start(), outcome.result.output.clone(), @@ -1111,18 +1134,56 @@ where FrameResult::Call(outcome) => { let precompile = callee .is_some_and(|c| self.active_precompiles.contains(&c)); + // EVM-101's first two cases. Counted + // separately because they are separate + // windows -- RSKIP-90 closed one and + // RSKIP-171 the other -- so a single + // counter could not say which branch a + // removal would be retiring. if precompile && outcome.instruction_result().is_ok() { - !self.rskip90_active + let preserves = !self.rskip90_active; + if preserves { + crate::legacy_census::Legacy + ::PrecompileCallKeepsReturnData + .hit(); + } + preserves } else { - !self.rskip171_active + let preserves = !self.rskip171_active; + if preserves { + crate::legacy_census::Legacy + ::EmptyCallKeepsReturnData + .hit(); + } + preserves } } - FrameResult::Create(outcome) => matches!( - outcome.instruction_result(), - InstructionResult::CallTooDeep - | InstructionResult::OutOfFunds - | InstructionResult::CreateCollision - ), + FrameResult::Create(outcome) => { + let refused = matches!( + outcome.instruction_result(), + InstructionResult::CallTooDeep + | InstructionResult::OutOfFunds + | InstructionResult::CreateCollision + ); + // EVM-101's third case. RSKIP-171 added + // the clearing on the call paths only, so + // a CREATE refused before its program is + // built still leaves the caller's + // return-data buffer holding an earlier + // call's output -- at every height, with + // no upper bound. + // + // Counting the refused path alone settles + // whether the case ever arose. Only a + // non-zero makes the harder question -- + // whether anything then read the stale + // buffer -- worth asking. + if refused { + crate::legacy_census::Legacy::RefusedCreateKeepsReturnData + .hit(); + } + refused + } }; if rskj_preserves { use revm::interpreter::interpreter_types::ReturnData; @@ -1147,6 +1208,37 @@ where FrameResult::Create(outcome) if matches!(outcome.instruction_result(), InstructionResult::Revert) ); + // The most EVM memory this frame expanded, sampled as it + // ends -- once per frame rather than per opcode, which a + // memory-touching instruction hook would cost. The + // chain-wide maximum over frames is the figure wanted. + { + use revm::interpreter::interpreter_types::{InputsTr, MemoryTr}; + let frame = evm.frame_stack().get(); + let used = frame.interpreter.memory.size() as u64; + let who = frame.interpreter.input.target_address(); + if rustock_core::vm_extremes::note_memory_bytes(used) { + tracing::warn!( + target: "rustock::vm_extremes", + "new EVM-memory high-water mark: {used} octets in a frame of {who}" + ); + } + } + // The largest RETURN payload. `Return` only -- STOP and + // SELFDESTRUCT end a frame with no RETURN behind them, and + // a revert is not a return. + if matches!(result.instruction_result(), InstructionResult::Return) { + let returned = match &result { + FrameResult::Call(o) => o.result.output.len(), + FrameResult::Create(o) => o.result.output.len(), + }; + if rustock_core::vm_extremes::note_return_bytes(returned as u64) { + tracing::warn!( + target: "rustock::vm_extremes", + "new largest RETURN: {returned} octets" + ); + } + } self.close_frame(evm, result.instruction_result().is_ok()); // The program's internal transactions (`crate::internal_tx`). // rskj `Program.suicide` makes one of the balance it diff --git a/crates/execution/src/rsk_instructions.rs b/crates/execution/src/rsk_instructions.rs index 2850e25b..d6cc7587 100644 --- a/crates/execution/src/rsk_instructions.rs +++ b/crates/execution/src/rsk_instructions.rs @@ -162,6 +162,21 @@ pub fn set_transaction_index(index: u64) { TX_INDEX.with(|i| i.set(index)); } +thread_local! { + /// The block being executed, for the RSK-opcode journal. + /// + /// The whole-chain run of 2026-11-22 found exactly one SWAPN in 9,429,718 + /// blocks and could not say which block it was in, because the record + /// carried only the transaction index. A single occurrence in nine million + /// blocks is worth locating. + static BLOCK_NUMBER: core::cell::Cell = const { core::cell::Cell::new(0) }; +} + +/// Called once per block, beside [`set_transaction_index`] per transaction. +pub fn set_block_number(number: u64) { + BLOCK_NUMBER.with(|b| b.set(number)); +} + /// Install the rskj-semantics CALL family into an instruction table. /// /// `extcodehash_enabled` reflects RSKIP140 (papyrus): the spec is PETERSBURG @@ -380,7 +395,7 @@ pub fn install( instructions.insert_instruction( opcode::STATICCALL, if !staticcall_enabled { - Instruction::new(invalid_opcode::, 0) + Instruction::new(invalid_staticcall::, 0) } else if staticcall_takes_value { Instruction::new(rsk_static_call_with_value::, CALL_STATIC_GAS) } else { @@ -500,6 +515,19 @@ fn invalid_opcode( context.interpreter.halt(InstructionResult::OpcodeNotFound); } +/// `invalid_opcode`, counted for `EVM-041a`. +/// +/// A separate function rather than a flag inside `invalid_opcode`, because +/// that handler is shared with EXTCODEHASH below papyrus200 and the two are +/// different rules -- counting inside it would report one window's occupancy +/// under the other's name. +fn invalid_staticcall( + context: InstructionContext<'_, H, WIRE>, +) { + crate::legacy_census::Legacy::StaticcallNotAnOpcode.hit(); + invalid_opcode(context); +} + /// `keccak256("")`, the code hash rskj reports for an existing-but-codeless /// account and for active precompiles (`Keccak256Helper.keccak256(EMPTY)`). pub(crate) const KECCAK_EMPTY: B256 = B256::new([ @@ -591,7 +619,14 @@ fn rsk_extcodehash( KECCAK_EMPTY } else { match context.host.holds_contract_marker(addr) { - Some(true) => B256::ZERO, + Some(true) => { + // EVM-043. Only this arm differs from the standard rule -- + // `Some(false)` gives the empty-code hash either way -- so + // counting the whole legacy branch would overstate the + // window's occupancy. + crate::legacy_census::Legacy::ExtcodehashByTrieExistence.hit(); + B256::ZERO + } Some(false) => KECCAK_EMPTY, None => { context.interpreter.halt_fatal(); @@ -1026,7 +1061,7 @@ fn rsk_opcode_index(op: u8) -> usize { /// to look: the first occurrence of an opcode that may never have run on this /// chain belongs in the journal. Capped, because a contract in a loop would /// otherwise fill the log with the same discovery. -fn record_rsk_opcode(op: u8) { +fn record_rsk_opcode(op: u8, who: Address) { let n = RSK_OPCODE_HITS[rsk_opcode_index(op)].fetch_add(1, Ordering::Relaxed) + 1; if n <= 8 { let name = match op { @@ -1036,9 +1071,11 @@ fn record_rsk_opcode(op: u8) { }; tracing::warn!( target: "rustock::rsk_opcodes", - "{name} (0x{op:02x}) executed, occurrence {n} in this process, transaction \ - index {} of its block. These opcodes were removed by RSKIP191 at iris300.", - TX_INDEX.with(|i| i.get()) + "{name} (0x{op:02x}) executed at block #{} transaction {} by contract {who}, \ + occurrence {n} in this process. These opcodes were removed by RSKIP191 at \ + iris300.", + BLOCK_NUMBER.with(|b| b.get()), + TX_INDEX.with(|i| i.get()), ); } } @@ -1155,7 +1192,10 @@ pub fn rsk_opcode_hits() -> [u64; 3] { } fn rsk_dupn(context: InstructionContext<'_, H, WIRE>) { - record_rsk_opcode(RSK_DUPN); + { + use revm::interpreter::interpreter_types::InputsTr; + record_rsk_opcode(RSK_DUPN, context.interpreter.input.target_address()); + } let Some([depth]) = context.interpreter.stack.popn::<1>() else { context.interpreter.halt_underflow(); return; @@ -1173,7 +1213,10 @@ fn rsk_dupn(context: InstructionContex /// top with the item `d + 2` from the top, so SWAPN of 0 is SWAP1. It fails /// as DUPN does, and steps over the next byte in the same way. fn rsk_swapn(context: InstructionContext<'_, H, WIRE>) { - record_rsk_opcode(RSK_SWAPN); + { + use revm::interpreter::interpreter_types::InputsTr; + record_rsk_opcode(RSK_SWAPN, context.interpreter.input.target_address()); + } let Some([depth]) = context.interpreter.stack.popn::<1>() else { context.interpreter.halt_underflow(); return; @@ -1210,7 +1253,10 @@ fn step_over_next_byte( /// TXINDEX (before RSKIP191), rskj `VM.doTXINDEX`: pushes the index in its /// block of the transaction being executed. See `TX_INDEX`. fn rsk_txindex(context: InstructionContext<'_, H, WIRE>) { - record_rsk_opcode(RSK_TXINDEX); + { + use revm::interpreter::interpreter_types::InputsTr; + record_rsk_opcode(RSK_TXINDEX, context.interpreter.input.target_address()); + } assert_configured("TX_INDEX"); let index = TX_INDEX.with(|i| i.get()); if !context.interpreter.stack.push(U256::from(index)) { @@ -1533,6 +1579,10 @@ where if stipend > 0 && stipend_sum_wraps() { let held = requested.min(i64::MAX as u64); if held > i64::MAX as u64 - stipend { + // EVM-062: the request was within the stipend of 2^63-1, so rskj's + // signed sum went negative and the calling frame failed with all + // its gas. Counting the branch is what licenses retiring it. + crate::legacy_census::Legacy::StipendSumOverflows.hit(); context.interpreter.halt_oog(); return None; } From 7b92791f7b21da77a2efa4496f3c1e7c7bdaf0cc Mon Sep 17 00:00:00 2001 From: Sergio Demian Lerner Date: Mon, 23 Nov 2026 16:27:59 +0000 Subject: [PATCH 4/9] Make reexec_all stoppable, resumable, and honest about what it measured A seventeen-hour replay that loses its findings on a stop is not a tool, and this one lost them three ways at once. - The gap list lived only in memory until the scheduler drained its queue, so a kill dropped it. It is now appended after every finished segment, which also keeps the in-memory list small enough that GAP_KEY_LIMIT is never reached. The cap rose from 50,000 to 2,000,000 regardless: the whole-chain run found 510,219 reads and recorded 9.8% of them. - File::create truncated the list, so a resumed run destroyed the previous run's findings. It appends, and truncates only on a genuinely fresh run. - The census counters lived only in memory too, so a resumed run would report its own segments' totals as the whole chain's -- a known-occupied control reading zero, which looks exactly like a clean window. They are banked per segment and reloaded on resume, and the run says out loud when it could not reload them. The gap file is now named after the state file rather than merely placed beside it. Deriving it from the parent directory meant every run on this machine shared one segment-gaps.txt whatever --state said, so a second run with a fresh state file would truncate the first's repair list. On 2026-11-23 that came within one condition of destroying an 18-hour, 510,219-row list, and survived only because the state file happened to be pre-seeded. Stopping is now external and graceful: touch .stop and it finishes the segments in flight, banks them, and exits 2 -- not 1, because a requested stop is not a failure and a script needs to tell them apart. Findings are banked before a segment is marked done, so an interruption between the two replays a segment rather than marking one done whose findings were lost. Two reporting defects went with it. There was no tracing subscriber at all, so the line claiming occurrences were "logged at WARN" was false -- a whole-chain run found one SWAPN and could not say which block it was in. And the positive controls are now reported by name, because "the campaign failed" sends a reader to the whole table where "EVM-023a reported 0" names one counter and one block. Co-Authored-By: Claude Opus 5 --- crates/cli/examples/reexec_all.rs | 300 ++++++++++++++++++++++++++---- 1 file changed, 266 insertions(+), 34 deletions(-) diff --git a/crates/cli/examples/reexec_all.rs b/crates/cli/examples/reexec_all.rs index a27a7d43..b27ba99f 100644 --- a/crates/cli/examples/reexec_all.rs +++ b/crates/cli/examples/reexec_all.rs @@ -147,6 +147,19 @@ struct RamWithFallback { segment: String, } +/// Distinct gap keys kept in memory, and so the most the repair list can hold. +/// +/// A bound rather than a choice, but a generous one. At roughly fifty octets a +/// key this is ~100 MB at the cap, against a whole-chain run that measured +/// 510,219 fallback reads -- so the cap is about four times the largest figure +/// observed rather than a tenth of it. The previous value of 50,000 truncated +/// that run at 9.8%, and a truncated repair list applied as if complete leaves +/// the segment set still under-covering while looking repaired. +/// +/// Truncation is still reported out loud if it happens, because the counters +/// stay exact either way. +const GAP_KEY_LIMIT: usize = 2_000_000; + impl TrieStore for RamWithFallback { fn get(&self, key: &[u8]) -> Option> { if let Some(v) = self.ram.lookup(key) { @@ -156,7 +169,7 @@ impl TrieStore for RamWithFallback { let n = self.from_full.fetch_add(1, Ordering::Relaxed) + 1; let blk = self.current_block.load(Ordering::Relaxed); let mut g = self.gaps.lock().unwrap(); - if g.len() < 50_000 { + if g.len() < GAP_KEY_LIMIT { g.push((blk, self.segment.clone(), key.to_vec())); } // Say the first few out loud: a segment-only run would have got @@ -170,7 +183,26 @@ impl TrieStore for RamWithFallback { } return Some(v); } - self.absent.fetch_add(1, Ordering::Relaxed); + let n = self.absent.fetch_add(1, Ordering::Relaxed) + 1; + // Recorded as well, and marked. These are the reads the archive cannot + // serve either, so they are the ones that cannot be repaired from it -- + // exactly the keys worth having, and until now the only trace they left + // was a number. + let blk = self.current_block.load(Ordering::Relaxed); + { + let mut g = self.gaps.lock().unwrap(); + if g.len() < GAP_KEY_LIMIT { + g.push((blk, format!("{} ABSENT-IN-BOTH", self.segment), key.to_vec())); + } + } + if n <= 50 { + println!( + "[gap] block #{blk} segment {} wanted {} and NEITHER the segment nor the \ + fallback has it", + self.segment, + alloy_primitives::hex::encode(key) + ); + } None } fn put(&self, _k: &[u8], _v: &[u8]) {} @@ -387,7 +419,95 @@ fn rss_mb() -> u64 { // -------------------------------------------------------------------- main -- + +/// A sidecar beside the state file: `.`. +fn sidecar(state_path: &str, ext: &str) -> std::path::PathBuf { + let p = std::path::Path::new(state_path); + let name = p.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); + p.with_file_name(format!("{name}.{ext}")) +} + +/// Bank the counters so a stop does not lose them. +/// +/// Written after every finished segment. Without this a resumed run reports +/// only the segments it personally ran, so a known-occupied control could read +/// zero and the whole table would look unvalidated. +fn save_counters(path: &std::path::Path) { + let census: Vec = + rustock_execution::legacy_census::snapshot().iter().map(|v| v.to_string()).collect(); + let ext: Vec = + rustock_core::vm_extremes::snapshot().iter().map(|v| v.to_string()).collect(); + let body = format!("census {}\nextremes {}\n", census.join(" "), ext.join(" ")); + let tmp = path.with_extension("tmp"); + if std::fs::write(&tmp, body).is_ok() { + let _ = std::fs::rename(&tmp, path); + } +} + +/// Reload counters banked by [`save_counters`]. Returns what it managed. +fn load_counters(path: &std::path::Path) -> (bool, bool) { + let Ok(text) = std::fs::read_to_string(path) else { + return (false, false); + }; + let (mut census_ok, mut ext_ok) = (false, false); + for line in text.lines() { + let mut it = line.split_whitespace(); + match it.next() { + Some("census") => { + let v: Vec = it.filter_map(|t| t.parse().ok()).collect(); + census_ok = rustock_execution::legacy_census::restore(&v); + } + Some("extremes") => { + let v: Vec = it.filter_map(|t| t.parse().ok()).collect(); + if let Ok(a) = <[u64; 3]>::try_from(v.as_slice()) { + rustock_core::vm_extremes::restore(&a); + ext_ok = true; + } + } + _ => {} + } + } + (census_ok, ext_ok) +} + +/// Append what the gap list holds to the repair file and clear it. +/// +/// Called after every finished segment, which is what makes the repair list +/// survive a stop, survive a crash, and survive a resume -- and keeps the +/// in-memory list small enough that `GAP_KEY_LIMIT` is never reached. +/// Entries carry their own segment name, so draining another worker's +/// in-flight rows early is harmless. +fn flush_gaps(gaps: &Mutex)>>, path: &std::path::Path) -> usize { + let drained: Vec<(u64, String, Vec)> = { + let mut g = gaps.lock().unwrap_or_else(|e| e.into_inner()); + std::mem::take(&mut *g) + }; + if drained.is_empty() { + return 0; + } + let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(path) else { + eprintln!("WARNING: could not append {} gap rows to {}", drained.len(), path.display()); + return 0; + }; + for (b, seg, k) in &drained { + let _ = writeln!(f, "{b}\t{seg}\t{}", alloy_primitives::hex::encode(k)); + } + let _ = f.flush(); + drained.len() +} + fn main() -> anyhow::Result<()> { + // Without this there is no subscriber, so every `warn!` the counters emit + // is discarded -- and the report below used to claim the occurrences were + // "logged at WARN", which was false. A whole-chain run found one SWAPN and + // could not say which block it was in. + let _ = tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("warn")), + ) + .with_writer(std::io::stderr) + .try_init(); let a: Vec = std::env::args().collect(); let flag = |k: &str| a.iter().position(|x| x == k).and_then(|i| a.get(i + 1)).cloned(); if a.len() < 3 { @@ -471,10 +591,49 @@ fn main() -> anyhow::Result<()> { rustock_execution::supply::set_per_transaction(false); rustock_execution::supply::set_per_block(false); + // This is the measurement run, so recording is on. A node leaves both off + // and carries only the call sites. + rustock_execution::legacy_census::enable(); + rustock_core::vm_extremes::enable(); + let done: HashSet = std::fs::read_to_string(&state_path) .map(|s| s.lines().map(|l| l.trim().to_string()).filter(|l| !l.is_empty()).collect()) .unwrap_or_default(); + // Resume: reload the counters a previous run of this state file banked, + // and keep appending to the same repair list. A fresh run (empty state) + // starts both over. + let counters_path = sidecar(&state_path, "counters"); + let stop_path = sidecar(&state_path, "stop"); + // Named after the state file, not merely beside it. Deriving this from the + // parent directory alone meant every run on this machine shared one + // `segment-gaps.txt` whatever `--state` said -- so a second run with a + // fresh state file would truncate the first run's repair list. On + // 2026-11-23 that came within one condition of destroying an 18-hour, + // 510,219-row list; it survived only because the state file happened to be + // pre-seeded, which is luck, not design. + let gaps_path = sidecar(&state_path, "segment-gaps.txt"); + if done.is_empty() { + let _ = std::fs::remove_file(&counters_path); + let _ = std::fs::write( + &gaps_path, + "# block\tsegment\tnode-key -- reads a segment could not serve\n", + ); + } else { + let (census_ok, ext_ok) = load_counters(&counters_path); + println!( + "resuming: {} segment(s) already done; counters {}, high-water marks {}", + done.len(), + if census_ok { "reloaded" } else { "NOT reloaded -- totals below cover this run only" }, + if ext_ok { "reloaded" } else { "NOT reloaded" }, + ); + } + let _ = std::fs::remove_file(&stop_path); + println!( + "to stop cleanly at the next segment boundary: touch {}", + stop_path.display() + ); + let all = discover(&segroot, base.is_some())?; let pending: Vec = all.iter().filter(|s| !done.contains(&s.name)).cloned().collect(); let total_blocks: u64 = pending.iter().map(|s| s.blocks()).sum(); @@ -525,6 +684,8 @@ fn main() -> anyhow::Result<()> { std::fs::OpenOptions::new().create(true).append(true).open(&state_path)?, )); let stop = Arc::new(AtomicBool::new(false)); + // A requested stop is not a failure, and the exit code must say so. + let asked_to_stop = Arc::new(AtomicBool::new(false)); let blocks_done = Arc::new(AtomicU64::new(0)); let peak_rss = Arc::new(AtomicU64::new(0)); let from_full = Arc::new(AtomicU64::new(0)); @@ -581,11 +742,31 @@ fn main() -> anyhow::Result<()> { let (fb, from_full, absent, gaps) = (fallback_dir.clone(), from_full.clone(), absent.clone(), gaps.clone()); let bl = base.clone(); + let (gaps_path, counters_path, stop_path, asked_to_stop) = ( + gaps_path.clone(), + counters_path.clone(), + stop_path.clone(), + asked_to_stop.clone(), + ); scope.spawn(move || { loop { if stop.load(Ordering::Relaxed) { return; } + // An external, graceful stop: finish nothing new, keep + // everything already banked. The in-flight segment on the + // other worker still completes and is recorded. + if stop_path.exists() { + println!( + "[t{id}] stop requested -- not starting another segment. \ + Progress is banked; resume with the same --state." + ); + asked_to_stop.store(true, Ordering::Relaxed); + stop.store(true, Ordering::Relaxed); + let (_, cv) = &*sched; + cv.notify_all(); + return; + } let seg = { let (m, cv) = &*sched; let mut g = m.lock().unwrap(); @@ -632,9 +813,19 @@ fn main() -> anyhow::Result<()> { bd as f64 / total_blocks as f64 * 100.0, el / 60.0 ); + // Bank the findings BEFORE the segment is marked + // done: if this is interrupted between the two, the + // segment is replayed again and its rows re-appended, + // which is wasteful but correct. The other order + // would mark a segment done whose gaps were lost. + let wrote = flush_gaps(&gaps, &gaps_path); + save_counters(&counters_path); let mut f = state.lock().unwrap(); let _ = writeln!(f, "{}", seg.name); let _ = f.flush(); + if wrote > 0 { + println!("[t{id}] banked {wrote} gap row(s) for repair"); + } } Err(e) => { let msg = format!("{e:#}"); @@ -665,39 +856,43 @@ fn main() -> anyhow::Result<()> { peak_rss.load(Ordering::Relaxed) ); if fallback_dir.is_some() { - let g = gaps.lock().unwrap(); + // Whatever the last segments left; everything earlier was appended as + // it was found, so this is a remainder rather than the whole list. + let tail = flush_gaps(&gaps, &gaps_path); + save_counters(&counters_path); + let rows = std::fs::read_to_string(&gaps_path) + .map(|t| t.lines().filter(|l| !l.starts_with('#')).count()) + .unwrap_or(0); println!( - "segment gaps: {} reads served by the fallback, {} absent in both, {} distinct keys recorded", + "segment gaps: {} reads served by the fallback, {} absent in both; \ + {rows} row(s) in the repair list ({tail} appended just now)", from_full.load(Ordering::Relaxed), absent.load(Ordering::Relaxed), - g.len() ); - // Beside the state file, not at a path baked in from the machine this - // was written on. It used to be the latter, inside an `if let Ok`, so - // anywhere else it produced no repair list and said nothing -- the - // failure mode this tool exists to complain about. - let gaps_path = std::path::Path::new(&state_path) - .parent() - .unwrap_or_else(|| std::path::Path::new(".")) - .join("segment-gaps.txt"); - match std::fs::File::create(&gaps_path) { - Ok(mut f) => { - let _ = writeln!(f, "# block\tsegment\tnode-key -- reads a segment could not serve"); - for (b, seg, k) in g.iter() { - let _ = writeln!(f, "{b}\t{seg}\t{}", alloy_primitives::hex::encode(k)); - } - println!("gap keys written to {} (the repair list)", gaps_path.display()); - } - Err(e) => { - println!( - "WARNING: could not write the repair list to {}: {e}. The {} gap(s) above \ - are the only record.", - gaps_path.display(), - g.len() - ); - } + println!("gap keys written to {} (the repair list)", gaps_path.display()); + // The list is now appended per segment, so it is complete for every + // segment this run finished -- including when the run is interrupted. + // The old cap could silently drop 90% of it; it survives only as a + // guard against a single segment producing an absurd number of rows. + if rows >= GAP_KEY_LIMIT { + println!( + "WARNING: {rows} rows is at or past the {GAP_KEY_LIMIT} guard. Check that \ + the list was not curtailed before repairing from it." + ); } } + + if asked_to_stop.load(Ordering::Relaxed) { + println!( + "\nSTOPPED ON REQUEST. Everything finished is banked: segments in {}, \ + counters in {}, gap rows in {}.\nResume by re-running the same command -- \ + finished segments are skipped and the counters are reloaded.", + state_path, + counters_path.display(), + gaps_path.display() + ); + std::process::exit(2); + } if stop.load(Ordering::Relaxed) { println!("STOPPED on a failure -- see above"); std::process::exit(1); @@ -764,21 +959,58 @@ fn report_rsk_opcodes(done: u64, planned: u64) { // 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:"); + println!( + "legacy branches taken in this run{}:", + if rustock_execution::legacy_census::is_enabled() { + "" + } else { + " -- RECORDING WAS OFF, so every figure below is zero for that reason" + } + ); for (rule, what, window, hits) in &census { println!(" {rule:<8} {hits:>10} {what} [{window}]"); } + + // Maxima rather than counts, so they are reported apart from the census + // and read differently: a zero here means nothing was observed at all, + // where a zero above means a branch was never taken. + println!("\nhigh-water marks over this run:"); + for (what, value, block) in rustock_core::vm_extremes::extremes() { + if value == 0 { + println!(" {what:<34} {value:>12} (nothing observed)"); + } else { + println!(" {what:<34} {value:>12} last reached at #{block}"); + } + } // 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. + // Two of them now. Reporting them by name matters: "the campaign failed" + // sends a reader looking at the whole table, where "EVM-023a reported 0" + // names one counter and one block to check. + let controls = rustock_execution::legacy_census::positive_controls(); + for (rule, hits) in controls { + let window = match rule { + "BR-086" => "#4,976,300..#5,468,000", + "EVM-023a" => "#1..#3,396 (mainnet #3,307 must fire it)", + _ => "its window", + }; + if hits > 0 { + println!(" positive control {rule}: {hits} -- fired."); + } else { + println!( + " POSITIVE CONTROL {rule} DID NOT FIRE. Either this run did not cover \ + {window}, or the counter is not wired to the branch it names." + ); + } + } if rustock_execution::legacy_census::positive_control_fired() { - println!(" positive control fired: the counters are live, so the zeros above mean something."); + println!(" both controls 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." + " AT LEAST ONE POSITIVE CONTROL DID NOT FIRE -- see above. Until that is \ + resolved, treat every zero in this table as unproven, not as a clean window." ); } From ed5f493383c8eb87c73223215753b79ae26cbbbc Mon Sep 17 00:00:00 2001 From: Sergio Demian Lerner Date: Mon, 23 Nov 2026 16:28:17 +0000 Subject: [PATCH 5/9] Two read-only tools: an account's balance, and a contract's code account_at reports one account's nonce and balance at a chosen block from a single trie lookup, and reports an absent account as absent rather than as a zero balance. The two are different facts and on this chain the distinction carries weight: a precompile address exists from an activation onward whatever its balance, and an empty account is kept rather than pruned. contract_code answers the question every measurement raises next. When a high-water mark, a census hit or a divergence points at an address, the state tools say whether it exists and what it holds, and none of them say what it is. This prints the code, the instruction count, RSK's 0xFC header if present, and the PUSH4 constants from a linear decode that honours PUSH immediates -- so an octet inside a push is never read as an opcode, the discipline opcode_census uses and the reason a naive byte scan over-reports. It also takes --sig 'token0()' and prints that signature's selector, which is the point: a selector list identifies a contract only if the names behind it are computed rather than recalled. That is what turned the 413 KB memory high-water mark from a guess into an identification -- 29 of 33 PUSH4 constants in that contract compute to the exact Uniswap V3 Pool ABI. Co-Authored-By: Claude Opus 5 --- crates/cli/examples/account_at.rs | 139 +++++++++++++++++++++ crates/cli/examples/contract_code.rs | 178 +++++++++++++++++++++++++++ 2 files changed, 317 insertions(+) create mode 100644 crates/cli/examples/account_at.rs create mode 100644 crates/cli/examples/contract_code.rs diff --git a/crates/cli/examples/account_at.rs b/crates/cli/examples/account_at.rs new file mode 100644 index 00000000..39779917 --- /dev/null +++ b/crates/cli/examples/account_at.rs @@ -0,0 +1,139 @@ +//! An account's nonce and balance, as the trie holds them at a chosen block. +//! +//! One lookup, no walk: a unitrie account key is derived from the address, so +//! the state root plus the address is enough. Nothing here executes anything. +//! +//! ```text +//! account_at <0xaddress>… +//! [--block N] [--engine flatdb|rocksdb] +//! ``` +//! +//! `--block` defaults to the node's **executed** head, which is the state a +//! balance ordinarily means; pass a height for a historical one, which needs a +//! store that still holds that state (`archive_bound` says how high an archive +//! reaches, and a garbage-collected store answers only above its watermark -- +//! `segbuild_status` prints that). +//! +//! `--engine` defaults to `flatdb`, which is what the mainnet node runs; the +//! archive is `rocksdb`. Passing the wrong one fails at the open rather than +//! quietly answering from nothing. +//! +//! An absent account is reported as absent rather than as a zero balance. The +//! two are different facts, and on this chain the distinction carries weight: +//! a precompile address exists as an account from an activation onward whatever +//! its balance, and an empty account is kept rather than pruned (`BR-057`). +//! +//! Read-only, and safe to run against a live node. + +use alloy_primitives::U256; +use anyhow::{Context, Result}; +use rustock_storage::epoch_store::{EpochConfig, EpochTrieStore}; +use rustock_storage::BlockStore; +use rustock_trie::{account_key_from_bytes, AccountState, TrieKeySlice, TrieNode, TrieStore}; +use std::sync::Arc; + +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()) +} + +/// Ten-to-the-eighteenth, so a balance reads as RBTC as well as in weis. +fn as_rbtc(wei: U256) -> String { + let unit = U256::from(10u64).pow(U256::from(18)); + let whole = wei / unit; + let frac = wei % unit; + // Eighteen places, trimmed, so a dust balance is not rounded to nothing. + let frac = format!("{:018}", frac).trim_end_matches('0').to_string(); + if frac.is_empty() { + format!("{whole}") + } else { + format!("{whole}.{frac}") + } +} + +fn main() -> Result<()> { + let positional: Vec = + std::env::args().skip(1).take_while(|a| !a.starts_with("--")).collect(); + if positional.len() < 3 { + eprintln!( + "usage: account_at <0xaddress>... \ + [--block N] [--engine flatdb|rocksdb]" + ); + std::process::exit(64); + } + let (data_dir, trie_dir) = (positional[0].clone(), positional[1].clone()); + let engine = flag("engine").unwrap_or_else(|| "flatdb".into()); + + let blocks = BlockStore::open_read_only(&data_dir) + .with_context(|| format!("opening {data_dir} read-only"))?; + + // The executed head, not the best header: only executed blocks have state. + let (at, root) = match flag("block").and_then(|v| v.parse::().ok()) { + Some(number) => { + let hash = blocks + .canonical_hash(number)? + .with_context(|| format!("no canonical block at #{number}"))?; + let header = + blocks.header(hash)?.with_context(|| format!("no header at #{number}"))?; + (number, header.state_root) + } + None => { + let (hash, root) = blocks.exec_head()?.context("this node has executed nothing")?; + let number = blocks.header(hash)?.map(|h| h.number).unwrap_or(0); + (number, root) + } + }; + + let engine_parsed = rustock_storage::TrieEngine::parse(&engine)?; + let config = EpochConfig::default(); + let expected = rustock_storage::epoch_backend::keys_for_rotation(config.rotate_bytes); + let store: Arc = Arc::new( + EpochTrieStore::open_read_only_with( + std::path::Path::new(&trie_dir), + config, + engine_parsed.factory(expected), + ) + .with_context(|| format!("opening {trie_dir} read-only as {engine}"))?, + ); + + let root_bytes = store.get(root.as_slice()).with_context(|| { + format!( + "the state root {root:?} of #{at} is not in {trie_dir}. A garbage-collected \ + store answers only above its collection watermark, and an archive only up to \ + the height it was built to." + ) + })?; + let node = TrieNode::from_message(&root_bytes, store.as_ref()); + + println!("state at #{at} root {root:?}"); + println!("store {trie_dir} ({engine})"); + println!(); + + for raw in &positional[2..] { + let hex = raw.trim().trim_start_matches("0x"); + let bytes = alloy_primitives::hex::decode(hex) + .with_context(|| format!("{raw} is not a hex address"))?; + anyhow::ensure!( + bytes.len() == 20 || bytes.len() == 1, + "{raw} is {} octets; an address is 20 (or 1, for REMASC)", + bytes.len() + ); + let key = account_key_from_bytes(&bytes); + match node.get(&TrieKeySlice::from_key(&key), store.as_ref()) { + Some(encoded) => { + let account = AccountState::decode(&encoded) + .with_context(|| format!("decoding the account state of 0x{hex}"))?; + println!("0x{hex}"); + println!(" nonce {}", account.nonce); + println!(" balance {} wei", account.balance); + println!(" {} RBTC", as_rbtc(account.balance)); + if account.state_flags != 0 { + println!(" flags 0x{:08x}", account.state_flags); + } + } + // Absent is not zero. See the module note. + None => println!("0x{hex}\n ABSENT -- no account at this address in this state"), + } + } + Ok(()) +} diff --git a/crates/cli/examples/contract_code.rs b/crates/cli/examples/contract_code.rs new file mode 100644 index 00000000..b9edf8f4 --- /dev/null +++ b/crates/cli/examples/contract_code.rs @@ -0,0 +1,178 @@ +//! A contract's bytecode, and the function selectors it dispatches on. +//! +//! The state tools answer whether an account exists and what it holds; +//! none of them answer *what it is*. When a measurement points at an address -- +//! a high-water mark, a census hit, a divergence -- the next question is always +//! what the code does, and that needs the code. +//! +//! ```text +//! contract_code <0xaddress>... +//! [--block N] [--engine flatdb|rocksdb] [--plain] [--hex] +//! ``` +//! +//! `--plain` opens the trie directory as a single rustock-format store rather +//! than an epoch store, which is what an archival trie and a segbuild segment +//! are. Without it the directory is opened as an epoch store, which is what the +//! node keeps. +//! +//! # What the selector list is, and is not +//! +//! Solidity dispatches by comparing the first four octets of calldata against +//! `PUSH4` constants, so the `PUSH4` immediates in a contract's code are its +//! likely entry points. The list is a strong hint and not a proof: a `PUSH4` +//! can be any constant, a dispatcher can be written without one, and a proxy +//! has none of the selectors it actually serves. +//! +//! The decode is linear and honours `PUSH` immediates, so an octet *inside* a +//! push is never read as an opcode -- the same discipline `opcode_census` uses, +//! and the reason a naive byte scan over-reports. It also skips RSK's `0xFC` +//! code header, which moves the offset every instruction decodes from. +//! +//! Read-only, and safe to run beside a live node. + +use anyhow::{Context, Result}; +use rustock_trie::{code_key_from_bytes, TrieKeySlice, TrieNode, TrieStore}; +use std::sync::Arc; + +fn flag(name: &str) -> Option { + let a: Vec = std::env::args().collect(); + a.windows(2).find(|w| w[0] == format!("--{name}")).map(|w| w[1].clone()) +} +fn has(name: &str) -> bool { + std::env::args().any(|a| a == format!("--{name}")) +} + +/// `(selectors, instructions)` from a linear decode that honours `PUSH`. +fn decode(code: &[u8]) -> (Vec<[u8; 4]>, usize) { + // RSK's code header: `0xFC`, then three octets, the third giving how many + // more follow. Execution and jumpdest analysis both start after it. + let mut i = if code.first() == Some(&0xfc) && code.len() >= 4 { + 4 + code[3] as usize + } else { + 0 + }; + let (mut sels, mut n) = (Vec::new(), 0usize); + while i < code.len() { + let op = code[i]; + n += 1; + if (0x60..=0x7f).contains(&op) { + let width = (op - 0x5f) as usize; + if op == 0x63 && i + 4 < code.len() { + sels.push([code[i + 1], code[i + 2], code[i + 3], code[i + 4]]); + } + i += 1 + width; + } else { + i += 1; + } + } + sels.sort_unstable(); + sels.dedup(); + (sels, n) +} + +/// `--sig "token0()"` prints that signature's selector and exits. +/// +/// The point is to turn a guess into a check. A selector list identifies a +/// contract only if the names behind it are verified, and recalling that +/// `0x0dfe1681` is `token0()` is exactly the kind of claim that should be +/// computed rather than remembered. +fn selectors_from_signatures() -> bool { + let args: Vec = std::env::args().collect(); + let sigs: Vec<&String> = args + .windows(2) + .filter(|w| w[0] == "--sig") + .map(|w| &w[1]) + .collect(); + if sigs.is_empty() { + return false; + } + for sig in sigs { + let h = alloy_primitives::keccak256(sig.as_bytes()); + println!("0x{} {sig}", alloy_primitives::hex::encode(&h[0..4])); + } + true +} + +fn main() -> Result<()> { + if selectors_from_signatures() { + return Ok(()); + } + let pos: Vec = + std::env::args().skip(1).take_while(|a| !a.starts_with("--")).collect(); + if pos.len() < 3 { + eprintln!( + "usage: contract_code <0xaddress>... \ + [--block N] [--engine flatdb|rocksdb] [--plain] [--hex]" + ); + std::process::exit(64); + } + let (data_dir, trie_dir) = (pos[0].clone(), pos[1].clone()); + + let blocks = rustock_storage::BlockStore::open_read_only(&data_dir) + .with_context(|| format!("opening {data_dir} read-only"))?; + let (at, root) = match flag("block").and_then(|v| v.parse::().ok()) { + Some(n) => { + let h = blocks.canonical_hash(n)?.with_context(|| format!("no block #{n}"))?; + (n, blocks.header(h)?.with_context(|| format!("no header #{n}"))?.state_root) + } + None => { + let (h, r) = blocks.exec_head()?.context("this node has executed nothing")?; + (blocks.header(h)?.map(|x| x.number).unwrap_or(0), r) + } + }; + + let store: Arc = if has("plain") { + Arc::new( + rustock_storage::RocksDbTrieStore::open_read_only(&trie_dir) + .with_context(|| format!("opening {trie_dir} as a plain rustock store"))?, + ) + } else { + let engine = flag("engine").unwrap_or_else(|| "flatdb".into()); + let cfg = rustock_storage::epoch_store::EpochConfig::default(); + let expected = rustock_storage::epoch_backend::keys_for_rotation(cfg.rotate_bytes); + Arc::new( + rustock_storage::epoch_store::EpochTrieStore::open_read_only_with( + std::path::Path::new(&trie_dir), + cfg, + rustock_storage::TrieEngine::parse(&engine)?.factory(expected), + ) + .with_context(|| format!("opening {trie_dir} as an epoch store ({engine})"))?, + ) + }; + + let root_bytes = store.get(root.as_slice()).with_context(|| { + format!("the state root of #{at} is not in {trie_dir}; a collected store answers only \ + above its watermark, and an archive only to the height it was built to") + })?; + let node = TrieNode::from_message(&root_bytes, store.as_ref()); + println!("state at #{at}\n"); + + for raw in &pos[2..] { + let hex = raw.trim().trim_start_matches("0x"); + let bytes = alloy_primitives::hex::decode(hex) + .with_context(|| format!("{raw} is not a hex address"))?; + let key = code_key_from_bytes(&bytes); + match node.get(&TrieKeySlice::from_key(&key), store.as_ref()) { + None => println!("0x{hex}\n NO CODE -- an EOA, or a contract with none\n"), + Some(code) => { + let (sels, insns) = decode(&code); + println!("0x{hex}"); + println!(" code {} octets, {insns} instructions", code.len()); + if code.first() == Some(&0xfc) { + println!(" header RSK 0xFC code header present"); + } + println!(" PUSH4 constants ({}), likely selectors:", sels.len()); + for chunk in sels.chunks(8) { + let line: Vec = + chunk.iter().map(|s| format!("0x{}", alloy_primitives::hex::encode(s))).collect(); + println!(" {}", line.join(" ")); + } + if has("hex") { + println!(" {}", alloy_primitives::hex::encode(&code)); + } + println!(); + } + } + } + Ok(()) +} From 6da555573384f093faa5fb0c1c87a258dc7e2efd Mon Sep 17 00:00:00 2001 From: Sergio Demian Lerner Date: Mon, 23 Nov 2026 16:28:17 +0000 Subject: [PATCH 6/9] Settle EVM-045: the one SWAPN this chain executed, and that removing it changes nothing The whole-chain run found exactly one SWAPN in 9,429,718 blocks, at mainnet #996,053. It is not a contract using the opcode. The transaction is a contract creation whose init code is 68 octets of transfer(address,uint256) calldata -- somebody sent an ERC-20 transfer with an empty `to`, so the node executed the calldata as init code. Its first octet is 0xa9, which below iris300 is SWAPN, and the octet after it is the operand: SWAPN 5 on an empty stack. The creation fails and the address holds no account to this day. So the window is occupied, and a count alone would have ended the matter there. Replaying the block both ways says otherwise. With SWAPN installed, 0xa9 underflows -- an exceptional halt consuming all gas. With it replaced by the invalid-opcode handler, 0xa9 is OpcodeNotFound -- also an exceptional halt consuming all gas, and the EVM records which exception nowhere. Identical state root, gasUsed, paid fees and receipts, both matching the recorded root. EVM-045 is therefore removable on mainnet despite firing, which no count could have shown. The test seeds from the pre-RSKIP126 baseline rather than the parent header, because headers below #1,591,000 declare Orchid-format roots that name no node in a Unitrie store. Run it once as it stands and once with SWAPN replaced in rsk_instructions::install: one instruction changes and nothing else. Moving iris300 instead would also move RSKIP-218's REMASC recipient and RSKIP-174's created-at-a-funded-address rule, either of which would shift the root for reasons unrelated to SWAPN. The report records the run's results in full: 28 counters, thirteen windows this chain never entered, fifteen it occupies, the three high-water marks, four zeros that prove less than they look, and one figure not yet reconciled. Co-Authored-By: Claude Opus 5 --- crates/execution/tests/swapn_at_996053.rs | 106 ++++++++++ docs/retroactive-guard-measurements.md | 234 ++++++++++++++++++---- 2 files changed, 298 insertions(+), 42 deletions(-) create mode 100644 crates/execution/tests/swapn_at_996053.rs diff --git a/crates/execution/tests/swapn_at_996053.rs b/crates/execution/tests/swapn_at_996053.rs new file mode 100644 index 00000000..5a017191 --- /dev/null +++ b/crates/execution/tests/swapn_at_996053.rs @@ -0,0 +1,106 @@ +//! Does removing `SWAPN` change mainnet block #996,053? +//! +//! The whole-chain run of 2026-11-22 found exactly one `SWAPN` execution in +//! 9,429,718 blocks, at #996,053, transaction 0, in contract +//! `0x56bF637ee636D8ebDE45a046c45DEac6eF67a019`. The transaction is a contract +//! **creation** whose init code is 68 octets of `transfer(address,uint256)` +//! calldata -- someone sent an ERC-20 transfer with an empty `to`. Its first +//! octet is `0xa9`, which below iris300 is `SWAPN`, and the octet after it is +//! its operand. `SWAPN 5` on an empty stack underflows, the creation fails, +//! and the address holds no account to this day. +//! +//! So `EVM-045`'s window is occupied -- but perhaps only nominally. With the +//! opcode present, `0xa9` underflows: an exceptional halt consuming all gas. +//! With it gone, `0xa9` is `OpcodeNotFound`: also an exceptional halt consuming +//! all gas. If both leave the same state, RSKIP-191 removed nothing this chain +//! depended on, and the count of one is not an obstacle to retiring the branch. +//! +//! **That is a claim about consensus, so it is measured here rather than argued.** +//! This test replays the real block against the real pre-state and asserts the +//! computed root matches the header. Run it once as it stands, then once with +//! `SWAPN` replaced by the invalid-opcode handler in +//! `rsk_instructions::install`, and compare. One instruction changes between +//! the two runs and nothing else -- moving `iris300` instead would also move +//! RSKIP-218's REMASC recipient and RSKIP-174's created-at-a-funded-address +//! rule, either of which would shift the root for reasons unrelated to `SWAPN`. +//! +//! ```text +//! RUSTOCK_BLOCKS_DB=/var/lib/rustock \ +//! RUSTOCK_ARCHIVE_TRIE= \ +//! cargo test -p rustock-execution --test swapn_at_996053 -- --ignored --nocapture +//! ``` + +use std::sync::Arc; + +const BLOCK: u64 = 996_053; + +/// The pre-RSKIP126 root baseline: one Unitrie root per block for 1..=1,591,000. +/// +/// Read directly rather than through the CLI's `support::baseline`, which is an +/// example-local module a crate test cannot reach. Layout, little-endian: +/// magic `RSKBASE1` (8), schema (4), reserved (4), first (8), last (8), +/// anchor (32), then roots at a fixed 32-octet stride. +fn baseline_root(path: &str, block: u64) -> Option<[u8; 32]> { + let bytes = std::fs::read(path).ok()?; + if bytes.len() < 64 || &bytes[0..8] != b"RSKBASE1" { + return None; + } + let first = u64::from_le_bytes(bytes[16..24].try_into().ok()?); + let last = u64::from_le_bytes(bytes[24..32].try_into().ok()?); + if block < first || block > last { + return None; + } + let at = 64 + (block - first) as usize * 32; + bytes.get(at..at + 32)?.try_into().ok() +} + +#[test] +#[ignore = "requires RUSTOCK_BLOCKS_DB and RUSTOCK_ARCHIVE_TRIE"] +fn block_996053_replays_and_reports_its_root() { + let (Ok(db), Ok(archive), Ok(baseline)) = ( + std::env::var("RUSTOCK_BLOCKS_DB"), + std::env::var("RUSTOCK_ARCHIVE_TRIE"), + std::env::var("RUSTOCK_BASELINE"), + ) else { + eprintln!("RUSTOCK_BLOCKS_DB / RUSTOCK_ARCHIVE_TRIE / RUSTOCK_BASELINE not set; skipping"); + return; + }; + + let blocks = Arc::new(rustock_storage::BlockStore::open_read_only(&db).expect("block store")); + let trie: Arc = + Arc::new(rustock_storage::RocksDbTrieStore::open_read_only(&archive).expect("archive")); + + let hash = blocks.canonical_hash(BLOCK).unwrap().expect("canonical hash"); + let header = blocks.header(hash).unwrap().expect("header"); + let (transactions, ommers) = blocks.body(hash).unwrap().expect("body"); + // #996,053 is below #1,591,000, so BOTH the pre-state and the expected root + // come from the baseline: the headers of that era declare Orchid-format + // roots, which name no node in a Unitrie store and cannot be compared + // against a computed Unitrie root. + let seed = baseline_root(&baseline, BLOCK - 1).expect("no baseline root for the parent"); + let expected = baseline_root(&baseline, BLOCK).expect("no baseline root for the block"); + let pre_bytes = trie.get(&seed).expect("pre-state root absent from the archive"); + let pre = rustock_trie::TrieNode::from_message(&pre_bytes, trie.as_ref()); + let processor = rustock_execution::BlockProcessor::new( + rustock_execution::RskHardforkConfig::mainnet(), + blocks.clone(), + ); + let block = rustock_core::Block { header, transactions, ommers }; + let out = processor + .execute_block(&block, &pre, trie.clone()) + .expect("execution failed outright"); + + println!("block #{BLOCK}"); + println!(" baseline root 0x{}", expected.iter().map(|b| format!("{b:02x}")).collect::()); + println!(" computed root {:?}", out.state_root_hash); + println!(" block gas_used {} paid_fees {}", out.gas_used, out.paid_fees); + for (i, r) in out.receipts.iter().enumerate() { + println!(" receipt {i}: {r:?}"); + } + assert_eq!( + out.state_root_hash.as_slice(), + expected.as_slice(), + "computed root differs from the baseline -- with SWAPN removed this is the \ + finding; with SWAPN present it means the fixture is wrong" + ); +} diff --git a/docs/retroactive-guard-measurements.md b/docs/retroactive-guard-measurements.md index 5703aeab..84a6db74 100644 --- a/docs/retroactive-guard-measurements.md +++ b/docs/retroactive-guard-measurements.md @@ -7,8 +7,13 @@ 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. +and how to widen it. + +As of 2026-11-23 the whole chain has been re-executed with every counter live: +**9,429,718 blocks, 106 segments, 17.4 hours**, both positive controls firing. +Twenty-eight branches were counted, thirteen of them never taken. What remains +unrun is named as such -- `BR-134`, which needs a receipts scan rather than a +replay, and every result's testnet half. ## The rule that decides what needs measuring @@ -117,6 +122,67 @@ dead regions after a terminator until the next `JUMPDEST`, and honours RSK's **It also found the code header was never used** by any contract alive at that height. +**And the replay disagreed with it, which is the useful part.** The whole-chain +run found `SWAPN` **executed once**, in a chain where the census found it +reachable in nothing. Both results are correct, and the gap between them is the +census's scope: it decodes the contracts **alive at one height**, so it cannot +see a contract that ran and was destroyed before that height, and it cannot see +constructor code, which executes and is never stored. + +**Located, and then settled.** A second run carrying the block number and the +executing contract put the occurrence at mainnet **#996,053**, transaction 0, +contract `0x56bF637ee636D8ebDE45a046c45DEac6eF67a019`. + +The transaction is a contract **creation** whose init code is 68 octets of +`transfer(address,uint256)` calldata: + +```text +a9059cbb 000…c3439c113bf4e8da22f5bc6093a0dd7b95de06a4 000…1000000000000000000 +``` + +Someone sent an ERC-20 transfer with an empty `to`, so the node treated the +calldata as init code and executed it. Its first octet is `0xa9`, which below +iris300 is `SWAPN`, and the octet after it is the operand: `SWAPN 5` on an empty +stack. The creation fails, and the address holds no account to this day. Nobody +ever used the opcode deliberately. + +**And removing it changes nothing.** With `SWAPN` present, `0xa9` underflows -- +an exceptional halt consuming all gas. With it replaced by the invalid-opcode +handler, `0xa9` is `OpcodeNotFound` -- also an exceptional halt consuming all +gas. Replaying the real block against the real pre-state both ways gives +identical results: + +| | `SWAPN` enabled | `SWAPN` disabled | +|---|---|---| +| state root | `0x11686e23…91664e` | `0x11686e23…91664e` | +| block gas used | 6,800,000 | 6,800,000 | +| paid fees | 402,832,000,000,000 | 402,832,000,000,000 | +| receipt 0 | gas 6,800,000, status false | gas 6,800,000, status false | +| receipt 1 (REMASC) | gas 0, status true | gas 0, status true | + +Both roots match the baseline. **So `EVM-045` is removable on mainnet despite +its count being non-zero** -- the window is occupied, but only nominally, and no +count alone could have shown that. + +The fixture is `crates/execution/tests/swapn_at_996053.rs`, which replays the +block from the baseline seed and the archival trie. Run it once as it stands and +once with `SWAPN` replaced by `invalid_opcode` in `rsk_instructions::install`; +one instruction changes between the runs and nothing else. Moving `iris300` +instead would also move RSKIP-218's REMASC recipient and RSKIP-174's +created-at-a-funded-address rule, either of which would shift the root for +reasons unrelated to `SWAPN`. + +**Still open:** testnet. Its activation ladder differs and no equivalent replay +has been run, so this closes the mainnet half only. `DUPN` and `TXINDEX` never +executed on mainnet at all. + +So the census's zero was never the claim the campaign needed. It is a sound +*necessary condition* over surviving code and nothing more -- which is how it was +written up here, and it is still the cheapest way to rule a rule out. But a +negative from it does not close a window; only the replay does. `EVM-041a`'s +shift-opcode half, which this report hands to the census for want of a branch to +count, inherits exactly that limitation and should be read with it. + ```sh cargo run --release -p rustock-cli --example opcode_census -- \ /var/lib/rustock /mnt/import/rustock-trie --block 3614799 --threads 3 @@ -161,55 +227,139 @@ 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 +## What the whole-chain run measured -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. +Run over the whole chain on 2026-11-22/23: **9,429,718 blocks, 106 segments, +17.4 hours** at two workers, with an archival trie behind the segment set as a +fallback. Every block's state root was verified, and every segment with it. -| 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 | +The counters cost one relaxed atomic add on a branch already behind a height +test, so this one replay measured every row below at once. -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`). +### Read the controls first -```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 -``` +| Control | Count | | +|---|---|---| +| `BR-086` | **55,834** | fired | +| `EVM-023a` | **4,875** | fired | -**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. +Both fired, so the zeros below are measurements rather than silence. A counter +that cannot fire reports zero exactly as convincingly as a branch nothing took, +which is why the tool prints this verdict before the table and refuses to call +the campaign validated without it. + +### Windows this chain never entered -### Two positive controls, and why the report leads with them +| Rule | Branch | Window (mainnet) | +|---|---|---| +| `BR-030` | an internal call to the bridge ends its caller | below #729,000 | +| `EVM-041a` | `STATICCALL` reached before RSKIP-91 made it an opcode | below #729,000 | +| `EVM-062` | a call's stipend sum overflowed a signed 64-bit integer | below #2,018,000 | +| `EVM-043` | `EXTCODEHASH` answered from the trie-existence marker | #2,392,700–#3,614,800 | +| `EVM-023` | a precompile's exception burned the calling frame's gas | below #3,614,800 | +| `BR-097` | a Bitcoin header refused for 12-octet chain-work overflow | BTC #849,138 to #6,549,300 | +| `EVM-046` | a dirty-high-bits address reached the account, not the precompile | all heights | +| `PC-042` | a block-header depth outside `0..32,767` | all heights | +| `PC-051` | `ECRECOVER` given a `v` word with information above octet 63 | all heights | +| `BV-110` | a gas limit of 2^63 or more, read as a negative signed long | all heights | +| `BV-125` | the uncle count's 32-bit product wrapped in the difficulty | all heights | +| `BV-173` | the uncle sum wrapped across the 32 newest headers | all heights | +| `BR-061` | a peg-out amount that did not fit a signed 64-bit long | all heights | -**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. +**Every narrowing guard reports zero except `BR-112`.** No overflow or +truncation has ever changed a value this chain accepted. That is the baseline +those counters now monitor against, and it is clean. -`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. +### Windows this chain occupies -Read that line before any of the zeros. +| Rule | Branch | Count | +|---|---|---| +| `EVM-100` | a precompile wrote its whole output past the declared region | **352,910** | +| `EVM-101` (case 2) | a call that ran nothing kept the caller's return-data buffer | **178,728** | +| `BR-015` | `receiveHeaders` public rather than federation-only | 84,315 | +| `BR-086` | funds-migration end age 172,800 rather than 10,585 | 55,834 | +| `EVM-024` | a privileged sender's bridge transaction executed free | 44,646 | +| `BR-136` | `addSignature`'s topic carried the federator's BTC key | 28,038 | +| `EVM-033` | a contract created at a funded address lost that balance | 4,874 | +| `EVM-023a` | a precompile transaction charged past its own gas limit | 4,875 | +| `EVM-034` | an internally created contract's nonce was 0, not 1 | 562 | +| `BR-011a` | a windowed bridge method invoked while it existed | 83 | +| `EVM-101` (case 3) | a refused `CREATE` kept a stale return-data buffer | 43 | +| `BR-125` | `commitFederation` handed over immediately, with no SVP | 13 | +| `BR-055` | a rejected, unrefundable peg-in marked processed | 4 | +| `BR-112` | a negative flyover code sign-extended across 256 bits | 3 | +| `EVM-101` (case 1) | a successful precompile call kept the caller's buffer | 11 | + +### The quantities a hit count would have lost + +- **RSK's own opcodes** (`EVM-045`): `DUPN` 0, **`SWAPN` 1**, `TXINDEX` 0. The + one occurrence is mainnet #996,053, and replaying that block with the opcode + removed gives an identical state root -- see `EVM-045` above. Occupied, but + removable. +- **The code header** (`EVM-032`): 15,066 contracts deployed, **none** carrying + the `0xFC` header. This answers the question the census could only narrow. +- **Seven-operand `STATICCALL`** (`EVM-041b`): 0 executed, 0 with a non-zero + value, over the whole #729,000–#1,052,700 window. +- **Empty deploys below RSKIP-453** (`EVM-037`): 0 over the maximum code size, + **172** unable to pay the code deposit; the largest code any of them returned + was 24,532 octets, 44 short of the limit. + +### High-water marks + +Maxima rather than counts, so a zero here means nothing was observed at all +rather than that a branch was never taken. + +| | Value | Block | +|---|---|---| +| Deepest CALL-family frame | **401** | #7,931,702 | +| Most EVM memory expanded | **422,944 octets** | #9,085,105 | +| Largest `RETURN` payload | **24,573 octets** | #6,714,553 | + +Two of the three sit on limits. 401 is one past RSKIP-150's call-depth cap of +400 — the mark is taken where the frame is *opened*, before the cap refuses it, +so it records the depth reached rather than the depth that survived. And 24,573 +is three octets under the 24,576 contract-size ceiling, so the largest `RETURN` +this chain ever carried is a maximum-size deployment. + +### Four zeros that prove less than they look + +Stated here rather than left for a reader to infer: + +- **`EVM-023` is known occupied on testnet**, at #808,484. Its mainnet zero says + nothing about the branch being dead; a testnet replay would settle it and none + has been run. +- **`BR-061` is unreachable on mainnet and testnet balances by construction** — + no balance approaches 2^63 satoshis. Its zero was never in doubt. The branch + *is* reachable on regtest, whose genesis funds accounts with 10^30 wei. +- **`EVM-041a` is half-measured.** `STATICCALL` below orchid is an explicit + invalid-opcode substitution and is counted. The shift opcodes and `CREATE2` + below wasabi100 come from the spec selection rather than from a branch, so + there is nothing at that site to count; they need the reachability census. +- **`BV-110`'s zero is expected.** A header carrying a gas limit of 2^63 or more + is invalid, so no canonical block holds one. A non-zero there would have been + a finding about the decoder, not about the chain. + +### One figure not yet reconciled + +`EVM-023a` reports **4,875** occurrences below #3,397, but both the +specification and the RSKIP-136 write-up describe mainnet #3,307 as *the* +occurrence, singular. 4,875 across 3,396 blocks is 1.4 per block, which is +plausible for early federation traffic but contradicts the written claim. The +control *fired*, which is all that was needed to validate the campaign, but the +figure should not be cited as evidence until the discrepancy is resolved. + +### Segment completeness, as a by-product + +The replay reads state through the segment set with an archival trie behind it, +and records every read a segment could not serve. Over the whole chain: +**510,219 such reads, none absent from both stores**, concentrated in a small +number of blocks that perform deep Bridge walks — a peg-in's confirmation count +or a pegout's UTXO selection. + +That list is the input to repairing the segments. An earlier run capped the +record at 50,000 keys and so retained 9.8% of it; the list is now appended per +finished segment, which both removes the cap in practice and makes it survive an +interrupted run. ## Instrumented separately: `BR-134` From 82e2dc66758b59bb1d378496f6785bbbc519ec21 Mon Sep 17 00:00:00 2001 From: Sergio Demian Lerner Date: Mon, 23 Nov 2026 16:28:50 +0000 Subject: [PATCH 7/9] Remove the stale copy of legacy_census.rs left behind by the move The move to rustock-core added the new path but did not record the old one's deletion, leaving two copies of the census registry in the tree. The stale one is declared by no `mod` statement so it compiled and did nothing, which is the problem: a registry that exists twice is a registry someone edits the wrong half of. Belongs in the move commit; it is separate only because nothing here is pushed yet and rewriting four commits to tidy one deletion is the worse trade. Co-Authored-By: Claude Opus 5 --- crates/execution/src/legacy_census.rs | 169 -------------------------- 1 file changed, 169 deletions(-) delete mode 100644 crates/execution/src/legacy_census.rs diff --git a/crates/execution/src/legacy_census.rs b/crates/execution/src/legacy_census.rs deleted file mode 100644 index c4c0d7eb..00000000 --- a/crates/execution/src/legacy_census.rs +++ /dev/null @@ -1,169 +0,0 @@ -//! 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()); - } - } -} From 9c9975b9b2b379077f32c22b91159e1f9f186ee8 Mon Sep 17 00:00:00 2001 From: Sergio Demian Lerner Date: Mon, 23 Nov 2026 17:23:21 +0000 Subject: [PATCH 8/9] Abort on a missing segment node instead of reporting it as an absence TrieStore::get answers Option, so a segbuild reader cannot tell a key that is genuinely absent from the state -- a legitimate answer the consensus rules branch on -- from a node this store never captured. Reading the second as the first is unsound and silent, and it is asymmetric: only code that reads state the builder never read can hit it, so it always looks like a regression in the newer code. That asymmetry made a replay of #374 look like a mainnet consensus divergence, and on 2026-11-22 it made segment 026-3792187-3815755 present as a STATE ROOT MISMATCH at #3,812,411 -- investigated for a day as a consensus bug before being isolated as one missing node. AbortOnMissingNode stops the run and names both explanations, saying plainly that this is NOT evidence of a consensus bug and that a passing run of older code is no control, because code that never performs the read is immune by construction. Verified on the real segment: replaying 026 with no fallback now aborts naming node ab12d849e9d1ea716caca53b211e88b4c45f4eb04d9a58ec9c6bdb0b502dd8d2, which is exactly the gap the whole-chain fallback run recorded independently at that block. Two unrelated mechanisms, the same node. No change to NodeRef::resolve, which has 46 non-test callers in consensus-path trie code. The guarantee does not need one: a trie walk reaches a store only through NodeRef::Hash(h), and a parent commits to its child's hash, so a node named by a hash exists in the real trie by construction. A genuine absence is NodeRef::Empty and never reaches the store at all. Scoped to the replay path and documented as such. It must not sit behind a deliberate presence probe -- snapshot.rs's `if store.get(h).is_none()` expects misses and handles them, and this would turn that expectation into an abort. Issue #398 also asked for negative-read markers in the segment format so a reader could tell the two apart. That is unnecessary, as above, and the cost would have been a format change invalidating every segment already built; the reasoning is recorded on the issue. Refs #398 Co-Authored-By: Claude Opus 5 --- crates/cli/examples/reexec_all.rs | 10 +- crates/storage/src/lib.rs | 1 + crates/storage/src/segment_reader.rs | 138 +++++++++++++++++++++++++++ 3 files changed, 148 insertions(+), 1 deletion(-) create mode 100644 crates/storage/src/segment_reader.rs diff --git a/crates/cli/examples/reexec_all.rs b/crates/cli/examples/reexec_all.rs index b27ba99f..9e0a9eb3 100644 --- a/crates/cli/examples/reexec_all.rs +++ b/crates/cli/examples/reexec_all.rs @@ -1098,7 +1098,15 @@ fn run_segment( with_fb = Some(w.clone()); w } - None => Arc::new(loaded), + // No fallback: every read must be served by the segment itself, so a + // miss is unambiguously a gap -- the caller asked for a node by its + // committed hash. Abort naming both explanations rather than answering + // `None`, which the trie walk would read as a genuine absence and turn + // into a STATE ROOT MISMATCH that looks like a consensus bug (#398). + None => Arc::new(rustock_storage::segment_reader::AbortOnMissingNode::new( + loaded, + seg.name.clone(), + )), }; // Where to start, and what state to start from. Three cases, and only the diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs index 7ca386e7..996aedd9 100644 --- a/crates/storage/src/lib.rs +++ b/crates/storage/src/lib.rs @@ -1,3 +1,4 @@ +pub mod segment_reader; pub mod trie_store; pub mod cached_trie_store; pub mod epoch_backend; diff --git a/crates/storage/src/segment_reader.rs b/crates/storage/src/segment_reader.rs new file mode 100644 index 00000000..eb996c1f --- /dev/null +++ b/crates/storage/src/segment_reader.rs @@ -0,0 +1,138 @@ +//! A segment-backed trie reader that refuses to confuse a gap with an absence. +//! +//! `TrieStore::get` answers `Option`, and a segbuild reader cannot tell these +//! apart from the answer alone: +//! +//! - the key is **genuinely absent from the state** -- a legitimate answer the +//! consensus rules branch on; +//! - the node is **absent from this store** -- the segment never captured it. +//! +//! Reading the second as the first is unsound, and silently so. It is also +//! *asymmetric*: only code that reads state the builder never read can hit it, +//! so it always looks like a regression in the newer code. That asymmetry is +//! what made a replay of #374 look like a mainnet consensus divergence +//! (`docs/trie-segments-design.md` 6.9d), and what made segment +//! `026-3792187-3815755` present as a `STATE ROOT MISMATCH` at #3,812,411 on +//! 2026-11-22 -- investigated for a day as a consensus bug before being +//! isolated as a missing node. +//! +//! # Why no marker in the segment is needed +//! +//! The distinction is already in the data. A trie walk reaches a store only +//! through `NodeRef::Hash(h)`, and a parent commits to its child's hash. So a +//! node named by a hash **exists in the real trie by construction**: if the +//! store does not have it, the store is incomplete. A genuine absence never +//! reaches the store at all -- it is `NodeRef::Empty`, decided in the parent. +//! +//! Issue #398 originally proposed recording negative reads in the segment +//! format to tell the two apart. That is unnecessary, and the cost would have +//! been a format change invalidating every segment already built. +//! +//! # Where this may and may not be used +//! +//! **Only on a replay path**, where every `get` is a committed reference -- a +//! node message, or a long value by its `value_hash`. It must never sit behind +//! a deliberate presence probe such as `snapshot.rs`'s +//! `if store.get(h).is_none()`, which expects misses and handles them; this +//! would turn that expectation into an abort. + +use rustock_trie::TrieStore; + +/// Wraps a segment store so a missing node stops the run instead of being +/// reported as an absence. +pub struct AbortOnMissingNode { + inner: S, + /// Named in the abort, because "a node is missing" is not actionable and + /// "a node is missing from segment 026-3792187-3815755" is. + segment: String, +} + +impl AbortOnMissingNode { + pub fn new(inner: S, segment: impl Into) -> Self { + Self { inner, segment: segment.into() } + } + + /// The abort text, separated so it can be asserted without aborting. + /// + /// It names **both** explanations deliberately. The intuitive reading of a + /// missing node is "the code under test is wrong", and that is the one + /// reading this message exists to prevent. + pub fn message(segment: &str, key: &[u8]) -> String { + format!( + "ABORT: node {hash} is not present in segment {segment}\n\ + \n\ + This is NOT evidence of a consensus bug in the code under test.\n\ + Two explanations, and they are not distinguishable from here:\n\ + \n\ + \x20 (a) the code under test reads state this segment never captured,\n\ + \x20 because the code that BUILT the segment never read it --\n\ + \x20 an incomplete segment, not a wrong execution;\n\ + \x20 (b) the code that built this segment was itself wrong, and\n\ + \x20 the state it captured does not match the chain.\n\ + \n\ + A passing run of an older version is not a control here: older code\n\ + that never performs the read is immune by construction.\n\ + \n\ + Re-run with a complete store behind the segments (an archival trie\n\ + as a fallback) before concluding anything about consensus.", + hash = key.iter().map(|b| format!("{b:02x}")).collect::(), + ) + } +} + +impl TrieStore for AbortOnMissingNode { + fn get(&self, key: &[u8]) -> Option> { + match self.inner.get(key) { + Some(v) => Some(v), + // Panic rather than return None. The whole point is that `None` + // here is a lie: the caller asked for a node by its committed hash. + None => panic!("{}", Self::message(&self.segment, key)), + } + } + fn put(&self, key: &[u8], value: &[u8]) { + self.inner.put(key, value); + } + fn flush(&self) { + self.inner.flush(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A store that holds exactly one key, so a miss is arranged rather than + /// hoped for. + struct OneKey(Vec, Vec); + impl TrieStore for OneKey { + fn get(&self, key: &[u8]) -> Option> { + (key == self.0.as_slice()).then(|| self.1.clone()) + } + fn put(&self, _k: &[u8], _v: &[u8]) {} + fn flush(&self) {} + } + + #[test] + fn a_present_node_is_returned_unchanged() { + let s = AbortOnMissingNode::new(OneKey(vec![1, 2, 3], vec![9, 9]), "seg"); + assert_eq!(s.get(&[1, 2, 3]), Some(vec![9, 9])); + } + + #[test] + #[should_panic(expected = "is not present in segment seg")] + fn a_missing_node_aborts_instead_of_answering_absent() { + let s = AbortOnMissingNode::new(OneKey(vec![1, 2, 3], vec![9, 9]), "seg"); + let _ = s.get(&[4, 5, 6]); + } + + /// The wrong reading is the intuitive one, so the message must say so. + #[test] + fn the_message_names_both_explanations_and_denies_the_obvious_one() { + let m = AbortOnMissingNode::::message("026-3792187-3815755", &[0xab, 0xcd]); + assert!(m.contains("NOT evidence of a consensus bug")); + assert!(m.contains("incomplete segment, not a wrong execution")); + assert!(m.contains("the code that built this segment was itself wrong")); + assert!(m.contains("026-3792187-3815755")); + assert!(m.contains("abcd"), "the node's hash must be in the message"); + } +} From 3dc341db6b01d34e47a29c78170bac06a35ed468 Mon Sep 17 00:00:00 2001 From: Sergio Demian Lerner Date: Mon, 23 Nov 2026 18:13:49 +0000 Subject: [PATCH 9/9] Bump url to 2.5.9 for RUSTSEC-2026-0592 A stack overflow in Url::origin() on nested blob: URLs. The advisory was published after this branch was cut, so cargo-deny's advisories check started failing on every branch at once, this one included -- it is not a consequence of anything here, which touches neither Cargo.toml nor Cargo.lock otherwise. A patch bump within the existing semver range: url 2.5.8 -> 2.5.9 and form_urlencoded 1.2.2 -> 1.2.3. No [[package]] entry is added, so no new dependency, no new build.rs and no new proc macro arrive with it. Workspace typechecks with examples and tests, no warnings. Co-Authored-By: Claude Opus 5 --- Cargo.lock | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 12360c4d..307c6be1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1534,9 +1534,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -4415,9 +4415,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna",