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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
153 changes: 153 additions & 0 deletions crates/cli/examples/bridge_event_width.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
//! Did the bridge ever log an **empty** single dynamic field?
//!
//! The bridge encodes an event whose data is one dynamic `bytes`/`string` by
//! sizing the content as `((len - 1) / 32 + 1) * 32` in signed truncating
//! division (rskj `SolidityType.BytesType.encode`). At `len = 0` that is
//! `(-1 / 32 + 1) * 32 = 32`, so an empty field still emits one zero word and
//! the data is **96 octets** where the canonical ABI gives 64.
//!
//! Whether any caller ever produced it is a question about the chain, and the
//! evidence is in the **receipts** rather than in the execution -- so this needs
//! no replay. It is the cheapest measurement of its kind: a sequential read of
//! stored receipts.
//!
//! # Why "data is 96 octets" is the wrong test on its own
//!
//! The encoding is `offset(32) ++ length(32) ++ content`, and the content is
//! padded to a whole number of words. So a field of **1 to 32** octets also
//! encodes to exactly 96 -- legitimately, and commonly, since a 32-octet hash
//! is the ordinary case. Filtering on the total alone would report every one of
//! those as a hit.
//!
//! What distinguishes the quirk is the **length word**: 96 octets *and* a
//! declared length of zero. This reports both numbers, because the gap between
//! them is what shows the sharper test was needed.
//!
//! # What it reads
//!
//! Every log of every canonical block in the range, filtered to the bridge
//! address. Logs are what the chain recorded, which is what binds: an argument
//! from today's callers being non-empty is a fact about code, and can be
//! falsified by a version of that code nobody is reading.
//!
//! Read-only, and safe to run against a live node.
//!
//! ```text
//! bridge_event_width <data-dir> [--from N] [--to N]
//! ```

use anyhow::{Context, Result};
use rustock_storage::BlockStore;
use std::time::Instant;

/// rskj `PrecompiledContracts.BRIDGE_ADDR`.
const BRIDGE: &str = "0000000000000000000000000000000001000006";

fn flag(name: &str) -> Option<String> {
let args: Vec<String> = std::env::args().collect();
args.windows(2).find(|w| w[0] == format!("--{name}")).map(|w| w[1].clone())
}

