From 37bf1f34d7c4d1ddebde63af05bdc5748d0d319a Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Sat, 31 Oct 2026 10:52:14 -0400 Subject: [PATCH 01/19] Port EVM inspection: Craft Anything Source: storytold/craft-anything@f64ae3bf3c8863a982af1304e06de20653803968:crates/formats/src/evm.rs --- crates/evm/src/lib.rs | 737 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 737 insertions(+) create mode 100644 crates/evm/src/lib.rs diff --git a/crates/evm/src/lib.rs b/crates/evm/src/lib.rs new file mode 100644 index 000000000..ed5c9f56a --- /dev/null +++ b/crates/evm/src/lib.rs @@ -0,0 +1,737 @@ +//! EVM bytecode: the public function selectors a contract's dispatcher compares against, where +//! each one jumps, whether it refuses payments, fallback/receive presence, and the compiler +//! metadata (CBOR) appended to the code. Nothing is executed; this is a linear sweep that +//! respects PUSH data plus pattern matching over the instruction stream. + +use crate::FormatError; +use serde::Serialize; +use serde_json::{Map, Value}; + +/// Largest bytecode we analyse (16 MiB; deployed contracts are at most 24 KiB). +pub const MAX_CODE: usize = 16 << 20; +const MAX_FUNCTIONS: usize = 4096; +const LISTING_CAP: usize = 400; + +/// How input bytes are encoded. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Encoding { + /// Hex when the bytes are all hex digits (with an optional 0x), raw otherwise. + Auto, + Raw, + Hex, +} + +/// Turn input bytes into bytecode. Hex is strict: optional `0x`, even length, only hex digits; +/// surrounding whitespace is ignored. +pub fn decode_input(input: &[u8], enc: Encoding) -> Result<(Vec, &'static str), FormatError> { + let trimmed = input.trim_ascii(); + let body = trimmed.strip_prefix(b"0x").or_else(|| trimmed.strip_prefix(b"0X")).unwrap_or(trimmed); + let looks_hex = !body.is_empty() && body.iter().all(u8::is_ascii_hexdigit); + let hex = match enc { + Encoding::Hex => true, + Encoding::Raw => false, + Encoding::Auto => looks_hex, + }; + if !hex { + if input.len() > MAX_CODE { + return Err(FormatError::TooLarge(format!("{} bytes; the limit is {MAX_CODE}", input.len()))); + } + return Ok((input.to_vec(), "raw")); + } + if body.is_empty() { + return Err(FormatError::Malformed("no hex digits".into())); + } + if let Some(p) = body.iter().position(|b| !b.is_ascii_hexdigit()) { + return Err(FormatError::Malformed(format!("not a hex digit at position {p}"))); + } + if !body.len().is_multiple_of(2) { + return Err(FormatError::Malformed(format!("odd number of hex digits ({})", body.len()))); + } + if body.len() / 2 > MAX_CODE { + return Err(FormatError::TooLarge(format!("{} bytes; the limit is {MAX_CODE}", body.len() / 2))); + } + let nib = |c: u8| -> u8 { + match c { + b'0'..=b'9' => c - b'0', + b'a'..=b'f' => c - b'a' + 10, + _ => c.wrapping_sub(b'A').wrapping_add(10) & 0x0f, + } + }; + Ok((body.chunks(2).map(|p| (nib(p.first().copied().unwrap_or(b'0')) << 4) | nib(p.get(1).copied().unwrap_or(b'0'))).collect(), "hex")) +} + +#[derive(Debug, Clone, Copy)] +struct Ins { + off: usize, + op: u8, + /// Immediate (PUSH data) start and length. + imm: (usize, usize), +} + +fn push_len(op: u8) -> usize { + if (0x60..=0x7f).contains(&op) { usize::from(op - 0x5f) } else { 0 } +} + +/// The mnemonic of an opcode (`UNKNOWN_0x…` for unassigned ones). +pub fn mnemonic(op: u8) -> String { + let s = match op { + 0x00 => "STOP", + 0x01 => "ADD", + 0x02 => "MUL", + 0x03 => "SUB", + 0x04 => "DIV", + 0x05 => "SDIV", + 0x06 => "MOD", + 0x07 => "SMOD", + 0x08 => "ADDMOD", + 0x09 => "MULMOD", + 0x0a => "EXP", + 0x0b => "SIGNEXTEND", + 0x10 => "LT", + 0x11 => "GT", + 0x12 => "SLT", + 0x13 => "SGT", + 0x14 => "EQ", + 0x15 => "ISZERO", + 0x16 => "AND", + 0x17 => "OR", + 0x18 => "XOR", + 0x19 => "NOT", + 0x1a => "BYTE", + 0x1b => "SHL", + 0x1c => "SHR", + 0x1d => "SAR", + 0x20 => "KECCAK256", + 0x30 => "ADDRESS", + 0x31 => "BALANCE", + 0x32 => "ORIGIN", + 0x33 => "CALLER", + 0x34 => "CALLVALUE", + 0x35 => "CALLDATALOAD", + 0x36 => "CALLDATASIZE", + 0x37 => "CALLDATACOPY", + 0x38 => "CODESIZE", + 0x39 => "CODECOPY", + 0x3a => "GASPRICE", + 0x3b => "EXTCODESIZE", + 0x3c => "EXTCODECOPY", + 0x3d => "RETURNDATASIZE", + 0x3e => "RETURNDATACOPY", + 0x3f => "EXTCODEHASH", + 0x40 => "BLOCKHASH", + 0x41 => "COINBASE", + 0x42 => "TIMESTAMP", + 0x43 => "NUMBER", + 0x44 => "PREVRANDAO", + 0x45 => "GASLIMIT", + 0x46 => "CHAINID", + 0x47 => "SELFBALANCE", + 0x48 => "BASEFEE", + 0x49 => "BLOBHASH", + 0x4a => "BLOBBASEFEE", + 0x50 => "POP", + 0x51 => "MLOAD", + 0x52 => "MSTORE", + 0x53 => "MSTORE8", + 0x54 => "SLOAD", + 0x55 => "SSTORE", + 0x56 => "JUMP", + 0x57 => "JUMPI", + 0x58 => "PC", + 0x59 => "MSIZE", + 0x5a => "GAS", + 0x5b => "JUMPDEST", + 0x5c => "TLOAD", + 0x5d => "TSTORE", + 0x5e => "MCOPY", + 0x5f => "PUSH0", + 0x60..=0x7f => return format!("PUSH{}", op - 0x5f), + 0x80..=0x8f => return format!("DUP{}", op - 0x7f), + 0x90..=0x9f => return format!("SWAP{}", op - 0x8f), + 0xa0..=0xa4 => return format!("LOG{}", op - 0xa0), + 0xf0 => "CREATE", + 0xf1 => "CALL", + 0xf2 => "CALLCODE", + 0xf3 => "RETURN", + 0xf4 => "DELEGATECALL", + 0xf5 => "CREATE2", + 0xfa => "STATICCALL", + 0xfd => "REVERT", + 0xfe => "INVALID", + 0xff => "SELFDESTRUCT", + _ => return format!("UNKNOWN_{op:#04x}"), + }; + s.to_string() +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct EvmFunction { + /// `0x` + 8 hex digits. + pub selector: String, + /// Where the dispatcher sends calls with this selector. + pub bytecode_offset: usize, + /// Offset of the comparison in the dispatcher. + pub compare_offset: usize, + pub dispatch: &'static str, + /// `eq-jumpi` (jump on match) or `eq-iszero-fallthrough` (body follows the check). + pub pattern: &'static str, + /// `nonpayable`, `payable` or `unknown` (view/pure cannot be told from the dispatcher). + pub mutability: &'static str, + /// Why the mutability was chosen. + pub mutability_reason: String, + /// False when the destination is not a JUMPDEST (the match is then doubtful). + pub jumpdest_valid: bool, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct EvmMetadata { + pub offset: usize, + pub length: usize, + pub entries: Value, + pub compiler: Option, + pub ipfs: Option, + pub swarm: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct EvmInterface { + pub code_size: usize, + /// Bytes analysed after removing the metadata tail. + pub analysed_size: usize, + pub metadata: Option, + pub instructions: usize, + pub jumpdests: usize, + /// How the selector is pulled from calldata: `shr-224`, `div-2^224`, `and-mask`, or none. + pub selector_extraction: Option<&'static str>, + pub dispatcher_offset: Option, + /// `solc-like`, `vyper-like`, `mixed` or `none`. + pub style: &'static str, + pub functions: Vec, + /// Comparisons that split the selector range (binary-search dispatchers). + pub binary_search_splits: usize, + /// A CALLVALUE check that runs before any selector comparison (all functions non-payable). + pub callvalue_check_before_dispatch: bool, + pub short_calldata_check: bool, + /// `present`, `absent` or `unknown`. + pub fallback: &'static str, + /// `present` or `not-detected`. + pub receive: &'static str, + /// The dispatcher region as text (first instructions only). + pub dispatcher_listing: Vec, + pub warnings: Vec, +} + +fn sweep(code: &[u8]) -> Vec { + let mut out = Vec::with_capacity(code.len().min(1 << 20) / 2); + let mut i = 0usize; + while i < code.len() { + let op = code.get(i).copied().unwrap_or(0); + let n = push_len(op); + out.push(Ins { off: i, op, imm: (i + 1, n) }); + i = i.saturating_add(1).saturating_add(n); + } + out +} + +fn imm<'a>(code: &'a [u8], ins: &Ins) -> &'a [u8] { + // Truncated PUSH data at the end of code reads as zero-padded; we only use what exists. + let (s, n) = ins.imm; + code.get(s..s.saturating_add(n).min(code.len())).unwrap_or(&[]) +} + +fn imm_u64(code: &[u8], ins: &Ins) -> Option { + let b = imm(code, ins); + if ins.imm.1 > 8 || b.len() != ins.imm.1 { + return None; + } + Some(b.iter().fold(0u64, |a, &x| (a << 8) | u64::from(x))) +} + +fn is_push(op: u8) -> bool { + (0x60..=0x7f).contains(&op) +} + +/// Strip and decode a trailing CBOR metadata block. +fn split_metadata(code: &[u8]) -> (usize, Option) { + let n = code.len(); + if n < 4 { + return (n, None); + } + let len = usize::from(u16::from_be_bytes([code.get(n - 2).copied().unwrap_or(0), code.get(n - 1).copied().unwrap_or(0)])); + if len == 0 || len.saturating_add(2) > n { + return (n, None); + } + let start = n - 2 - len; + let Some(cbor) = code.get(start..n - 2) else { return (n, None) }; + if !matches!(cbor.first(), Some(0xa1..=0xb7 | 0xbf)) { + return (n, None); + } + let mut pos = 0usize; + let Some(v) = cbor_item(cbor, &mut pos, 0) else { return (n, None) }; + if pos != cbor.len() { + return (n, None); + } + let Value::Object(map) = &v else { return (n, None) }; + let compiler = map + .get("solc") + .and_then(|s| s.as_str().map(String::from)) + .map(|v| format!("solc {v}")) + .or_else(|| map.get("vyper").and_then(Value::as_str).map(|v| format!("vyper {v}"))); + let ipfs = map.get("ipfs").and_then(Value::as_str).map(String::from); + let swarm = map.get("bzzr1").or_else(|| map.get("bzzr0")).and_then(Value::as_str).map(String::from); + (start, Some(EvmMetadata { offset: start, length: len + 2, entries: v.clone(), compiler, ipfs, swarm })) +} + +fn cbor_arg(b: &[u8], pos: &mut usize, info: u8) -> Option { + let take = |pos: &mut usize, k: usize| -> Option { + let s = b.get(*pos..pos.checked_add(k)?)?; + *pos += k; + Some(s.iter().fold(0u64, |a, &x| (a << 8) | u64::from(x))) + }; + match info { + 0..=23 => Some(u64::from(info)), + 24 => take(pos, 1), + 25 => take(pos, 2), + 26 => take(pos, 4), + 27 => take(pos, 8), + _ => None, + } +} + +fn cbor_item(b: &[u8], pos: &mut usize, depth: u32) -> Option { + if depth > 4 { + return None; + } + let ib = *b.get(*pos)?; + *pos += 1; + let major = ib >> 5; + let info = ib & 0x1f; + match major { + 0 => cbor_arg(b, pos, info).map(Value::from), + 2 | 3 => { + let n = usize::try_from(cbor_arg(b, pos, info)?).ok()?; + let s = b.get(*pos..pos.checked_add(n)?)?; + *pos += n; + Some(if major == 3 { Value::from(String::from_utf8_lossy(s).into_owned()) } else { Value::from(bytes_value(s)) }) + } + 4 => { + let n = usize::try_from(cbor_arg(b, pos, info)?).ok()?.min(64); + let mut items = Vec::new(); + for _ in 0..n { + items.push(cbor_item(b, pos, depth + 1)?); + } + // A version array like [0, 3, 10] reads as "0.3.10". + if items.len() == 3 && items.iter().all(Value::is_u64) { + return Some(Value::from(items.iter().map(|v| v.to_string()).collect::>().join("."))); + } + Some(Value::Array(items)) + } + 5 => { + let n = usize::try_from(cbor_arg(b, pos, info)?).ok()?.min(32); + let mut m = Map::new(); + for _ in 0..n { + let k = match cbor_item(b, pos, depth + 1)? { + Value::String(s) => s, + other => other.to_string(), + }; + let v = cbor_item(b, pos, depth + 1)?; + let v = match (k.as_str(), &v) { + ("solc", Value::String(s)) if s.starts_with("0x") && s.len() == 8 => { + let d: Vec = (0..3).filter_map(|i| u8::from_str_radix(s.get(2 + 2 * i..4 + 2 * i)?, 16).ok()).collect(); + if let [a, bb, c] = d.as_slice() { Value::from(format!("{a}.{bb}.{c}")) } else { v } + } + ("ipfs", Value::String(s)) if s.starts_with("0x1220") => Value::from(base58(&hex_decode(s.get(2..).unwrap_or("")))), + _ => v, + }; + m.insert(k, v); + } + Some(Value::Object(m)) + } + 7 => match info { + 20 => Some(Value::Bool(false)), + 21 => Some(Value::Bool(true)), + 22 => Some(Value::Null), + _ => None, + }, + _ => None, + } +} + +fn bytes_value(s: &[u8]) -> String { + let mut out = String::with_capacity(2 + s.len() * 2); + out.push_str("0x"); + for b in s { + out.push_str(&format!("{b:02x}")); + } + out +} + +fn hex_decode(s: &str) -> Vec { + (0..s.len() / 2).filter_map(|i| u8::from_str_radix(s.get(2 * i..2 * i + 2)?, 16).ok()).collect() +} + +fn base58(b: &[u8]) -> String { + const A: &[u8; 58] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; + let zeros = b.iter().take_while(|&&x| x == 0).count(); + let mut digits: Vec = Vec::new(); + for &byte in b.iter().take(128) { + let mut carry = u32::from(byte); + for d in digits.iter_mut() { + carry += u32::from(*d) << 8; + *d = (carry % 58) as u8; + carry /= 58; + } + while carry > 0 { + digits.push((carry % 58) as u8); + carry /= 58; + } + } + let mut s: String = std::iter::repeat_n('1', zeros).collect(); + s.extend(digits.iter().rev().map(|&d| char::from(*A.get(usize::from(d)).unwrap_or(&b'1')))); + s +} + +/// Analyse bytecode (already decoded from hex if needed). +pub fn analyze(code: &[u8]) -> Result { + if code.is_empty() { + return Err(FormatError::Truncated("no bytecode".into())); + } + if code.len() > MAX_CODE { + return Err(FormatError::TooLarge(format!("{} bytes; the limit is {MAX_CODE}", code.len()))); + } + if code.starts_with(&[0xef, 0x00]) { + return Err(FormatError::Unsupported("EVM Object Format (EOF, 0xEF00) containers are not analysed".into())); + } + let mut warnings = Vec::new(); + let (end, metadata) = split_metadata(code); + let body = code.get(..end).unwrap_or(code); + let ins = sweep(body); + let jumpdests = ins.iter().filter(|i| i.op == 0x5b).count(); + let at = |k: usize| ins.get(k); + let op_at = |k: usize| at(k).map(|i| i.op); + let index_of = |off: usize| ins.binary_search_by_key(&off, |i| i.off).ok(); + + // Selector extraction: CALLDATALOAD followed by SHR 224, DIV 2^224 or a 4-byte mask. + let mut extraction: Option<(&'static str, usize)> = None; + for (k, i) in ins.iter().enumerate() { + if i.op != 0x35 { + continue; + } + for d in 1..=6 { + let Some(n) = at(k + d) else { break }; + let kind = match n.op { + 0x60 if imm(body, n) == [0xe0] && op_at(k + d + 1) == Some(0x1c) => Some("shr-224"), + 0x7c if imm(body, n).first() == Some(&1) && imm(body, n).iter().skip(1).all(|&b| b == 0) => Some("div-2^224"), + 0x63 if imm(body, n) == [0xff, 0xff, 0xff, 0xff] && (op_at(k + d + 1) == Some(0x16) || op_at(k + d + 2) == Some(0x16)) => Some("and-mask"), + _ => None, + }; + if let Some(kind) = kind { + extraction = Some((kind, k)); + break; + } + } + if extraction.is_some() { + break; + } + } + let disp_start = extraction.map(|(_, k)| k).unwrap_or(0); + if extraction.is_none() { + warnings.push("no selector extraction (CALLDATALOAD then SHR/DIV/AND) was seen; matches below are less certain".into()); + } + + // CALLVALUE check before the dispatcher: CALLVALUE DUP1 ISZERO PUSH JUMPI. + let callvalue_before = ins.iter().take(disp_start).any(|i| i.op == 0x34); + + let mut functions: Vec = Vec::new(); + let mut splits = 0usize; + let mut last_jumpi: Option = None; + let mut solc_like = 0usize; + let mut vyper_like = 0usize; + for k in disp_start..ins.len() { + let Some(i) = at(k) else { break }; + let n = push_len(i.op); + if !(1..=4).contains(&n) { + continue; + } + let Some(sel) = imm_u64(body, i) else { continue }; + let found = |dk: usize| -> Option { + let p = at(dk)?; + (is_push(p.op) && p.imm.1 <= 3 && op_at(dk + 1) == Some(0x57)).then_some(dk) + }; + // PUSH sel, [DUP2], EQ, PUSH dest, JUMPI + let eq_k = if op_at(k + 1) == Some(0x14) { + Some(k + 1) + } else if matches!(op_at(k + 1), Some(0x80..=0x8f)) && op_at(k + 2) == Some(0x14) { + Some(k + 2) + } else { + None + }; + let mut hit: Option<(usize, usize, &'static str)> = None; + if let Some(e) = eq_k { + if let Some(pk) = found(e + 1) + && let Some(dest) = at(pk).and_then(|p| imm_u64(body, p)) + { + hit = Some((usize::try_from(dest).unwrap_or(usize::MAX), pk + 1, "eq-jumpi")); + } else if n == 4 && op_at(e + 1) == Some(0x15) && found(e + 2).is_some() { + // Vyper-style: if selector != x jump to the next check; the body follows. + if let Some(next) = at(e + 4) { + hit = Some((next.off, e + 3, "eq-iszero-fallthrough")); + } + } + } else if n == 4 { + // Vyper also loads the selector from memory: PUSH sel, PUSH1 0, MLOAD, EQ, ISZERO … + for d in 1..=3 { + if op_at(k + d) == Some(0x14) && op_at(k + d + 1) == Some(0x15) && found(k + d + 2).is_some() { + if let Some(next) = at(k + d + 4) { + hit = Some((next.off, k + d + 3, "eq-iszero-fallthrough")); + } + break; + } + } + let direct = matches!(op_at(k + 1), Some(0x10 | 0x11)) && found(k + 2).is_some(); + let via_dup = matches!(op_at(k + 1), Some(0x80..=0x8f)) && matches!(op_at(k + 2), Some(0x10 | 0x11)) && found(k + 3).is_some(); + if hit.is_none() && (direct || via_dup) { + splits += 1; + } + } + let Some((dest, jumpi_k, pattern)) = hit else { continue }; + if n < 4 && extraction.is_none() { + continue; + } + let selector = format!("0x{sel:08x}"); + if functions.iter().any(|f| f.selector == selector) { + continue; + } + if pattern == "eq-jumpi" { + solc_like += 1; + } else { + vyper_like += 1; + } + last_jumpi = Some(jumpi_k); + let di = index_of(dest); + let jumpdest_valid = pattern != "eq-jumpi" || di.and_then(at).is_some_and(|x| x.op == 0x5b); + let (mutability, reason) = if callvalue_before { + ("nonpayable", "a CALLVALUE check runs before the dispatcher, so every function refuses payments".to_string()) + } else { + match di { + Some(d) => payability(body, &ins, d, &index_of), + None => ("unknown", "the destination is not an instruction boundary".to_string()), + } + }; + functions.push(EvmFunction { + selector, + bytecode_offset: dest, + compare_offset: i.off, + dispatch: "abi", + pattern, + mutability, + mutability_reason: reason, + jumpdest_valid, + }); + if functions.len() >= MAX_FUNCTIONS { + warnings.push(format!("stopped at {MAX_FUNCTIONS} selectors")); + break; + } + } + if functions.iter().any(|f| !f.jumpdest_valid) { + warnings.push("some destinations are not JUMPDESTs; those matches may be data, not dispatch".into()); + } + + // Short calldata path and receive(). + let mut short_calldata = false; + let mut receive = "not-detected"; + let mut fallback = "unknown"; + for (k, i) in ins.iter().enumerate().take(disp_start.saturating_add(64)) { + if i.op != 0x36 { + continue; + } + if op_at(k + 1) == Some(0x15) && at(k + 2).is_some_and(|p| is_push(p.op)) && op_at(k + 3) == Some(0x57) { + receive = "present"; + } + let lt = (1..=3).find(|d| op_at(k + d) == Some(0x10)); + if let Some(d) = lt + && at(k + d + 1).is_some_and(|p| is_push(p.op)) + && op_at(k + d + 2) == Some(0x57) + { + short_calldata = true; + } + } + if let Some(j) = last_jumpi + && solc_like > 0 + { + fallback = if reverts_soon(body, &ins, j + 1, &index_of) { "absent" } else { "present" }; + } + let style = match (solc_like > 0, vyper_like > 0) { + (true, true) => "mixed", + (true, false) => "solc-like", + (false, true) => "vyper-like", + _ => "none", + }; + let listing_end = last_jumpi.map(|j| j + 8).unwrap_or(LISTING_CAP).min(LISTING_CAP); + let dispatcher_listing = ins + .iter() + .take(listing_end) + .map(|i| { + let d = imm(body, i); + if d.is_empty() && push_len(i.op) == 0 { + format!("{:#06x}: {}", i.off, mnemonic(i.op)) + } else { + format!("{:#06x}: {} {}", i.off, mnemonic(i.op), bytes_value(d)) + } + }) + .collect(); + if functions.is_empty() { + warnings.push( + "no selector dispatcher was recognised (the code may be creation code without runtime, a proxy, a library, or use a jump-table dispatcher)".into(), + ); + } + Ok(EvmInterface { + code_size: code.len(), + analysed_size: body.len(), + metadata, + instructions: ins.len(), + jumpdests, + selector_extraction: extraction.map(|(k, _)| k), + dispatcher_offset: extraction.and_then(|(_, k)| at(k)).map(|i| i.off), + style, + functions, + binary_search_splits: splits, + callvalue_check_before_dispatch: callvalue_before, + short_calldata_check: short_calldata, + fallback, + receive, + dispatcher_listing, + warnings, + }) +} + +/// Follow a function's entry for a few instructions (and up to two unconditional jumps) looking +/// for a CALLVALUE check. +fn payability(code: &[u8], ins: &[Ins], start: usize, index_of: &dyn Fn(usize) -> Option) -> (&'static str, String) { + let mut k = start; + let mut hops = 0; + for _ in 0..48 { + let Some(i) = ins.get(k) else { break }; + match i.op { + 0x34 => return ("nonpayable", format!("checks CALLVALUE at {:#x}", i.off)), + 0x56 => { + let target = k.checked_sub(1).and_then(|p| ins.get(p)).filter(|p| is_push(p.op)).and_then(|p| imm_u64(code, p)); + match target.and_then(|t| index_of(usize::try_from(t).ok()?)) { + Some(t) if hops < 2 => { + hops += 1; + k = t; + continue; + } + _ => return ("unknown", "jumps somewhere we cannot follow before any CALLVALUE check".into()), + } + } + 0x57 => return ("unknown", "branches before any CALLVALUE check".into()), + 0x00 | 0xf3 | 0xfd | 0xfe | 0xff | 0x35 | 0x37 | 0x54 | 0x55 | 0xf1 | 0xf4 | 0xfa | 0xa0..=0xa4 => { + return ("payable", format!("reaches {} at {:#x} without a CALLVALUE check", mnemonic(i.op), i.off)); + } + _ => {} + } + k += 1; + } + ("unknown", "no CALLVALUE check in the first instructions".into()) +} + +fn reverts_soon(code: &[u8], ins: &[Ins], mut k: usize, index_of: &dyn Fn(usize) -> Option) -> bool { + let mut hops = 0; + for _ in 0..12 { + let Some(i) = ins.get(k) else { return false }; + match i.op { + 0xfd | 0xfe => return true, + 0x56 => { + let target = k.checked_sub(1).and_then(|p| ins.get(p)).filter(|p| is_push(p.op)).and_then(|p| imm_u64(code, p)); + match target.and_then(|t| index_of(usize::try_from(t).ok()?)) { + Some(t) if hops < 2 => { + hops += 1; + k = t; + continue; + } + _ => return false, + } + } + 0x5b | 0x50 | 0x80..=0x9f | 0x5f | 0x60..=0x7f => {} + _ => return false, + } + k += 1; + } + false +} + +#[cfg(test)] +mod tests { + use super::*; + use craft_anything_testkit::formats as fx; + + #[test] + fn dispatcher_selectors_and_metadata() { + let (code, dests) = fx::evm_runtime(); + let r = analyze(&code).unwrap(); + assert_eq!(r.selector_extraction, Some("shr-224")); + assert_eq!(r.style, "solc-like"); + let sels: Vec<_> = r.functions.iter().map(|f| f.selector.clone()).collect(); + assert_eq!(sels, fx::EVM_SELECTORS.iter().map(|s| format!("0x{s:08x}")).collect::>()); + for (f, d) in r.functions.iter().zip(dests) { + assert_eq!(f.bytecode_offset, d); + assert!(f.jumpdest_valid); + } + assert_eq!(r.functions[0].mutability, "nonpayable"); + assert_eq!(r.functions[1].mutability, "nonpayable"); + assert_eq!(r.functions[2].mutability, "payable"); + assert!(r.short_calldata_check); + assert_eq!(r.fallback, "absent"); + let m = r.metadata.unwrap(); + assert_eq!(m.compiler.as_deref(), Some("solc 0.8.19")); + assert!(m.ipfs.unwrap().starts_with("Qm")); + assert_eq!(r.analysed_size + m.length, code.len()); + } + + #[test] + fn hex_input_rules() { + let (code, _) = fx::evm_runtime(); + let hex = fx::to_hex(&code); + assert_eq!(decode_input(format!(" {hex}\n").as_bytes(), Encoding::Auto).unwrap(), (code.clone(), "hex")); + assert_eq!(decode_input(&code, Encoding::Auto).unwrap().1, "raw"); + assert!(decode_input(b"0x123", Encoding::Hex).is_err()); + assert!(decode_input(b"0xzz", Encoding::Hex).is_err()); + assert!(decode_input(b"", Encoding::Hex).is_err()); + assert!(matches!(analyze(&[0xef, 0x00, 0x01]), Err(FormatError::Unsupported(_)))); + assert_eq!(base58(&[0, 0, 1]), "112"); + } + + #[test] + fn vyper_style_fallthrough() { + // PUSH1 0 CALLDATALOAD PUSH1 0xe0 SHR PUSH1 0 MSTORE PUSH4 sel PUSH1 0 MLOAD EQ ISZERO PUSH2 next JUMPI + let mut c = + vec![0x60, 0x00, 0x35, 0x60, 0xe0, 0x1c, 0x60, 0x00, 0x52, 0x63, 0x12, 0x34, 0x56, 0x78, 0x60, 0x00, 0x51, 0x14, 0x15, 0x61, 0x00, 0x20, 0x57]; + let body = c.len(); + c.extend_from_slice(&[0x34, 0x15, 0x00]); + let r = analyze(&c).unwrap(); + assert_eq!(r.style, "vyper-like"); + assert_eq!(r.functions[0].selector, "0x12345678"); + assert_eq!(r.functions[0].bytecode_offset, body); + assert_eq!(r.functions[0].mutability, "nonpayable"); + } + + #[test] + fn hostile_inputs_do_not_panic() { + let (code, _) = fx::evm_runtime(); + for m in craft_anything_testkit::mutations(&code) { + let _ = analyze(&m); + } + for n in 0..code.len() { + let _ = analyze(&code[..n]); + } + for seed in 0..200 { + let n = craft_anything_testkit::noise(seed, 300); + let _ = analyze(&n); + let _ = decode_input(&n, Encoding::Auto); + } + // A metadata length that claims everything, and nested CBOR. + let _ = analyze(&[0xa1, 0xa1, 0xa1, 0xa1, 0xa1, 0xa1, 0xa1, 0x00, 0x07]); + let _ = analyze(&[0x7f; 40]); + } +} From 47b32d58471349e15c0b652cf35db82af0817d48 Mon Sep 17 00:00:00 2001 From: Afloat Date: Mon, 9 Nov 2026 10:39:03 +0800 Subject: [PATCH 02/19] Port EVM inspection: Keep damaged CBOR metadata in the contract bytecode (R3.12) (#1122) Source: storytold/craft-anything@d065d0df84eba1232d8ad5c9185b795610a49b58:crates/formats/src/evm.rs --- crates/evm/src/lib.rs | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/crates/evm/src/lib.rs b/crates/evm/src/lib.rs index ed5c9f56a..f3ed730df 100644 --- a/crates/evm/src/lib.rs +++ b/crates/evm/src/lib.rs @@ -298,6 +298,7 @@ fn cbor_arg(b: &[u8], pos: &mut usize, info: u8) -> Option { } } +/// Decode one bounded metadata item. An incomplete or unsupported value invalidates the metadata trailer. fn cbor_item(b: &[u8], pos: &mut usize, depth: u32) -> Option { if depth > 4 { return None; @@ -312,10 +313,13 @@ fn cbor_item(b: &[u8], pos: &mut usize, depth: u32) -> Option { let n = usize::try_from(cbor_arg(b, pos, info)?).ok()?; let s = b.get(*pos..pos.checked_add(n)?)?; *pos += n; - Some(if major == 3 { Value::from(String::from_utf8_lossy(s).into_owned()) } else { Value::from(bytes_value(s)) }) + Some(if major == 3 { Value::from(std::str::from_utf8(s).ok()?) } else { Value::from(bytes_value(s)) }) } 4 => { - let n = usize::try_from(cbor_arg(b, pos, info)?).ok()?.min(64); + let n = usize::try_from(cbor_arg(b, pos, info)?).ok()?; + if n > 64 { + return None; + } let mut items = Vec::new(); for _ in 0..n { items.push(cbor_item(b, pos, depth + 1)?); @@ -327,7 +331,10 @@ fn cbor_item(b: &[u8], pos: &mut usize, depth: u32) -> Option { Some(Value::Array(items)) } 5 => { - let n = usize::try_from(cbor_arg(b, pos, info)?).ok()?.min(32); + let n = usize::try_from(cbor_arg(b, pos, info)?).ok()?; + if n > 32 { + return None; + } let mut m = Map::new(); for _ in 0..n { let k = match cbor_item(b, pos, depth + 1)? { @@ -666,6 +673,26 @@ mod tests { use super::*; use craft_anything_testkit::formats as fx; + /// A plausible trailer length alone must not remove instructions from the analyzed bytecode. + #[test] + fn incomplete_cbor_must_not_shorten_the_analyzed_contract() { + // A nested array declares 65 integers but supplies just 64. The top-level map + // and its length suffix otherwise look complete. + let mut short = vec![0xa1, 0x61, b'x', 0x98, 65]; + short.extend([0; 64]); + let mut short_map = vec![0xa1, 0x61, b'x', 0xb8, 33]; + for key in 0..32 { + short_map.extend([0x18, key, 0]); + } + for cbor in [short, short_map, vec![0xa1, 0x61, b'x', 0x61, 0xff]] { + let mut code = vec![0x00]; + code.extend(&cbor); + code.extend((cbor.len() as u16).to_be_bytes()); + assert!(split_metadata(&code).1.is_none()); + assert_eq!(analyze(&code).unwrap().analysed_size, code.len()); + } + } + #[test] fn dispatcher_selectors_and_metadata() { let (code, dests) = fx::evm_runtime(); From 5624c2a8e4e20f106f7b100fd11e950bd74e4d6b Mon Sep 17 00:00:00 2001 From: Afloat Date: Mon, 9 Nov 2026 20:15:48 +0800 Subject: [PATCH 03/19] Port EVM inspection: Require a rejecting branch before labelling EVM dispatch nonpayable (R3.12) (#1323) Source: storytold/craft-anything@3f7b9a36158f7f732254051c0cc2df7832aec8d3:crates/formats/src/evm.rs --- crates/evm/src/lib.rs | 61 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 56 insertions(+), 5 deletions(-) diff --git a/crates/evm/src/lib.rs b/crates/evm/src/lib.rs index f3ed730df..94cbf74f1 100644 --- a/crates/evm/src/lib.rs +++ b/crates/evm/src/lib.rs @@ -446,8 +446,13 @@ pub fn analyze(code: &[u8]) -> Result { warnings.push("no selector extraction (CALLDATALOAD then SHR/DIV/AND) was seen; matches below are less certain".into()); } - // CALLVALUE check before the dispatcher: CALLVALUE DUP1 ISZERO PUSH JUMPI. - let callvalue_before = ins.iter().take(disp_start).any(|i| i.op == 0x34); + // Only a guard on the straight-line entry path can apply to every selector. + let callvalue_before = ins + .iter() + .take(disp_start) + .enumerate() + .take_while(|(_, i)| !matches!(i.op, 0x00 | 0x56 | 0x57 | 0xf3 | 0xfd | 0xfe | 0xff)) + .any(|(k, i)| i.op == 0x34 && rejects_value(body, &ins, k, &index_of)); let mut functions: Vec = Vec::new(); let mut splits = 0usize; @@ -620,7 +625,7 @@ fn payability(code: &[u8], ins: &[Ins], start: usize, index_of: &dyn Fn(usize) - for _ in 0..48 { let Some(i) = ins.get(k) else { break }; match i.op { - 0x34 => return ("nonpayable", format!("checks CALLVALUE at {:#x}", i.off)), + 0x34 if rejects_value(code, ins, k, index_of) => return ("nonpayable", format!("rejects nonzero CALLVALUE at {:#x}", i.off)), 0x56 => { let target = k.checked_sub(1).and_then(|p| ins.get(p)).filter(|p| is_push(p.op)).and_then(|p| imm_u64(code, p)); match target.and_then(|t| index_of(usize::try_from(t).ok()?)) { @@ -633,7 +638,8 @@ fn payability(code: &[u8], ins: &[Ins], start: usize, index_of: &dyn Fn(usize) - } } 0x57 => return ("unknown", "branches before any CALLVALUE check".into()), - 0x00 | 0xf3 | 0xfd | 0xfe | 0xff | 0x35 | 0x37 | 0x54 | 0x55 | 0xf1 | 0xf4 | 0xfa | 0xa0..=0xa4 => { + 0xfd | 0xfe => return ("unknown", "halts with an error before any CALLVALUE check".into()), + 0x00 | 0xf3 | 0xff | 0x35 | 0x37 | 0x54 | 0x55 | 0xf1 | 0xf4 | 0xfa | 0xa0..=0xa4 => { return ("payable", format!("reaches {} at {:#x} without a CALLVALUE check", mnemonic(i.op), i.off)); } _ => {} @@ -643,6 +649,26 @@ fn payability(code: &[u8], ins: &[Ins], start: usize, index_of: &dyn Fn(usize) - ("unknown", "no CALLVALUE check in the first instructions".into()) } +/// CALLVALUE only reads the payment. Recognize a direct test that sends the nonzero path +/// to a rejection, allowing the common DUP1 that preserves the original value for cleanup. +fn rejects_value(code: &[u8], ins: &[Ins], k: usize, index_of: &dyn Fn(usize) -> Option) -> bool { + let mut next = k + 1; + if ins.get(next).is_some_and(|i| i.op == 0x80) { + next += 1; + } + let jumps_when_zero = ins.get(next).is_some_and(|i| i.op == 0x15); + next += usize::from(jumps_when_zero); + let Some(push) = ins.get(next).filter(|i| is_push(i.op)) else { return false }; + if ins.get(next + 1).is_none_or(|i| i.op != 0x57) { + return false; + } + let Some(target) = imm_u64(code, push).and_then(|v| usize::try_from(v).ok()).and_then(index_of) else { return false }; + if ins.get(target).is_none_or(|i| i.op != 0x5b) { + return false; + } + reverts_soon(code, ins, if jumps_when_zero { next + 2 } else { target }, index_of) +} + fn reverts_soon(code: &[u8], ins: &[Ins], mut k: usize, index_of: &dyn Fn(usize) -> Option) -> bool { let mut hops = 0; for _ in 0..12 { @@ -740,7 +766,32 @@ mod tests { assert_eq!(r.style, "vyper-like"); assert_eq!(r.functions[0].selector, "0x12345678"); assert_eq!(r.functions[0].bytecode_offset, body); - assert_eq!(r.functions[0].mutability, "nonpayable"); + assert_eq!(r.functions[0].mutability, "payable", "ISZERO followed by STOP never rejects payment"); + } + + #[test] + fn nonpayable_needs_a_rejecting_nonzero_branch() { + fn dispatch(prefix: &[u8]) -> EvmInterface { + let mut code = prefix.to_vec(); + code.extend([0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x63, 1, 2, 3, 4, 0x14, 0x60]); + code.extend([(code.len() + 3) as u8, 0x57, 0x00, 0x5b, 0x00]); + analyze(&code).unwrap() + } + let read_only = dispatch(&[0x34, 0x50]); // CALLVALUE POP + assert!(!read_only.callvalue_check_before_dispatch); + assert_eq!(read_only.functions[0].mutability, "payable"); + let guard = dispatch(&[0x34, 0x80, 0x15, 0x60, 9, 0x57, 0x5f, 0x80, 0xfd, 0x5b, 0x50]); + assert!(guard.callvalue_check_before_dispatch); + assert_eq!(guard.functions[0].mutability, "nonpayable"); + // The other common form jumps to REVERT for a nonzero value and otherwise skips it. + let direct = dispatch(&[0x34, 0x60, 7, 0x57, 0x60, 11, 0x56, 0x5b, 0x5f, 0x80, 0xfd, 0x5b]); + assert!(direct.callvalue_check_before_dispatch); + // Reversing that conditional rejects zero-value calls, not payments. + let reversed = dispatch(&[0x34, 0x15, 0x60, 8, 0x57, 0x60, 12, 0x56, 0x5b, 0x5f, 0x80, 0xfd, 0x5b]); + assert!(!reversed.callvalue_check_before_dispatch); + // An unconditional jump bypasses the otherwise valid guard before the dispatcher. + let bypassed = dispatch(&[0x60, 12, 0x56, 0x34, 0x80, 0x15, 0x60, 12, 0x57, 0x5f, 0x80, 0xfd, 0x5b]); + assert!(!bypassed.callvalue_check_before_dispatch); } #[test] From 1e3a26885f3ec1b4ffb58f9a6e142a99d1da7eba Mon Sep 17 00:00:00 2001 From: Afloat Date: Wed, 11 Nov 2026 01:16:26 +0800 Subject: [PATCH 04/19] Port EVM inspection: Avoid repeated selector scans in EVM dispatchers (R3.12) (#1538) Source: storytold/craft-anything@1565bd4278955161e4c704cee37bbae9f22bfb3a:crates/formats/src/evm.rs --- crates/evm/src/lib.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/evm/src/lib.rs b/crates/evm/src/lib.rs index 94cbf74f1..059252dc4 100644 --- a/crates/evm/src/lib.rs +++ b/crates/evm/src/lib.rs @@ -6,6 +6,7 @@ use crate::FormatError; use serde::Serialize; use serde_json::{Map, Value}; +use std::collections::BTreeSet; /// Largest bytecode we analyse (16 MiB; deployed contracts are at most 24 KiB). pub const MAX_CODE: usize = 16 << 20; @@ -455,6 +456,7 @@ pub fn analyze(code: &[u8]) -> Result { .any(|(k, i)| i.op == 0x34 && rejects_value(body, &ins, k, &index_of)); let mut functions: Vec = Vec::new(); + let mut selectors = BTreeSet::new(); let mut splits = 0usize; let mut last_jumpi: Option = None; let mut solc_like = 0usize; @@ -510,10 +512,10 @@ pub fn analyze(code: &[u8]) -> Result { if n < 4 && extraction.is_none() { continue; } - let selector = format!("0x{sel:08x}"); - if functions.iter().any(|f| f.selector == selector) { + if !selectors.insert(sel) { continue; } + let selector = format!("0x{sel:08x}"); if pattern == "eq-jumpi" { solc_like += 1; } else { From ef2997f9eb9b8767305bb905a00abe9da992a17d Mon Sep 17 00:00:00 2001 From: Afloat Date: Wed, 11 Nov 2026 01:34:53 +0800 Subject: [PATCH 05/19] Port EVM inspection: Preserve EVM bytecode when metadata map keys are ambiguous (R3.12) (#1508) Source: storytold/craft-anything@a7e66ab5982afe34d0905bbfe9c65d260f41c455:crates/formats/src/evm.rs --- crates/evm/src/lib.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/evm/src/lib.rs b/crates/evm/src/lib.rs index 059252dc4..b2a439780 100644 --- a/crates/evm/src/lib.rs +++ b/crates/evm/src/lib.rs @@ -338,10 +338,15 @@ fn cbor_item(b: &[u8], pos: &mut usize, depth: u32) -> Option { } let mut m = Map::new(); for _ in 0..n { - let k = match cbor_item(b, pos, depth + 1)? { - Value::String(s) => s, - other => other.to_string(), - }; + // The metadata view uses JSON object keys. Coercing other CBOR key + // types to strings can merge distinct keys and hide bytecode. + if b.get(*pos).map(|byte| byte >> 5) != Some(3) { + return None; + } + let Value::String(k) = cbor_item(b, pos, depth + 1)? else { return None }; + if m.contains_key(&k) { + return None; + } let v = cbor_item(b, pos, depth + 1)?; let v = match (k.as_str(), &v) { ("solc", Value::String(s)) if s.starts_with("0x") && s.len() == 8 => { From 80f6ae251599e8df319aa2d2650cad6104420490 Mon Sep 17 00:00:00 2001 From: Afloat Date: Wed, 11 Nov 2026 18:10:38 +0800 Subject: [PATCH 06/19] Port EVM inspection: Require matching operands before reporting EVM dispatch facts (R3.12) (#1651) Source: storytold/craft-anything@341dd7def502be2925c8f3c111c4d51a0afea39b:crates/formats/src/evm.rs --- crates/evm/src/lib.rs | 38 +++++++++++++++++++++++++------------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/crates/evm/src/lib.rs b/crates/evm/src/lib.rs index b2a439780..9769d17e9 100644 --- a/crates/evm/src/lib.rs +++ b/crates/evm/src/lib.rs @@ -434,7 +434,14 @@ pub fn analyze(code: &[u8]) -> Result { let Some(n) = at(k + d) else { break }; let kind = match n.op { 0x60 if imm(body, n) == [0xe0] && op_at(k + d + 1) == Some(0x1c) => Some("shr-224"), - 0x7c if imm(body, n).first() == Some(&1) && imm(body, n).iter().skip(1).all(|&b| b == 0) => Some("div-2^224"), + 0x7c if d == 1 + && imm(body, n).first() == Some(&1) + && imm(body, n).iter().skip(1).all(|&b| b == 0) + && op_at(k + d + 1) == Some(0x90) + && op_at(k + d + 2) == Some(0x04) => + { + Some("div-2^224") + } 0x63 if imm(body, n) == [0xff, 0xff, 0xff, 0xff] && (op_at(k + d + 1) == Some(0x16) || op_at(k + d + 2) == Some(0x16)) => Some("and-mask"), _ => None, }; @@ -499,13 +506,15 @@ pub fn analyze(code: &[u8]) -> Result { } } else if n == 4 { // Vyper also loads the selector from memory: PUSH sel, PUSH1 0, MLOAD, EQ, ISZERO … - for d in 1..=3 { - if op_at(k + d) == Some(0x14) && op_at(k + d + 1) == Some(0x15) && found(k + d + 2).is_some() { - if let Some(next) = at(k + d + 4) { - hit = Some((next.off, k + d + 3, "eq-iszero-fallthrough")); - } - break; - } + let load = at(k + 1).is_some_and(|p| (p.op == 0x5f || is_push(p.op)) && imm_u64(body, p) == Some(0)); + if load + && op_at(k + 2) == Some(0x51) + && op_at(k + 3) == Some(0x14) + && op_at(k + 4) == Some(0x15) + && found(k + 5).is_some() + && let Some(next) = at(k + 7) + { + hit = Some((next.off, k + 6, "eq-iszero-fallthrough")); } let direct = matches!(op_at(k + 1), Some(0x10 | 0x11)) && found(k + 2).is_some(); let via_dup = matches!(op_at(k + 1), Some(0x80..=0x8f)) && matches!(op_at(k + 2), Some(0x10 | 0x11)) && found(k + 3).is_some(); @@ -529,7 +538,9 @@ pub fn analyze(code: &[u8]) -> Result { last_jumpi = Some(jumpi_k); let di = index_of(dest); let jumpdest_valid = pattern != "eq-jumpi" || di.and_then(at).is_some_and(|x| x.op == 0x5b); - let (mutability, reason) = if callvalue_before { + let (mutability, reason) = if !jumpdest_valid { + ("unknown", "the destination is not a JUMPDEST".to_owned()) + } else if callvalue_before { ("nonpayable", "a CALLVALUE check runs before the dispatcher, so every function refuses payments".to_string()) } else { match di { @@ -567,10 +578,11 @@ pub fn analyze(code: &[u8]) -> Result { if op_at(k + 1) == Some(0x15) && at(k + 2).is_some_and(|p| is_push(p.op)) && op_at(k + 3) == Some(0x57) { receive = "present"; } - let lt = (1..=3).find(|d| op_at(k + d) == Some(0x10)); - if let Some(d) = lt - && at(k + d + 1).is_some_and(|p| is_push(p.op)) - && op_at(k + d + 2) == Some(0x57) + // LT pops the size first in PUSH 4, CALLDATASIZE, LT. + if k.checked_sub(1).and_then(at).is_some_and(|p| is_push(p.op) && imm_u64(body, p) == Some(4)) + && op_at(k + 1) == Some(0x10) + && at(k + 2).is_some_and(|p| is_push(p.op)) + && op_at(k + 3) == Some(0x57) { short_calldata = true; } From eb27a0d8ed72a41387e2ad233f9d7437ca1eadf1 Mon Sep 17 00:00:00 2001 From: RRFZ <247457381+Plastic-time@users.noreply.github.com> Date: Thu, 12 Nov 2026 00:23:25 -0500 Subject: [PATCH 07/19] Port EVM inspection: Keep ordinary EVM metadata arrays typed (R3.12) (#1732) (#1732) Source: storytold/craft-anything@726fa4d25ba49e2742d88860b3adcb83df46d5c2:crates/formats/src/evm.rs --- crates/evm/src/lib.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/crates/evm/src/lib.rs b/crates/evm/src/lib.rs index 9769d17e9..da6df0961 100644 --- a/crates/evm/src/lib.rs +++ b/crates/evm/src/lib.rs @@ -325,10 +325,6 @@ fn cbor_item(b: &[u8], pos: &mut usize, depth: u32) -> Option { for _ in 0..n { items.push(cbor_item(b, pos, depth + 1)?); } - // A version array like [0, 3, 10] reads as "0.3.10". - if items.len() == 3 && items.iter().all(Value::is_u64) { - return Some(Value::from(items.iter().map(|v| v.to_string()).collect::>().join("."))); - } Some(Value::Array(items)) } 5 => { @@ -349,6 +345,9 @@ fn cbor_item(b: &[u8], pos: &mut usize, depth: u32) -> Option { } let v = cbor_item(b, pos, depth + 1)?; let v = match (k.as_str(), &v) { + ("solc" | "vyper", Value::Array(items)) if items.len() == 3 && items.iter().all(Value::is_u64) => { + Value::from(items.iter().map(|v| v.to_string()).collect::>().join(".")) + } ("solc", Value::String(s)) if s.starts_with("0x") && s.len() == 8 => { let d: Vec = (0..3).filter_map(|i| u8::from_str_radix(s.get(2 + 2 * i..4 + 2 * i)?, 16).ok()).collect(); if let [a, bb, c] = d.as_slice() { Value::from(format!("{a}.{bb}.{c}")) } else { v } From 9d718a87410cb6e30966bd617b25bfd0a3528955 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:58:27 +0100 Subject: [PATCH 08/19] Port EVM inspection: Reject '+' signs in hex of EVM metadata solc and ipfs values (#1971) Source: storytold/craft-anything@86c2dd0227f4ee8b2f953dc8b00a9d1426032e11:crates/formats/src/evm.rs --- crates/evm/src/lib.rs | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/crates/evm/src/lib.rs b/crates/evm/src/lib.rs index da6df0961..6eb9aace4 100644 --- a/crates/evm/src/lib.rs +++ b/crates/evm/src/lib.rs @@ -349,7 +349,7 @@ fn cbor_item(b: &[u8], pos: &mut usize, depth: u32) -> Option { Value::from(items.iter().map(|v| v.to_string()).collect::>().join(".")) } ("solc", Value::String(s)) if s.starts_with("0x") && s.len() == 8 => { - let d: Vec = (0..3).filter_map(|i| u8::from_str_radix(s.get(2 + 2 * i..4 + 2 * i)?, 16).ok()).collect(); + let d: Vec = (0..3).filter_map(|i| hex_byte(s.get(2 + 2 * i..4 + 2 * i)?)).collect(); if let [a, bb, c] = d.as_slice() { Value::from(format!("{a}.{bb}.{c}")) } else { v } } ("ipfs", Value::String(s)) if s.starts_with("0x1220") => Value::from(base58(&hex_decode(s.get(2..).unwrap_or("")))), @@ -378,8 +378,13 @@ fn bytes_value(s: &[u8]) -> String { out } +/// One byte from two hex digits; `from_str_radix` alone would also accept a leading `+`. +fn hex_byte(pair: &str) -> Option { + if pair.bytes().all(|c| c.is_ascii_hexdigit()) { u8::from_str_radix(pair, 16).ok() } else { None } +} + fn hex_decode(s: &str) -> Vec { - (0..s.len() / 2).filter_map(|i| u8::from_str_radix(s.get(2 * i..2 * i + 2)?, 16).ok()).collect() + (0..s.len() / 2).filter_map(|i| hex_byte(s.get(2 * i..2 * i + 2)?)).collect() } fn base58(b: &[u8]) -> String { @@ -717,6 +722,21 @@ mod tests { use super::*; use craft_anything_testkit::formats as fx; + #[test] + fn hex_signs_are_not_hex_digits() { + let solc = |v: &str| { + let mut b = vec![0xa1, 0x64]; + b.extend(b"solc"); + b.push(0x60 + v.len() as u8); + b.extend(v.as_bytes()); + cbor_item(&b, &mut 0, 0).unwrap()["solc"].clone() + }; + assert_eq!(solc("0x+1+2+3"), "0x+1+2+3"); + assert_eq!(solc("0x000008"), "0.0.8"); + assert!(hex_decode("+f").is_empty()); + assert_eq!(hex_decode("0f"), vec![15]); + } + /// A plausible trailer length alone must not remove instructions from the analyzed bytecode. #[test] fn incomplete_cbor_must_not_shorten_the_analyzed_contract() { From 5e1f00b37f2f1f26bd22dac8040425f785db8a09 Mon Sep 17 00:00:00 2001 From: Afloat Date: Wed, 11 Nov 2026 01:34:53 +0800 Subject: [PATCH 09/19] Port EVM regression: Preserve EVM bytecode when metadata map keys are ambiguous (R3.12) (#1508) Source: storytold/craft-anything@a7e66ab5982afe34d0905bbfe9c65d260f41c455:crates/formats/tests/evm_metadata_map_keys.rs --- crates/evm/tests/evm_metadata_map_keys.rs | 68 +++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 crates/evm/tests/evm_metadata_map_keys.rs diff --git a/crates/evm/tests/evm_metadata_map_keys.rs b/crates/evm/tests/evm_metadata_map_keys.rs new file mode 100644 index 000000000..cfd108521 --- /dev/null +++ b/crates/evm/tests/evm_metadata_map_keys.rs @@ -0,0 +1,68 @@ +use craft_anything_formats::evm::analyze; + +fn contract_with_trailer(cbor: &[u8]) -> Vec { + let mut code = vec![0x5b, 0x00]; + code.extend_from_slice(cbor); + code.extend_from_slice(&u16::try_from(cbor.len()).unwrap().to_be_bytes()); + code +} + +fn assert_unrecognized(cbor: &[u8]) { + let code = contract_with_trailer(cbor); + let result = analyze(&code).unwrap(); + assert!(result.metadata.is_none(), "ambiguous map must remain bytecode: {cbor:02x?}"); + assert_eq!(result.analysed_size, code.len()); +} + +#[test] +fn duplicate_compiler_keys_do_not_replace_the_reported_version() { + assert_unrecognized(b"\xa2\x64solc\x43\x00\x08\x13\x64solc\x43\x00\x08\x1a"); +} + +#[test] +fn identical_duplicate_keys_are_also_ambiguous() { + assert_unrecognized(b"\xa2\x64solc\x43\x00\x08\x13\x64solc\x43\x00\x08\x13"); +} + +#[test] +fn numeric_keys_cannot_collide_with_text_keys() { + assert_unrecognized(b"\xa2\x01\x00\x61\x31\x01"); +} + +#[test] +fn metadata_map_keys_must_be_encoded_as_text() { + for key in [vec![0x01], vec![0x41, b'x'], vec![0x83, 0, 1, 2], vec![0xf5], vec![0xf6], vec![0xa0]] { + let mut cbor = vec![0xa1]; + cbor.extend(key); + cbor.push(0); + assert_unrecognized(&cbor); + } +} + +#[test] +fn nested_maps_do_not_silently_overwrite_keys() { + assert_unrecognized(b"\xa1\x65extra\xa2\x61x\x00\x61x\x01"); + assert_unrecognized(b"\xa1\x65extra\xa1\x01\x00"); +} + +#[test] +fn ordinary_compiler_metadata_and_unique_nested_text_keys_still_decode() { + let code = contract_with_trailer(b"\xa2\x64solc\x43\x00\x08\x13\x65extra\xa2\x61x\x00\x61y\x01"); + let result = analyze(&code).unwrap(); + assert_eq!(result.analysed_size, 2); + let metadata = result.metadata.unwrap(); + assert_eq!(metadata.compiler.as_deref(), Some("solc 0.8.19")); + assert_eq!(metadata.entries["extra"]["x"], 0); + assert_eq!(metadata.entries["extra"]["y"], 1); + assert_eq!(metadata.length, code.len() - 2); +} + +#[test] +fn equal_keys_in_separate_maps_are_independent() { + let code = contract_with_trailer(b"\xa2\x61a\xa1\x61x\x00\x61b\xa1\x61x\x01"); + let result = analyze(&code).unwrap(); + assert_eq!(result.analysed_size, 2); + let entries = result.metadata.unwrap().entries; + assert_eq!(entries["a"]["x"], 0); + assert_eq!(entries["b"]["x"], 1); +} From 9acfe9da4ded07f44fba6b289ee5dfbaa1cda5af Mon Sep 17 00:00:00 2001 From: RRFZ <247457381+Plastic-time@users.noreply.github.com> Date: Thu, 12 Nov 2026 00:23:25 -0500 Subject: [PATCH 10/19] Port EVM regression: Keep ordinary EVM metadata arrays typed (R3.12) (#1732) (#1732) Source: storytold/craft-anything@726fa4d25ba49e2742d88860b3adcb83df46d5c2:crates/formats/tests/evm_metadata_arrays.rs --- crates/evm/tests/evm_metadata_arrays.rs | 39 +++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 crates/evm/tests/evm_metadata_arrays.rs diff --git a/crates/evm/tests/evm_metadata_arrays.rs b/crates/evm/tests/evm_metadata_arrays.rs new file mode 100644 index 000000000..ceeda5c07 --- /dev/null +++ b/crates/evm/tests/evm_metadata_arrays.rs @@ -0,0 +1,39 @@ +use craft_evm as evm; +use serde_json::json; + +/// Unrelated three-integer arrays stay arrays while compiler versions stay readable. +#[test] +fn cbor_arrays_are_not_all_compiler_versions() { + // {"sizes": [1, 2, 3], "vyper": [0, 3, 10]} + for (cbor, compiler) in [ + (b"\xa2\x65sizes\x83\x01\x02\x03\x65vyper\x83\x00\x03\x0a".as_slice(), "vyper 0.3.10"), + (b"\xa2\x65sizes\x83\x01\x02\x03\x64solc\x83\x00\x08\x13".as_slice(), "solc 0.8.19"), + ] { + let mut code = vec![0x00]; + code.extend(cbor); + code.extend((cbor.len() as u16).to_be_bytes()); + let result = evm::analyze(&code).unwrap(); + let meta = result.metadata.unwrap(); + assert_eq!(meta.entries["sizes"], json!([1, 2, 3])); + assert_eq!(meta.compiler.as_deref(), Some(compiler)); + assert_eq!(result.analysed_size, 1); + } +} + +/// A non-version Vyper array stays typed, and a truncated array stays bytecode. +#[test] +fn invalid_version_shapes_are_not_invented_or_silently_consumed() { + let cbor = b"\xa1\x65vyper\x82\x00\x03"; + let mut code = vec![0x00]; + code.extend(cbor); + code.extend((cbor.len() as u16).to_be_bytes()); + let meta = evm::analyze(&code).unwrap().metadata.unwrap(); + assert_eq!(meta.compiler, None); + assert_eq!(meta.entries["vyper"], json!([0, 3])); + + let mut truncated = code; + truncated[8] = 0x83; // Declare three items but keep only two. + let result = evm::analyze(&truncated).unwrap(); + assert!(result.metadata.is_none()); + assert_eq!(result.analysed_size, truncated.len()); +} From 76e8a7607f8b5b602e823d5759f8e4e7fd4ae45f Mon Sep 17 00:00:00 2001 From: Afloat Date: Wed, 11 Nov 2026 01:16:26 +0800 Subject: [PATCH 11/19] Port EVM regression: Avoid repeated selector scans in EVM dispatchers (R3.12) (#1538) Source: storytold/craft-anything@1565bd4278955161e4c704cee37bbae9f22bfb3a:crates/formats/tests/evm_selector_dedup.rs --- crates/evm/tests/evm_selector_dedup.rs | 70 ++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 crates/evm/tests/evm_selector_dedup.rs diff --git a/crates/evm/tests/evm_selector_dedup.rs b/crates/evm/tests/evm_selector_dedup.rs new file mode 100644 index 000000000..8ce4b88a4 --- /dev/null +++ b/crates/evm/tests/evm_selector_dedup.rs @@ -0,0 +1,70 @@ +use craft_evm as evm; + +fn prefix() -> Vec { + vec![0x5b, 0x00, 0x60, 0x00, 0x35, 0x60, 0xe0, 0x1c] +} + +fn comparison(code: &mut Vec, selector: u32, width: usize, destination: u8) { + code.push(0x5f + u8::try_from(width).unwrap()); + code.extend_from_slice(&selector.to_be_bytes()[4 - width..]); + code.extend([0x14, 0x60, destination, 0x57]); +} + +#[test] +fn repeated_comparisons_keep_the_first_destination_and_encounter_order() { + let mut code = prefix(); + comparison(&mut code, 0xfeed0002, 4, 0); + comparison(&mut code, 0xfeed0001, 4, 0); + let expected = evm::analyze(&code).unwrap().functions; + for _ in 0..2000 { + comparison(&mut code, 0xfeed0001, 4, 1); + comparison(&mut code, 0xfeed0002, 4, 1); + } + assert_eq!(evm::analyze(&code).unwrap().functions, expected); +} + +#[test] +fn different_push_widths_share_the_same_numeric_selector() { + let mut code = prefix(); + for width in 1..=4 { + comparison(&mut code, 17, width, if width == 1 { 0 } else { 1 }); + } + let result = evm::analyze(&code).unwrap(); + assert_eq!(result.functions.len(), 1); + assert_eq!(result.functions[0].selector, "0x00000011"); + assert_eq!(result.functions[0].bytecode_offset, 0); +} + +#[test] +fn rejected_candidates_do_not_spend_selector_identity() { + let mut code = vec![0x5b, 0x00]; + // Short comparisons without selector extraction are not considered functions. + comparison(&mut code, 17, 1, 1); + // A selector-shaped immediate without a comparison is not a function either. + code.extend([0x63, 0, 0, 0, 17, 0x50]); + comparison(&mut code, 17, 4, 0); + let result = evm::analyze(&code).unwrap(); + assert_eq!(result.functions.len(), 1); + assert_eq!(result.functions[0].bytecode_offset, 0); + assert!(result.functions[0].jumpdest_valid); +} + +#[test] +fn selector_cap_counts_unique_matches() { + let mut code = prefix(); + for selector in 0..4095 { + comparison(&mut code, selector, 4, 0); + } + for _ in 0..10000 { + comparison(&mut code, 4094, 4, 1); + } + let below = evm::analyze(&code).unwrap(); + assert_eq!(below.functions.len(), 4095); + assert!(!below.warnings.iter().any(|warning| warning.contains("stopped at"))); + comparison(&mut code, 4095, 4, 0); + comparison(&mut code, 4096, 4, 0); + let capped = evm::analyze(&code).unwrap(); + assert_eq!(capped.functions.len(), 4096); + assert_eq!(capped.functions.last().unwrap().selector, "0x00000fff"); + assert!(capped.warnings.iter().any(|warning| warning == "stopped at 4096 selectors")); +} From 5a74c5ef3637a885acdf553817b775a69b71f498 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 12:00:08 -0500 Subject: [PATCH 12/19] Expose shared read-only EVM inspection with retained bounds and regressions --- ATTRIBUTION.md | 4 + Cargo.lock | 23 ++++-- Cargo.toml | 1 + crates/evm/Cargo.toml | 14 ++++ crates/evm/README.md | 7 ++ crates/evm/src/lib.rs | 36 +++++++-- crates/evm/src/test_support.rs | 99 +++++++++++++++++++++++ crates/evm/tests/evm_metadata_map_keys.rs | 2 +- 8 files changed, 171 insertions(+), 15 deletions(-) create mode 100644 crates/evm/Cargo.toml create mode 100644 crates/evm/README.md create mode 100644 crates/evm/src/test_support.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index f772eede2..f62a8130b 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -141,3 +141,7 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. ## HTTP Archive reader `crates/har` preserves Craft Anything `crates/formats/src/har.rs` from `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Brandon Thomas introduced the typed reader in `f64ae3bf3c8863a982af1304e06de20653803968`; BFlat added UTF-8 BOM compatibility in `cb0bb9d8fa4536ba44ef2c86f5ed759b879cc2d3`. Both source snapshots retain primary author attribution. Shared wiring, explicit byte admission and its tests are subsequent Dylan M. Taylor changes. Redaction and analysis remain app-owned. + +## EVM bytecode inspection + +`crates/evm` extracts Craft Anything `crates/formats/src/evm.rs` at `a31e995858f4312e0f1d59a007112da191ef2d26` (MIT OR Apache-2.0). Eight separate source-history ports preserve Brandon Thomas, Afloat, RRFZ and NetterSilver as primary authors with immutable source references. Synthetic EVM fixtures and deterministic mutation helpers come from the same app source; regression files retain their source provenance. Neutral errors and workspace integration are subsequent changes. No code execution or transaction behavior is imported. diff --git a/Cargo.lock b/Cargo.lock index da0654156..d554ad256 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1881,6 +1881,15 @@ dependencies = [ "zip 9.1.3", ] +[[package]] +name = "craft-evm" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-ews" version = "0.1.0" @@ -2122,13 +2131,6 @@ dependencies = [ "flate2", ] -[[package]] -name = "craft-hdr" -version = "0.1.0" -dependencies = [ - "thiserror 2.0.21", -] - [[package]] name = "craft-har" version = "0.1.0" @@ -2137,6 +2139,13 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-hdr" +version = "0.1.0" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-heif" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index c8cd94409..b42f0a33d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/craft-libs" [workspace.dependencies] +craft-evm = { path = "crates/evm" } craft-har = { path = "crates/har" } craft-jsonc = { path = "crates/jsonc" } craft-palette = { path = "crates/palette" } diff --git a/crates/evm/Cargo.toml b/crates/evm/Cargo.toml new file mode 100644 index 000000000..92d0abae8 --- /dev/null +++ b/crates/evm/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "craft-evm" +description = "Read-only EVM bytecode dispatcher and compiler metadata inspection" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true +[lints] +workspace = true +[dependencies] +serde = { workspace = true } +serde_json = { workspace = true } +thiserror = { workspace = true } diff --git a/crates/evm/README.md b/crates/evm/README.md new file mode 100644 index 000000000..6214c45b4 --- /dev/null +++ b/crates/evm/README.md @@ -0,0 +1,7 @@ +# craft-evm + +Read-only EVM bytecode inspection: strict raw/hex admission, opcode listing, dispatcher selector and jump-pattern facts, and Solidity/Vyper CBOR metadata. No VM execution, RPC, wallet, signing or transaction support. + +Preserves Craft Anything's parser behavior and limits: 16 MiB decoded bytecode, 4,096 reported functions and 400 listing entries, plus existing bounded CBOR recursion/collection parsing. These are not a total allocator-byte guarantee. Dispatcher facts are heuristics, not a full control-flow or semantic proof. EOF containers remain unsupported. + +Application file I/O, evidence policy and selector naming remain outside this crate. diff --git a/crates/evm/src/lib.rs b/crates/evm/src/lib.rs index 6eb9aace4..18104edcf 100644 --- a/crates/evm/src/lib.rs +++ b/crates/evm/src/lib.rs @@ -1,9 +1,28 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + //! EVM bytecode: the public function selectors a contract's dispatcher compares against, where //! each one jumps, whether it refuses payments, fallback/receive presence, and the compiler //! metadata (CBOR) appended to the code. Nothing is executed; this is a linear sweep that //! respects PUSH data plus pattern matching over the instruction stream. -use crate::FormatError; +use EvmError as FormatError; + +/// Neutral inspection failure; no code is executed. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum EvmError { + #[error("truncated input: {0}")] + Truncated(String), + #[error("malformed input: {0}")] + Malformed(String), + #[error("unsupported: {0}")] + Unsupported(String), + #[error("input too large: {0}")] + TooLarge(String), +} + +#[cfg(test)] +mod test_support; use serde::Serialize; use serde_json::{Map, Value}; use std::collections::BTreeSet; @@ -446,7 +465,9 @@ pub fn analyze(code: &[u8]) -> Result { { Some("div-2^224") } - 0x63 if imm(body, n) == [0xff, 0xff, 0xff, 0xff] && (op_at(k + d + 1) == Some(0x16) || op_at(k + d + 2) == Some(0x16)) => Some("and-mask"), + 0x63 if imm(body, n) == [0xff, 0xff, 0xff, 0xff] && (op_at(k + d + 1) == Some(0x16) || op_at(k + d + 2) == Some(0x16)) => { + Some("and-mask") + } _ => None, }; if let Some(kind) = kind { @@ -720,7 +741,7 @@ fn reverts_soon(code: &[u8], ins: &[Ins], mut k: usize, index_of: &dyn Fn(usize) #[cfg(test)] mod tests { use super::*; - use craft_anything_testkit::formats as fx; + use crate::test_support::formats as fx; #[test] fn hex_signs_are_not_hex_digits() { @@ -796,8 +817,9 @@ mod tests { #[test] fn vyper_style_fallthrough() { // PUSH1 0 CALLDATALOAD PUSH1 0xe0 SHR PUSH1 0 MSTORE PUSH4 sel PUSH1 0 MLOAD EQ ISZERO PUSH2 next JUMPI - let mut c = - vec![0x60, 0x00, 0x35, 0x60, 0xe0, 0x1c, 0x60, 0x00, 0x52, 0x63, 0x12, 0x34, 0x56, 0x78, 0x60, 0x00, 0x51, 0x14, 0x15, 0x61, 0x00, 0x20, 0x57]; + let mut c = vec![ + 0x60, 0x00, 0x35, 0x60, 0xe0, 0x1c, 0x60, 0x00, 0x52, 0x63, 0x12, 0x34, 0x56, 0x78, 0x60, 0x00, 0x51, 0x14, 0x15, 0x61, 0x00, 0x20, 0x57, + ]; let body = c.len(); c.extend_from_slice(&[0x34, 0x15, 0x00]); let r = analyze(&c).unwrap(); @@ -835,14 +857,14 @@ mod tests { #[test] fn hostile_inputs_do_not_panic() { let (code, _) = fx::evm_runtime(); - for m in craft_anything_testkit::mutations(&code) { + for m in crate::test_support::mutations(&code) { let _ = analyze(&m); } for n in 0..code.len() { let _ = analyze(&code[..n]); } for seed in 0..200 { - let n = craft_anything_testkit::noise(seed, 300); + let n = crate::test_support::noise(seed, 300); let _ = analyze(&n); let _ = decode_input(&n, Encoding::Auto); } diff --git a/crates/evm/src/test_support.rs b/crates/evm/src/test_support.rs new file mode 100644 index 000000000..b31ace0a2 --- /dev/null +++ b/crates/evm/src/test_support.rs @@ -0,0 +1,99 @@ +pub mod formats { + pub const EVM_SELECTORS: [u32; 3] = [0xa905_9cbb, 0x70a0_8231, 0xd0e3_0db0]; + + /// Runtime bytecode with a compiler-style dispatcher, a fallback that reverts, two non-payable + /// functions (CALLVALUE check), one payable function, and a CBOR metadata tail (ipfs + solc 0.8.19). + /// Returns (bytecode, jump destinations of the three functions). + pub fn evm_runtime() -> (Vec, [usize; 3]) { + let mut c: Vec = vec![0x60, 0x80, 0x60, 0x40, 0x52]; + // if calldatasize < 4 goto fallback + c.extend_from_slice(&[0x60, 0x04, 0x36, 0x10, 0x61, 0, 0]); + let fb_patch = c.len() - 2; + c.push(0x57); + c.extend_from_slice(&[0x60, 0x00, 0x35, 0x60, 0xe0, 0x1c]); + let mut patches = Vec::new(); + for sel in EVM_SELECTORS { + c.push(0x80); + c.push(0x63); + c.extend_from_slice(&sel.to_be_bytes()); + c.extend_from_slice(&[0x14, 0x61, 0, 0]); + patches.push(c.len() - 2); + c.push(0x57); + } + let fallback = c.len(); + c.extend_from_slice(&[0x5b, 0x60, 0x00, 0x80, 0xfd]); + let mut dests = [0usize; 3]; + for (i, dest) in dests.iter_mut().enumerate() { + *dest = c.len(); + if i < 2 { + // JUMPDEST CALLVALUE DUP1 ISZERO PUSH2 ok JUMPI PUSH1 0 DUP1 REVERT JUMPDEST POP STOP + c.extend_from_slice(&[0x5b, 0x34, 0x80, 0x15, 0x61, 0, 0]); + let ok_patch = c.len() - 2; + c.extend_from_slice(&[0x57, 0x60, 0x00, 0x80, 0xfd]); + let ok = c.len(); + c.extend_from_slice(&[0x5b, 0x50, 0x00]); + c[ok_patch..ok_patch + 2].copy_from_slice(&(ok as u16).to_be_bytes()); + } else { + c.extend_from_slice(&[0x5b, 0x60, 0x01, 0x60, 0x00, 0x55, 0x00]); + } + } + c[fb_patch..fb_patch + 2].copy_from_slice(&(fallback as u16).to_be_bytes()); + for (p, d) in patches.iter().zip(dests) { + c[*p..*p + 2].copy_from_slice(&(d as u16).to_be_bytes()); + } + c.push(0xfe); + let mut meta = vec![0xa2, 0x64, b'i', b'p', b'f', b's', 0x58, 0x22, 0x12, 0x20]; + meta.extend((0..32u8).map(|i| i.wrapping_mul(7))); + meta.extend_from_slice(&[0x64, b's', b'o', b'l', b'c', 0x43, 0x00, 0x08, 0x13]); + let len = meta.len() as u16; + c.extend_from_slice(&meta); + c.extend_from_slice(&len.to_be_bytes()); + (c, dests) + } + + /// Bytecode as `0x`-prefixed lowercase hex. + pub fn to_hex(b: &[u8]) -> String { + let mut s = String::from("0x"); + for x in b { + s.push_str(&format!("{x:02x}")); + } + s + } +} +pub fn noise(seed: u64, len: usize) -> Vec { + let mut x = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1; + (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x as u8 + }) + .collect() +} +pub fn mutations(sample: &[u8]) -> Vec> { + let mut out = Vec::new(); + let n = sample.len(); + let step = (n / 64).max(1); + let mut len = 0; + while len < n { + out.push(sample[..len].to_vec()); + len += step; + } + for (i, seed) in (0..n).step_by(step).zip(1u64..) { + let mut m = sample.to_vec(); + let noise = noise(seed, 8); + for (j, v) in noise.iter().enumerate() { + if let Some(b) = m.get_mut(i + j) { + *b = *v; + } + } + out.push(m); + let mut m = sample.to_vec(); + if let Some(b) = m.get_mut(i) { + *b = 0xff; + } + out.push(m); + } + out +} diff --git a/crates/evm/tests/evm_metadata_map_keys.rs b/crates/evm/tests/evm_metadata_map_keys.rs index cfd108521..eed0fdfbd 100644 --- a/crates/evm/tests/evm_metadata_map_keys.rs +++ b/crates/evm/tests/evm_metadata_map_keys.rs @@ -1,4 +1,4 @@ -use craft_anything_formats::evm::analyze; +use craft_evm::analyze; fn contract_with_trailer(cbor: &[u8]) -> Vec { let mut code = vec![0x5b, 0x00]; From 383c52430ed0da0ef3a85ed251013efb8e431487 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 12:14:17 -0500 Subject: [PATCH 13/19] Separate EVM selector and calldata pattern inspection for lint gate --- crates/evm/src/lib.rs | 88 +++++++++++++++++++++++++------------------ 1 file changed, 51 insertions(+), 37 deletions(-) diff --git a/crates/evm/src/lib.rs b/crates/evm/src/lib.rs index 18104edcf..e85541eed 100644 --- a/crates/evm/src/lib.rs +++ b/crates/evm/src/lib.rs @@ -427,26 +427,9 @@ fn base58(b: &[u8]) -> String { s } -/// Analyse bytecode (already decoded from hex if needed). -pub fn analyze(code: &[u8]) -> Result { - if code.is_empty() { - return Err(FormatError::Truncated("no bytecode".into())); - } - if code.len() > MAX_CODE { - return Err(FormatError::TooLarge(format!("{} bytes; the limit is {MAX_CODE}", code.len()))); - } - if code.starts_with(&[0xef, 0x00]) { - return Err(FormatError::Unsupported("EVM Object Format (EOF, 0xEF00) containers are not analysed".into())); - } - let mut warnings = Vec::new(); - let (end, metadata) = split_metadata(code); - let body = code.get(..end).unwrap_or(code); - let ins = sweep(body); - let jumpdests = ins.iter().filter(|i| i.op == 0x5b).count(); +fn selector_extraction(body: &[u8], ins: &[Ins]) -> Option<(&'static str, usize)> { let at = |k: usize| ins.get(k); let op_at = |k: usize| at(k).map(|i| i.op); - let index_of = |off: usize| ins.binary_search_by_key(&off, |i| i.off).ok(); - // Selector extraction: CALLDATALOAD followed by SHR 224, DIV 2^224 or a 4-byte mask. let mut extraction: Option<(&'static str, usize)> = None; for (k, i) in ins.iter().enumerate() { @@ -479,6 +462,55 @@ pub fn analyze(code: &[u8]) -> Result { break; } } + extraction +} + +fn short_calldata_path(body: &[u8], ins: &[Ins], disp_start: usize) -> (bool, &'static str) { + let at = |k: usize| ins.get(k); + let op_at = |k: usize| at(k).map(|i| i.op); + // Short calldata path and receive(). + let mut short_calldata = false; + let mut receive = "not-detected"; + for (k, i) in ins.iter().enumerate().take(disp_start.saturating_add(64)) { + if i.op != 0x36 { + continue; + } + if op_at(k + 1) == Some(0x15) && at(k + 2).is_some_and(|p| is_push(p.op)) && op_at(k + 3) == Some(0x57) { + receive = "present"; + } + // LT pops the size first in PUSH 4, CALLDATASIZE, LT. + if k.checked_sub(1).and_then(at).is_some_and(|p| is_push(p.op) && imm_u64(body, p) == Some(4)) + && op_at(k + 1) == Some(0x10) + && at(k + 2).is_some_and(|p| is_push(p.op)) + && op_at(k + 3) == Some(0x57) + { + short_calldata = true; + } + } + (short_calldata, receive) +} + +/// Analyse bytecode (already decoded from hex if needed). +pub fn analyze(code: &[u8]) -> Result { + if code.is_empty() { + return Err(FormatError::Truncated("no bytecode".into())); + } + if code.len() > MAX_CODE { + return Err(FormatError::TooLarge(format!("{} bytes; the limit is {MAX_CODE}", code.len()))); + } + if code.starts_with(&[0xef, 0x00]) { + return Err(FormatError::Unsupported("EVM Object Format (EOF, 0xEF00) containers are not analysed".into())); + } + let mut warnings = Vec::new(); + let (end, metadata) = split_metadata(code); + let body = code.get(..end).unwrap_or(code); + let ins = sweep(body); + let jumpdests = ins.iter().filter(|i| i.op == 0x5b).count(); + let at = |k: usize| ins.get(k); + let op_at = |k: usize| at(k).map(|i| i.op); + let index_of = |off: usize| ins.binary_search_by_key(&off, |i| i.off).ok(); + + let extraction = selector_extraction(body, &ins); let disp_start = extraction.map(|(_, k)| k).unwrap_or(0); if extraction.is_none() { warnings.push("no selector extraction (CALLDATALOAD then SHR/DIV/AND) was seen; matches below are less certain".into()); @@ -592,26 +624,8 @@ pub fn analyze(code: &[u8]) -> Result { warnings.push("some destinations are not JUMPDESTs; those matches may be data, not dispatch".into()); } - // Short calldata path and receive(). - let mut short_calldata = false; - let mut receive = "not-detected"; + let (short_calldata, receive) = short_calldata_path(body, &ins, disp_start); let mut fallback = "unknown"; - for (k, i) in ins.iter().enumerate().take(disp_start.saturating_add(64)) { - if i.op != 0x36 { - continue; - } - if op_at(k + 1) == Some(0x15) && at(k + 2).is_some_and(|p| is_push(p.op)) && op_at(k + 3) == Some(0x57) { - receive = "present"; - } - // LT pops the size first in PUSH 4, CALLDATASIZE, LT. - if k.checked_sub(1).and_then(at).is_some_and(|p| is_push(p.op) && imm_u64(body, p) == Some(4)) - && op_at(k + 1) == Some(0x10) - && at(k + 2).is_some_and(|p| is_push(p.op)) - && op_at(k + 3) == Some(0x57) - { - short_calldata = true; - } - } if let Some(j) = last_jumpi && solc_like > 0 { From 51aadf525f9ac22ba0afbf127f83e17dacb8f8a8 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Tue, 17 Nov 2026 13:06:31 -0500 Subject: [PATCH 14/19] Share deterministic parser damage fixtures without changing their corpus Preserve the fixture helpers originally authored in Craft Anything testkit and extracted by FredApps for TAR. EVM and TAR now reuse craft-testkit with unchanged mutation sequences. Add sequence and stride regressions. Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Dylan M. Taylor --- Cargo.lock | 2 + crates/evm/Cargo.toml | 3 ++ crates/evm/src/test_support.rs | 38 +-------------- crates/tar/Cargo.toml | 3 ++ crates/tar/src/testkit.rs | 42 +--------------- crates/testkit/src/lib.rs | 1 + crates/testkit/src/sample_damage.rs | 74 +++++++++++++++++++++++++++++ 7 files changed, 85 insertions(+), 78 deletions(-) create mode 100644 crates/testkit/src/sample_damage.rs diff --git a/Cargo.lock b/Cargo.lock index d554ad256..d90e8532b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1885,6 +1885,7 @@ dependencies = [ name = "craft-evm" version = "0.1.0" dependencies = [ + "craft-testkit", "serde", "serde_json", "thiserror 2.0.21", @@ -3139,6 +3140,7 @@ dependencies = [ name = "craft-tar" version = "0.1.0" dependencies = [ + "craft-testkit", "serde", ] diff --git a/crates/evm/Cargo.toml b/crates/evm/Cargo.toml index 92d0abae8..018f5dff0 100644 --- a/crates/evm/Cargo.toml +++ b/crates/evm/Cargo.toml @@ -12,3 +12,6 @@ workspace = true serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } + +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/evm/src/test_support.rs b/crates/evm/src/test_support.rs index b31ace0a2..0dc9861ef 100644 --- a/crates/evm/src/test_support.rs +++ b/crates/evm/src/test_support.rs @@ -60,40 +60,4 @@ pub mod formats { s } } -pub fn noise(seed: u64, len: usize) -> Vec { - let mut x = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1; - (0..len) - .map(|_| { - x ^= x << 13; - x ^= x >> 7; - x ^= x << 17; - x as u8 - }) - .collect() -} -pub fn mutations(sample: &[u8]) -> Vec> { - let mut out = Vec::new(); - let n = sample.len(); - let step = (n / 64).max(1); - let mut len = 0; - while len < n { - out.push(sample[..len].to_vec()); - len += step; - } - for (i, seed) in (0..n).step_by(step).zip(1u64..) { - let mut m = sample.to_vec(); - let noise = noise(seed, 8); - for (j, v) in noise.iter().enumerate() { - if let Some(b) = m.get_mut(i + j) { - *b = *v; - } - } - out.push(m); - let mut m = sample.to_vec(); - if let Some(b) = m.get_mut(i) { - *b = 0xff; - } - out.push(m); - } - out -} +pub use craft_testkit::sample_damage::{mutations, noise}; diff --git a/crates/tar/Cargo.toml b/crates/tar/Cargo.toml index e0628a35a..e76bb9e4c 100644 --- a/crates/tar/Cargo.toml +++ b/crates/tar/Cargo.toml @@ -16,3 +16,6 @@ serde = { workspace = true, optional = true } [features] serde = ["dep:serde"] + +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/tar/src/testkit.rs b/crates/tar/src/testkit.rs index 828644a4b..f435b55e5 100644 --- a/crates/tar/src/testkit.rs +++ b/crates/tar/src/testkit.rs @@ -92,44 +92,4 @@ pub fn cpio_newc(files: &[(&str, &[u8], u32)]) -> Vec { out } -/// Deterministic pseudo-random bytes (xorshift) for fuzz-like loops. -pub fn noise(seed: u64, len: usize) -> Vec { - let mut x = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1; - (0..len) - .map(|_| { - x ^= x << 13; - x ^= x >> 7; - x ^= x << 17; - x as u8 - }) - .collect() -} - -/// Every way to damage a sample used by robustness tests: truncations at many lengths and -/// single-byte corruptions spread across the file. -pub fn mutations(sample: &[u8]) -> Vec> { - let mut out = Vec::new(); - let n = sample.len(); - let step = (n / 64).max(1); - let mut len = 0; - while len < n { - out.push(sample[..len].to_vec()); - len += step; - } - for (i, seed) in (0..n).step_by(step).zip(1u64..) { - let mut m = sample.to_vec(); - let noise = noise(seed, 8); - for (j, v) in noise.iter().enumerate() { - if let Some(b) = m.get_mut(i + j) { - *b = *v; - } - } - out.push(m); - let mut m = sample.to_vec(); - if let Some(b) = m.get_mut(i) { - *b = 0xff; - } - out.push(m); - } - out -} +pub use craft_testkit::sample_damage::{mutations, noise}; diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index 020938371..910f25518 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -39,6 +39,7 @@ pub mod deadline; pub mod guards; pub mod hostile; +pub mod sample_damage; #[cfg(not(target_arch = "wasm32"))] pub use deadline::{DeadlineLimit, wait_until, with_deadline}; diff --git a/crates/testkit/src/sample_damage.rs b/crates/testkit/src/sample_damage.rs new file mode 100644 index 000000000..33d9632bf --- /dev/null +++ b/crates/testkit/src/sample_damage.rs @@ -0,0 +1,74 @@ +//! Stable sampled truncations and corruptions for existing parser regression corpora. +//! +//! Unlike `hostile::mutations`, this preserves the historical TAR/EVM fixture sequence. + +/// Deterministic pseudo-random bytes (xorshift) for fuzz-like loops. +pub fn noise(seed: u64, len: usize) -> Vec { + let mut x = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1; + (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x as u8 + }) + .collect() +} + +/// Every way to damage a sample used by robustness tests: truncations at many lengths and +/// single-byte corruptions spread across the file. +pub fn mutations(sample: &[u8]) -> Vec> { + let mut out = Vec::new(); + let n = sample.len(); + let step = (n / 64).max(1); + let mut len = 0; + while len < n { + out.push(sample[..len].to_vec()); + len += step; + } + for (i, seed) in (0..n).step_by(step).zip(1u64..) { + let mut m = sample.to_vec(); + let noise = noise(seed, 8); + for (j, v) in noise.iter().enumerate() { + if let Some(b) = m.get_mut(i + j) { + *b = *v; + } + } + out.push(m); + let mut m = sample.to_vec(); + if let Some(b) = m.get_mut(i) { + *b = 0xff; + } + out.push(m); + } + out +} + +#[cfg(test)] +mod tests { + use super::{mutations, noise}; + + #[test] + fn fixture_sequence_stays_stable() { + assert_eq!(noise(1, 8), [173, 118, 54, 116, 236, 121, 207, 234]); + assert!(noise(1, 0).is_empty()); + assert!(mutations(&[]).is_empty()); + assert_eq!(mutations(&[42]), vec![vec![], vec![173], vec![255]]); + } + + #[test] + fn sampling_stride_preserves_truncation_and_corruption_order() { + let sample = vec![42; 128]; + let cases = mutations(&sample); + assert_eq!(cases.len(), 192); + for (index, prefix) in cases.iter().take(64).enumerate() { + assert_eq!(prefix, &sample[..index * 2]); + } + for (index, pair) in cases[64..].chunks_exact(2).enumerate() { + assert_eq!(pair[0].len(), sample.len()); + let mut expected = sample.clone(); + expected[index * 2] = 255; + assert_eq!(pair[1], expected); + } + } +} From 29fdd49d6d59e15a0e995ff1f16a289d86963b11 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 13:07:57 -0500 Subject: [PATCH 15/19] Use fixed-size chunks in fixture-order regression --- crates/testkit/src/sample_damage.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/testkit/src/sample_damage.rs b/crates/testkit/src/sample_damage.rs index 33d9632bf..f0bdec729 100644 --- a/crates/testkit/src/sample_damage.rs +++ b/crates/testkit/src/sample_damage.rs @@ -64,7 +64,7 @@ mod tests { for (index, prefix) in cases.iter().take(64).enumerate() { assert_eq!(prefix, &sample[..index * 2]); } - for (index, pair) in cases[64..].chunks_exact(2).enumerate() { + for (index, pair) in cases[64..].as_chunks::<2>().0.iter().enumerate() { assert_eq!(pair[0].len(), sample.len()); let mut expected = sample.clone(); expected[index * 2] = 255; From 17329ac50a6ff5452e2336d2ad684f94bfed2e82 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 14:09:45 -0500 Subject: [PATCH 16/19] Recognize extended metadata maps and track duplicate selector dispatch --- crates/evm/src/lib.rs | 6 ++++-- crates/evm/tests/evm_metadata_map_keys.rs | 25 +++++++++++++++++++++++ crates/evm/tests/evm_selector_dedup.rs | 14 +++++++++++++ 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/crates/evm/src/lib.rs b/crates/evm/src/lib.rs index e85541eed..502e451e1 100644 --- a/crates/evm/src/lib.rs +++ b/crates/evm/src/lib.rs @@ -283,7 +283,7 @@ fn split_metadata(code: &[u8]) -> (usize, Option) { } let start = n - 2 - len; let Some(cbor) = code.get(start..n - 2) else { return (n, None) }; - if !matches!(cbor.first(), Some(0xa1..=0xb7 | 0xbf)) { + if !matches!(cbor.first(), Some(0xa1..=0xb8 | 0xbf)) { return (n, None); } let mut pos = 0usize; @@ -583,6 +583,9 @@ pub fn analyze(code: &[u8]) -> Result { if n < 4 && extraction.is_none() { continue; } + // Duplicate identities still advance the end of the recognized dispatcher. + // Otherwise the fallback scan starts inside a later comparison, not after it. + last_jumpi = Some(jumpi_k); if !selectors.insert(sel) { continue; } @@ -592,7 +595,6 @@ pub fn analyze(code: &[u8]) -> Result { } else { vyper_like += 1; } - last_jumpi = Some(jumpi_k); let di = index_of(dest); let jumpdest_valid = pattern != "eq-jumpi" || di.and_then(at).is_some_and(|x| x.op == 0x5b); let (mutability, reason) = if !jumpdest_valid { diff --git a/crates/evm/tests/evm_metadata_map_keys.rs b/crates/evm/tests/evm_metadata_map_keys.rs index eed0fdfbd..17ee4822c 100644 --- a/crates/evm/tests/evm_metadata_map_keys.rs +++ b/crates/evm/tests/evm_metadata_map_keys.rs @@ -66,3 +66,28 @@ fn equal_keys_in_separate_maps_are_independent() { assert_eq!(entries["a"]["x"], 0); assert_eq!(entries["b"]["x"], 1); } + +#[test] +fn extended_length_metadata_maps_respect_the_pair_limit() { + let map = |count: u8| { + let mut cbor = vec![0xb8, count]; + for index in 0..count { + let key = format!("k{index:02}"); + cbor.push(0x63); + cbor.extend_from_slice(key.as_bytes()); + cbor.push(0); + } + cbor + }; + for count in [24, 32] { + let code = contract_with_trailer(&map(count)); + let report = analyze(&code).unwrap(); + assert_eq!(report.analysed_size, 2); + assert_eq!(report.metadata.unwrap().entries.as_object().unwrap().len(), usize::from(count)); + } + assert_unrecognized(&map(33)); + assert_unrecognized(&[0xb8]); + let mut truncated = map(24); + truncated.pop(); + assert_unrecognized(&truncated); +} diff --git a/crates/evm/tests/evm_selector_dedup.rs b/crates/evm/tests/evm_selector_dedup.rs index 8ce4b88a4..2761a23d3 100644 --- a/crates/evm/tests/evm_selector_dedup.rs +++ b/crates/evm/tests/evm_selector_dedup.rs @@ -68,3 +68,17 @@ fn selector_cap_counts_unique_matches() { assert_eq!(capped.functions.last().unwrap().selector, "0x00000fff"); assert!(capped.warnings.iter().any(|warning| warning == "stopped at 4096 selectors")); } + +#[test] +fn repeated_comparisons_keep_fallback_scan_after_the_last_dispatch() { + for (ending, expected) in [(&[0x5f, 0x5f, 0xfd][..], "absent"), (&[0x00][..], "present")] { + let mut code = prefix(); + comparison(&mut code, 0xfeed0001, 4, 0); + comparison(&mut code, 0xfeed0001, 4, 1); + code.extend_from_slice(ending); + let report = evm::analyze(&code).unwrap(); + assert_eq!(report.functions.len(), 1); + assert_eq!(report.functions[0].bytecode_offset, 0); + assert_eq!(report.fallback, expected); + } +} From 0ac2de52558cc27cb2cea15cc89e2e63f69d4153 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 15:49:47 -0500 Subject: [PATCH 17/19] Deduplicate JUMP destination resolution in the payability walkers --- crates/evm/src/lib.rs | 41 +++++++++++++++++++++-------------------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/crates/evm/src/lib.rs b/crates/evm/src/lib.rs index 502e451e1..2b1b089d5 100644 --- a/crates/evm/src/lib.rs +++ b/crates/evm/src/lib.rs @@ -677,6 +677,13 @@ pub fn analyze(code: &[u8]) -> Result { }) } +/// Resolve the destination of a JUMP to an instruction index, when the PUSH right before it is +/// readable and lands on an instruction boundary. +fn jump_destination(code: &[u8], ins: &[Ins], k: usize, index_of: &dyn Fn(usize) -> Option) -> Option { + let push = k.checked_sub(1).and_then(|p| ins.get(p)).filter(|p| is_push(p.op))?; + index_of(usize::try_from(imm_u64(code, push)?).ok()?) +} + /// Follow a function's entry for a few instructions (and up to two unconditional jumps) looking /// for a CALLVALUE check. fn payability(code: &[u8], ins: &[Ins], start: usize, index_of: &dyn Fn(usize) -> Option) -> (&'static str, String) { @@ -686,17 +693,14 @@ fn payability(code: &[u8], ins: &[Ins], start: usize, index_of: &dyn Fn(usize) - let Some(i) = ins.get(k) else { break }; match i.op { 0x34 if rejects_value(code, ins, k, index_of) => return ("nonpayable", format!("rejects nonzero CALLVALUE at {:#x}", i.off)), - 0x56 => { - let target = k.checked_sub(1).and_then(|p| ins.get(p)).filter(|p| is_push(p.op)).and_then(|p| imm_u64(code, p)); - match target.and_then(|t| index_of(usize::try_from(t).ok()?)) { - Some(t) if hops < 2 => { - hops += 1; - k = t; - continue; - } - _ => return ("unknown", "jumps somewhere we cannot follow before any CALLVALUE check".into()), + 0x56 => match jump_destination(code, ins, k, index_of) { + Some(t) if hops < 2 => { + hops += 1; + k = t; + continue; } - } + _ => return ("unknown", "jumps somewhere we cannot follow before any CALLVALUE check".into()), + }, 0x57 => return ("unknown", "branches before any CALLVALUE check".into()), 0xfd | 0xfe => return ("unknown", "halts with an error before any CALLVALUE check".into()), 0x00 | 0xf3 | 0xff | 0x35 | 0x37 | 0x54 | 0x55 | 0xf1 | 0xf4 | 0xfa | 0xa0..=0xa4 => { @@ -735,17 +739,14 @@ fn reverts_soon(code: &[u8], ins: &[Ins], mut k: usize, index_of: &dyn Fn(usize) let Some(i) = ins.get(k) else { return false }; match i.op { 0xfd | 0xfe => return true, - 0x56 => { - let target = k.checked_sub(1).and_then(|p| ins.get(p)).filter(|p| is_push(p.op)).and_then(|p| imm_u64(code, p)); - match target.and_then(|t| index_of(usize::try_from(t).ok()?)) { - Some(t) if hops < 2 => { - hops += 1; - k = t; - continue; - } - _ => return false, + 0x56 => match jump_destination(code, ins, k, index_of) { + Some(t) if hops < 2 => { + hops += 1; + k = t; + continue; } - } + _ => return false, + }, 0x5b | 0x50 | 0x80..=0x9f | 0x5f | 0x60..=0x7f => {} _ => return false, } From 65e38419d770ffdb67d6064a3baa391ad984d01b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 16:44:09 -0500 Subject: [PATCH 18/19] testkit: share the sampled-damage corpus with WASM and Java class --- Cargo.lock | 2 ++ crates/java-class/Cargo.toml | 2 ++ crates/java-class/src/test_support.rs | 42 +-------------------------- crates/wasm/Cargo.toml | 2 ++ crates/wasm/src/test_support.rs | 42 +-------------------------- 5 files changed, 8 insertions(+), 82 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4d32c4f1c..1fb437385 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2306,6 +2306,7 @@ dependencies = [ name = "craft-java-class" version = "0.1.0" dependencies = [ + "craft-testkit", "serde", "thiserror 2.0.21", ] @@ -3389,6 +3390,7 @@ dependencies = [ name = "craft-wasm" version = "0.1.0" dependencies = [ + "craft-testkit", "serde", "thiserror 2.0.21", "wasmparser 0.261.0", diff --git a/crates/java-class/Cargo.toml b/crates/java-class/Cargo.toml index 6dfbd16e5..1a5144fc3 100644 --- a/crates/java-class/Cargo.toml +++ b/crates/java-class/Cargo.toml @@ -11,3 +11,5 @@ workspace=true [dependencies] serde={workspace=true} thiserror={workspace=true} +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/java-class/src/test_support.rs b/crates/java-class/src/test_support.rs index 45853e807..e2e13ddbd 100644 --- a/crates/java-class/src/test_support.rs +++ b/crates/java-class/src/test_support.rs @@ -1,44 +1,4 @@ -/// Deterministic pseudo-random bytes (xorshift) for fuzz-like loops. -pub fn noise(seed: u64, len: usize) -> Vec { - let mut x = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1; - (0..len) - .map(|_| { - x ^= x << 13; - x ^= x >> 7; - x ^= x << 17; - x as u8 - }) - .collect() -} - -/// Every way to damage a sample used by robustness tests: truncations at many lengths and -/// single-byte corruptions spread across the file. -pub fn mutations(sample: &[u8]) -> Vec> { - let mut out = Vec::new(); - let n = sample.len(); - let step = (n / 64).max(1); - let mut len = 0; - while len < n { - out.push(sample[..len].to_vec()); - len += step; - } - for (i, seed) in (0..n).step_by(step).zip(1u64..) { - let mut m = sample.to_vec(); - let noise = noise(seed, 8); - for (j, v) in noise.iter().enumerate() { - if let Some(b) = m.get_mut(i + j) { - *b = *v; - } - } - out.push(m); - let mut m = sample.to_vec(); - if let Some(b) = m.get_mut(i) { - *b = 0xff; - } - out.push(m); - } - out -} +pub use craft_testkit::sample_damage::{mutations, noise}; pub mod java { use std::collections::HashMap; diff --git a/crates/wasm/Cargo.toml b/crates/wasm/Cargo.toml index c9a1cdcf3..ea07add48 100644 --- a/crates/wasm/Cargo.toml +++ b/crates/wasm/Cargo.toml @@ -13,3 +13,5 @@ serde = { workspace = true } thiserror = { workspace = true } wasmparser = { version = "0.261", default-features = false, features = ["std", "validate", "features", "component-model", "simd"] } wasmprinter = { version = "0.261", default-features = false, features = ["component-model"] } +[dev-dependencies] +craft-testkit = { workspace = true } diff --git a/crates/wasm/src/test_support.rs b/crates/wasm/src/test_support.rs index 58e7783a0..800f368fd 100644 --- a/crates/wasm/src/test_support.rs +++ b/crates/wasm/src/test_support.rs @@ -1,45 +1,5 @@ // Synthetic fixtures and mutations from Craft Anything testkit, same source revision. -/// Deterministic pseudo-random bytes (xorshift) for fuzz-like loops. -pub fn noise(seed: u64, len: usize) -> Vec { - let mut x = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1; - (0..len) - .map(|_| { - x ^= x << 13; - x ^= x >> 7; - x ^= x << 17; - x as u8 - }) - .collect() -} - -/// Every way to damage a sample used by robustness tests: truncations at many lengths and -/// single-byte corruptions spread across the file. -pub fn mutations(sample: &[u8]) -> Vec> { - let mut out = Vec::new(); - let n = sample.len(); - let step = (n / 64).max(1); - let mut len = 0; - while len < n { - out.push(sample[..len].to_vec()); - len += step; - } - for (i, seed) in (0..n).step_by(step).zip(1u64..) { - let mut m = sample.to_vec(); - let noise = noise(seed, 8); - for (j, v) in noise.iter().enumerate() { - if let Some(b) = m.get_mut(i + j) { - *b = *v; - } - } - out.push(m); - let mut m = sample.to_vec(); - if let Some(b) = m.get_mut(i) { - *b = 0xff; - } - out.push(m); - } - out -} +pub use craft_testkit::sample_damage::{mutations, noise}; pub mod formats { fn leb(mut v: u32, out: &mut Vec) { From 17f1b5d20fe9a25007682e25e7a7308e0f00af85 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 19:45:22 -0500 Subject: [PATCH 19/19] Keep uncertain EVM fallback and jump payability unknown --- crates/evm/src/lib.rs | 5 ++++- crates/evm/tests/evm_selector_dedup.rs | 31 ++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/crates/evm/src/lib.rs b/crates/evm/src/lib.rs index 2b1b089d5..29d254b40 100644 --- a/crates/evm/src/lib.rs +++ b/crates/evm/src/lib.rs @@ -628,7 +628,10 @@ pub fn analyze(code: &[u8]) -> Result { let (short_calldata, receive) = short_calldata_path(body, &ins, disp_start); let mut fallback = "unknown"; + // At the selector cap the remaining dispatcher has not been scanned. + // Its next comparison is not evidence that a fallback body exists. if let Some(j) = last_jumpi + && functions.len() < MAX_FUNCTIONS && solc_like > 0 { fallback = if reverts_soon(body, &ins, j + 1, &index_of) { "absent" } else { "present" }; @@ -694,7 +697,7 @@ fn payability(code: &[u8], ins: &[Ins], start: usize, index_of: &dyn Fn(usize) - match i.op { 0x34 if rejects_value(code, ins, k, index_of) => return ("nonpayable", format!("rejects nonzero CALLVALUE at {:#x}", i.off)), 0x56 => match jump_destination(code, ins, k, index_of) { - Some(t) if hops < 2 => { + Some(t) if hops < 2 && ins.get(t).is_some_and(|target| target.op == 0x5b) => { hops += 1; k = t; continue; diff --git a/crates/evm/tests/evm_selector_dedup.rs b/crates/evm/tests/evm_selector_dedup.rs index 2761a23d3..99aac44ba 100644 --- a/crates/evm/tests/evm_selector_dedup.rs +++ b/crates/evm/tests/evm_selector_dedup.rs @@ -82,3 +82,34 @@ fn repeated_comparisons_keep_fallback_scan_after_the_last_dispatch() { assert_eq!(report.fallback, expected); } } + +#[test] +fn selector_cap_leaves_fallback_unknown() { + for ending in [&[0x5f, 0x5f, 0xfd][..], &[0x00][..]] { + let mut code = prefix(); + for selector in 0..4097 { + comparison(&mut code, selector, 4, 0); + } + code.extend_from_slice(ending); + let report = evm::analyze(&code).unwrap(); + assert_eq!(report.functions.len(), 4096); + assert_eq!(report.fallback, "unknown"); + } +} + +#[test] +fn payability_only_follows_jumps_to_jumpdest() { + for (target, expected) in [(&[0x5b, 0x00][..], "payable"), (&[0x00][..], "unknown")] { + let mut code = prefix(); + let entry = u8::try_from(code.len() + 10).unwrap(); + comparison(&mut code, 0xfeed0001, 4, entry); + code.push(0x00); + assert_eq!(code.len(), usize::from(entry)); + code.extend([0x5b, 0x60, entry + 4, 0x56]); + code.extend_from_slice(target); + let report = evm::analyze(&code).unwrap(); + assert_eq!(report.functions.len(), 1); + assert!(report.functions[0].jumpdest_valid); + assert_eq!(report.functions[0].mutability, expected); + } +}