Merge pull request #2070 from storytold/feat/evm-inspection

Share read-only EVM bytecode and compiler metadata inspection
This commit is contained in:
Dylan M. Taylor authored and GitHub committed 2026-11-17 20:42:58 -05:00
commit 8cbe36c113
18 files changed
+1332 -123

No files matched your search

+4
View File
@@ -158,6 +158,10 @@ Sanitization, animation fitting and numeric output policy remain caller-owned.
`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.
## XFDF field reader
`crates/xfdf` extracts PDFCraft field reading from #5937 refresh `cb564fd827f572818e9ddb0ea5989a432b1f39fd` (MIT OR Apache-2.0). App-side annotation and form policy remains local; source history is retained in the original repository.
Generated
+13
View File
@@ -1912,6 +1912,16 @@ dependencies = [
"zip 9.1.3",
]
[[package]]
name = "craft-evm"
version = "0.1.0"
dependencies = [
"craft-testkit",
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-ews"
version = "0.1.0"
@@ -2296,6 +2306,7 @@ dependencies = [
name = "craft-java-class"
version = "0.1.0"
dependencies = [
"craft-testkit",
"serde",
"thiserror 2.0.21",
]
@@ -3188,6 +3199,7 @@ dependencies = [
name = "craft-tar"
version = "0.1.0"
dependencies = [
"craft-testkit",
"serde",
]
@@ -3378,6 +3390,7 @@ dependencies = [
name = "craft-wasm"
version = "0.1.0"
dependencies = [
"craft-testkit",
"serde",
"thiserror 2.0.21",
"wasmparser 0.261.0",
+1
View File
@@ -11,6 +11,7 @@ rust-version = "1.95"
repository = "https://github.com/storytold/craft-libs"
[workspace.dependencies]
craft-evm = { path = "crates/evm" }
craft-java-class = { path = "crates/java-class" }
craft-sourcemap = { path = "crates/sourcemap" }
craft-pcap = { path = "crates/pcap" }
+17
View File
@@ -0,0 +1,17 @@
[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 }
[dev-dependencies]
craft-testkit = { workspace = true }
+7
View File
@@ -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.
+895
View File
@@ -0,0 +1,895 @@
#![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 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;
/// 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<u8>, &'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<String>,
pub ipfs: Option<String>,
pub swarm: Option<String>,
}
#[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<EvmMetadata>,
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<usize>,
/// `solc-like`, `vyper-like`, `mixed` or `none`.
pub style: &'static str,
pub functions: Vec<EvmFunction>,
/// 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<String>,
pub warnings: Vec<String>,
}
fn sweep(code: &[u8]) -> Vec<Ins> {
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<u64> {
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<EvmMetadata>) {
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..=0xb8 | 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<u64> {
let take = |pos: &mut usize, k: usize| -> Option<u64> {
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,
}
}
/// 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<Value> {
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(std::str::from_utf8(s).ok()?) } else { Value::from(bytes_value(s)) })
}
4 => {
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)?);
}
Some(Value::Array(items))
}
5 => {
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 {
// 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" | "vyper", Value::Array(items)) if items.len() == 3 && items.iter().all(Value::is_u64) => {
Value::from(items.iter().map(|v| v.to_string()).collect::<Vec<_>>().join("."))
}
("solc", Value::String(s)) if s.starts_with("0x") && s.len() == 8 => {
let d: Vec<u8> = (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("")))),
_ => 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
}
/// One byte from two hex digits; `from_str_radix` alone would also accept a leading `+`.
fn hex_byte(pair: &str) -> Option<u8> {
if pair.bytes().all(|c| c.is_ascii_hexdigit()) { u8::from_str_radix(pair, 16).ok() } else { None }
}
fn hex_decode(s: &str) -> Vec<u8> {
(0..s.len() / 2).filter_map(|i| hex_byte(s.get(2 * i..2 * i + 2)?)).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<u8> = 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
}
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);
// 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 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,
};
if let Some(kind) = kind {
extraction = Some((kind, k));
break;
}
}
if extraction.is_some() {
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<EvmInterface, FormatError> {
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());
}
// 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<EvmFunction> = Vec::new();
let mut selectors = BTreeSet::new();
let mut splits = 0usize;
let mut last_jumpi: Option<usize> = 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<usize> {
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 …
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();
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;
}
// 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;
}
let selector = format!("0x{sel:08x}");
if pattern == "eq-jumpi" {
solc_like += 1;
} else {
vyper_like += 1;
}
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 {
("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 {
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());
}
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" };
}
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,
})
}
/// 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<usize>) -> Option<usize> {
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<usize>) -> (&'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 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 && ins.get(t).is_some_and(|target| target.op == 0x5b) => {
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 => {
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())
}
/// 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<usize>) -> 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<usize>) -> 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 => 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,
}
k += 1;
}
false
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_support::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() {
// 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();
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::<Vec<_>>());
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 <body: CALLVALUE ...>
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, "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]
fn hostile_inputs_do_not_panic() {
let (code, _) = fx::evm_runtime();
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 = crate::test_support::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]);
}
}
+63
View File
@@ -0,0 +1,63 @@
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<u8>, [usize; 3]) {
let mut c: Vec<u8> = 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 use craft_testkit::sample_damage::{mutations, noise};
+39
View File
@@ -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());
}
+93
View File
@@ -0,0 +1,93 @@
use craft_evm::analyze;
fn contract_with_trailer(cbor: &[u8]) -> Vec<u8> {
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);
}
#[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);
}
+115
View File
@@ -0,0 +1,115 @@
use craft_evm as evm;
fn prefix() -> Vec<u8> {
vec![0x5b, 0x00, 0x60, 0x00, 0x35, 0x60, 0xe0, 0x1c]
}
fn comparison(code: &mut Vec<u8>, 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"));
}
#[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);
}
}
#[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);
}
}
+2
View File
@@ -11,3 +11,5 @@ workspace=true
[dependencies]
serde={workspace=true}
thiserror={workspace=true}
[dev-dependencies]
craft-testkit = { workspace = true }
+1 -41
View File
@@ -1,44 +1,4 @@
/// Deterministic pseudo-random bytes (xorshift) for fuzz-like loops.
pub fn noise(seed: u64, len: usize) -> Vec<u8> {
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<Vec<u8>> {
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;
+3
View File
@@ -16,3 +16,6 @@ serde = { workspace = true, optional = true }
[features]
serde = ["dep:serde"]
[dev-dependencies]
craft-testkit = { workspace = true }
+1 -41
View File
@@ -92,44 +92,4 @@ pub fn cpio_newc(files: &[(&str, &[u8], u32)]) -> Vec<u8> {
out
}
/// Deterministic pseudo-random bytes (xorshift) for fuzz-like loops.
pub fn noise(seed: u64, len: usize) -> Vec<u8> {
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<Vec<u8>> {
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};
+1
View File
@@ -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};
+74
View File
@@ -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<u8> {
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<Vec<u8>> {
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..].as_chunks::<2>().0.iter().enumerate() {
assert_eq!(pair[0].len(), sample.len());
let mut expected = sample.clone();
expected[index * 2] = 255;
assert_eq!(pair[1], expected);
}
}
}
+2
View File
@@ -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 }
+1 -41
View File
@@ -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<u8> {
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<Vec<u8>> {
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<u8>) {