fn main() -> Result<()> {
let data_dir = std::env::args()
.nth(1)
.filter(|a| !a.starts_with("--"))
.context("usage: bridge_event_width <data-dir> [--from N] [--to N]")?;
let store = BlockStore::open_read_only(&data_dir)
.with_context(|| format!("opening {data_dir} read-only"))?;
let head = store
.head()?
.and_then(|h| store.header(h).ok().flatten())
.context("no chain head")?
.number;

let from: u64 = flag("from").and_then(|v| v.parse().ok()).unwrap_or(1);
let to: u64 = flag("to").and_then(|v| v.parse().ok()).unwrap_or(head).min(head);
let bridge: Vec<u8> = alloy_primitives::hex::decode(BRIDGE)?;

println!("scanning receipts of #{from}..#{to} for bridge logs");

let (mut blocks, mut bridge_logs, mut width_96, mut empty_96) = (0u64, 0u64, 0u64, 0u64);
let mut hits: Vec<(u64, String)> = Vec::new();
let started = Instant::now();
let mut last_report = Instant::now();

for number in from..=to {
let Some(hash) = store.canonical_hash(number).ok().flatten() else { continue };
let Some(receipts) = store.receipts(hash).ok().flatten() else { continue };
blocks += 1;
for receipt in &receipts {
for log in &receipt.logs {
if log.address.as_slice() != bridge.as_slice() {
continue;
}
bridge_logs += 1;
if log.data.len() != 96 {
continue;
}
width_96 += 1;
// offset(32) ++ length(32) ++ content. A declared length of
// zero with a word of content present is the quirk; 1..=32 is
// an ordinary short field that happens to be the same width.
let declared = &log.data[32..64];
if declared.iter().all(|b| *b == 0) {
empty_96 += 1;
let topic = log
.topics
.first()
.map(|t| format!("{t:?}"))
.unwrap_or_else(|| "(no topics)".into());
if hits.len() < 50 {
hits.push((number, topic));
}
}
}
}
if last_report.elapsed().as_secs() >= 15 {
let done = number - from + 1;
let rate = done as f64 / started.elapsed().as_secs_f64().max(0.001);
eprintln!(
" #{number}: {done} blocks ({rate:.0}/s), {bridge_logs} bridge logs, \
{width_96} of 96 octets, {empty_96} of them empty"
);
last_report = Instant::now();
}
}

println!();
println!("blocks with receipts {blocks}");
println!("bridge logs {bridge_logs}");
println!(" of exactly 96 octets {width_96} <- what a width-only test would report");
println!(" of those, length zero {empty_96} <- the 96-octet empty encoding");
println!("elapsed {:.0}s", started.elapsed().as_secs_f64());

if !hits.is_empty() {
println!();
println!("occurrences (block, topic0):");
for (number, topic) in &hits {
println!(" #{number} {topic}");
}
if empty_96 as usize > hits.len() {
println!(" ... and {} more", empty_96 as usize - hits.len());
}
}

println!();
if empty_96 == 0 {
println!(
"NONE FOUND in #{from}..#{to}. No bridge log in this range carries the 96-octet \
empty encoding, so as far as this chain's receipts go, no caller ever produced \
an empty single dynamic field."
);
} else {
println!(
"{empty_96} occurrence(s). The 96-octet encoding is in the chain's receipts, so \
it is frozen into a receipts root and the behaviour is load-bearing."
);
}
if blocks == 0 {
println!("but no receipts were read at all -- check the data directory and the range.");
std::process::exit(2);
}
Ok(())
}
23 changes: 23 additions & 0 deletions crates/cli/examples/opcode_census.rs
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,29 @@ fn main() -> Result<()> {
// judgement -- 443 of the first run's hits were the metadata trailer and
// constant pools, and the only way to be sure of the survivors is to read
// the bytes around them.
// Does an address exist as an account in the state trie? One lookup, no
// walk. Written to test a proposed screen for EVM-046 -- "no active
// precompile exists as an account, so no dirty-high-bits call ever landed"
// -- which needs the premise checked before it can be leaned on.
if let Some(hex) = flag("account") {
let node = TrieNode::from_message(&root_bytes, store.as_ref());
for one in hex.split(',') {
let bytes = alloy_primitives::hex::decode(one.trim().trim_start_matches("0x"))
.context("--account takes comma-separated hex addresses")?;
let key = rustock_trie::account_key_from_bytes(&bytes);
let found = node.get(&rustock_trie::TrieKeySlice::from_key(&key), store.as_ref());
println!(
" 0x{} {}",
one.trim().trim_start_matches("0x"),
match found {
Some(v) => format!("EXISTS ({} bytes of account state)", v.len()),
None => "absent".to_string(),
}
);
}
return Ok(());
}

if let Some(hex) = flag("dump") {
let bytes = alloy_primitives::hex::decode(hex.trim_start_matches("0x"))
.context("--dump takes a hex address")?;
Expand Down
57 changes: 57 additions & 0 deletions crates/cli/examples/reexec_all.rs
Original file line number Diff line number Diff line change
Expand Up @@ -760,6 +760,63 @@ fn report_rsk_opcodes(done: u64, planned: u64) {
"contracts deployed in this run: {created}, of which {headered} carried the RSK \
code header"
);
// The legacy-branch census. Printed as a table with each row's window, so
// a zero is always read against the range that produced it.
let census = rustock_execution::legacy_census::census();
println!();
println!("legacy branches taken in this run:");
for (rule, what, window, hits) in &census {
println!(" {rule:<8} {hits:>10} {what} [{window}]");
}
// A campaign that only ever returns zero has not been validated. The
// migration-end-age window is known occupied -- using the ordinary end age
// inside it diverged a real mainnet block -- so a zero there means the
// instrument is broken and every other zero in the table is worthless.
if rustock_execution::legacy_census::positive_control_fired() {
println!(" positive control fired: the counters are live, so the zeros above mean something.");
} else {
println!(
" POSITIVE CONTROL DID NOT FIRE. Either this run did not cover \
#4,976,300..#5,468,000, or the counters are not wired to the branches they \
name. Until that is resolved, treat every zero above as unproven."
);
}

let [staticcalls, with_value] =
rustock_execution::rsk_instructions::staticcall_value_counts();
println!(
"seven-operand STATICCALLs (RSKIP-91 to RSKIP-103, #729,000..#1,052,700): \
{staticcalls} executed, {with_value} carrying a non-zero value"
);
if staticcalls > 0 && with_value == 0 {
println!(
" the form ran but was never passed a value, so nothing on this chain ever \
moved funds through a static call."
);
} else if staticcalls == 0 {
println!(
" the seven-operand form never ran in this range -- which for a range below \
#729,000 means only that the window was not reached."
);
}

let [oversize, unpayable, largest] =
rustock_execution::rsk_instructions::empty_deploy_counts();
println!(
"internal creations below RSKIP-453 that deployed empty instead of reverting: \
{oversize} over the maximum code size, {unpayable} unable to pay the code deposit; \
largest code any of them returned: {largest} octets"
);
// The bound matters more than the counts. RSKIP-453 is #7,338,024 on
// mainnet, so a run that stops below that has only looked at part of the
// era where the quirk applies, and zero means "not here" rather than
// "never".
if oversize == 0 && unpayable == 0 {
println!(
" neither branch fired in this range. Both are dead guards below the highest \
block this run reached -- not below #7,338,024, unless the run covered it."
);
}
if created > 0 && headered == 0 {
println!(
" no contract in this range was ever deployed with a header. A census of the \
Expand Down
Loading
Loading