Skip to content

About

Replay a Sapper finding on your own machine with the engine and formats Sapper's Checkers use.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

60 Commits

Folders and files

Repository files navigation

sapper-replay

Replay a Sapper finding on your own machine and get the result hash Sapper's Checkers voted on.

Sapper's agents write every attack they find as a bundle: transactions sent from a fresh account with no privileges, on a fork of the chain pinned to one block. Before a bounty can settle, staked Checkers replay the bundle with this engine and its command line tool. Every replay starts from the same pinned state and measures the same values, so honest Checkers reach the same result hash. A bundle confirms only when it breaks a rule the contract's owner declared, or when the attacker ends up holding value the watched contract lost.

A replay runs on a local fork. It sends nothing to the live chain and needs no private key.

flowchart LR
  B[Bundle<br/>pinned block, attacker, calls, claim] --> F[Fresh fork<br/>at the pinned block]
  R[Declared rules] --> F
  F --> M[Measurement<br/>rules before and after,<br/>balances, transaction results]
  M --> H[Result hash]
  H --> V[Checker vote<br/>commit, then reveal]
Loading

Requirements

  • Bun 1.3 or later.
  • Foundry v1.8.1, for anvil. Checkers agree on result hashes only when they run the same Foundry release, so the engine refuses any other anvil.
  • An RPC endpoint for the bundle's chain that serves state at the bundle's pinned block: an archive node, unless the block is recent. The engine passes this URL to anvil on its command line, where any user on the machine can read it in the process list. Use a keyless URL, or one whose key grants access to nothing else.
git clone https://github.com/sapper-agents/sapper-replay
cd sapper-replay
bun install

Try it on a local chain

examples/ holds two bundles you can replay without an archive node. v1-bundle.json takes the fees of a contract whose fee recipient anyone can set, and breaks a rule in rules.json. v2-bundle.json deploys a vault whose initializer anyone can run again, then takes its 5 ETH. Both run on a fresh local anvil:

anvil                       # in a second terminal
forge build --root fixtures
bun examples/deploy.ts      # puts the version 1 target on the chain
bun src/cli.ts replay --bundle examples/v1-bundle.json --rules examples/rules.json --rpc http://127.0.0.1:8545
bun src/cli.ts replay --bundle examples/v2-bundle.json --rpc http://127.0.0.1:8545

Each replay prints "confirmed": true and exits 0. The contracts are vulnerable on purpose, so examples/deploy.ts runs only against a fresh local chain.

Replay a disclosed finding

When a finding on your contract is confirmed, Sapper seals a private disclosure to your disclosure key. It carries the finding's bundle as JSON (its bundle field), the measurement the Checkers agreed on, and a Foundry reproduction. Save the bundle as bundle.json and the rules you registered for the contract as rules.json, then replay with the version that computed the finding's hashes:

Version Replays findings for Bundles
v0.1.0 Sapper on Robinhood Chain, until 29 November 2026 version 1
v0.2.0 Sapper on Elysium, from 29 November 2026 versions 1 and 2

A finding from Robinhood Chain (v0.1.0)

git checkout v0.1.0 && bun install
bun src/cli.ts root --rules rules.json
bun src/cli.ts replay --bundle bundle.json --rules rules.json --rpc <archive rpc url> --tokens <watched tokens>
  • root prints the rules root. It equals the invariants root SapperScope holds for your contract.
  • replay forks the chain at the bundle's pinned block and prints the measurement. Its measurement.bundleHash equals the bundleHash that SapperSettlementGate.finding(findingId) returns, and its resultHash equals the resultHash the gate recorded when the Checkers reached consensus. The gate's address is in deployments/4663.json.
  • v0.1.0 measures watched tokens and rules in the order you give them, and the order changes the result hash. Pass --tokens as the token addresses the disclosed measurement lists in balances after eth, in that order, comma separated and without spaces, and keep rules.json in the order of the measurement's rules.
  • --rpc is required. The exit code is 0 when the claim is confirmed and 2 when it is not. Any other failure, such as an RPC that does not answer, ends with a stack trace and exit code 1: nothing was measured, so fix the cause and run it again.

git checkout main && bun install returns to the current engine.

A finding on Elysium (v0.2.0)

bun src/cli.ts hash --bundle bundle.json
bun src/cli.ts root --rules rules.json
bun src/cli.ts replay --bundle bundle.json --rules rules.json --rpc <archive rpc url> --tokens <watched tokens>

hash prints the bundle hash and root the rules root, the values Sapper recorded for the finding. replay puts watched tokens and rules in a fixed order itself, so pass them in any order. Command line lists every option.

Hashes in v0.1.0 and 0.2.0

A version 1 bundle has the same bundle hash in both versions, and a rules file both accept has the same root. Result hashes differ: 0.2.0 also records the watched contract's balances, lists watched tokens and rules in a fixed order, and counts a balance claim only when the watched contract lost what the attacker gained.

v0.1.0 also accepts four inputs that 0.2.0 refuses: deployer, deploy and setup keys in a version 1 bundle, which it drops; keys the rules format does not define, also dropped; an operand with both const and call, read as the call; and a constant with leading zeros, hashed as written.

Command line (0.2.0)

From a clone of this repository, run each command as bun src/cli.ts, which runs the version checked out. A project that installs the package runs the same commands as bunx sapper-replay.

bun src/cli.ts replay --bundle bundle.json [--rules rules.json] [--rpc <url>] [--tokens 0x..,0x.. ...]
                      [--prices prices.json] [--rated <Critical|High|Medium|Low>] [--duplicate]
                      [--finding 0x.. --checker 0x.. --salt 0x..] [--deadline <seconds>]
bun src/cli.ts hash --bundle bundle.json
bun src/cli.ts root --rules rules.json
{
  "confirmed": true,
  "passes": true,
  "reason": "rule assets-floor broken",
  "bundleHash": "0x…",
  "resultHash": "0x…",
  "rootCause": "0x…",
  "measurement": { "attackerFresh": true, "privileged": false, "txs": [], "rules": [], "balances": [], "target": [] }
}
  • Without --rpc, replay reads RPC_URL_<chainId> (RPC_URL_4663 for Robinhood Chain), then RPC_URL. It refuses an endpoint that serves a different chain from the bundle's.
  • --tokens takes watched token addresses separated by commas, in any case. Repeated flags add up: --tokens 0xa…,0xb… --tokens 0xc… watches all three. Each must have code at forkBlock or be a contract one of the bundle's deploy calls creates. Any other address is refused with exit code 1, because its balances would read as zero whatever the bundle does.
  • passes is the replay vote a Checker casts: the claim is confirmed and the replay never reached HyperCore.
  • The fork gives each request to the upstream 30 seconds and retries one that times out 3 times. A request that still fails stops the replay. --deadline stops the whole replay, and its fork, after that many seconds, from 1 to 99999 (900 by default). A signal (SIGINT, SIGTERM, or the SIGHUP a closing terminal sends) stops the fork before the command exits.
  • --finding, --checker and --salt add commitment, the value SapperCheckerNet.commit expects for this replay.
  • --prices rates the finding with the public rubric and adds rubric. With --rated, the severity the finding was rated at, the output adds the dispute ballot, and voteCommitment when the three values above are given. --duplicate marks the root cause as already found. Checkers vote on disputes from the Elysium release on.

A prices file gives each asset's dollar price and decimals, keyed by eth or a token address in any case:

{ "eth": { "usd": 3000, "decimals": 18 }, "0x…": { "usd": 1, "decimals": 6 } }

Exit codes

Code Meaning
0 The finding reproduces: passes is true. hash and root exit 0 once they print their value.
2 The finding does not reproduce, or the bundle is refused. That follows from the bundle and the chain at its pinned block, so running it again gives the same answer.
1 The replay could not run, and nothing was measured. Fix the cause and run it again.
129, 130, 143 SIGHUP, SIGINT or SIGTERM stopped the command, after stopping the fork.
  • A bundle the schema refuses prints one line on stdout, {"confirmed":false,"passes":false,"reason":"…"}, and exits 2 before any fork starts. That covers a malformed field, a version 2 form that is not canonical, a deployer that is the attacker and more than 24 calls. hash refuses such a bundle the same way.
  • Every other bundle is replayed, and the full result gives the reason it did not confirm, such as a reserved address, a privileged attacker, an attacker that is not fresh or a target without code. Its resultHash is the value Checkers vote on.
  • Exit code 1 is for what the operator supplies: command line arguments, the rules, --tokens and prices files, the RPC, anvil and the deadline. The error is one line on stderr. root exits 1 for a rules file it refuses.
  • v0.1.0 has its own exit codes, listed in A finding from Robinhood Chain (v0.1.0).

Rules

A rules file is a JSON array of rules, each a property the contract must keep. A rule compares two operands:

[
  {
    "id": "assets-floor",
    "description": "Vault assets never fall below the 12 ETH reserve",
    "lhs": { "call": { "target": "0x…", "fn": "totalAssets() view returns (uint256)", "args": [] } },
    "op": ">=",
    "rhs": { "const": "12000000000000000000" },
    "severity": "High"
  }
]
Field Required Value
id yes 2 to 64 lowercase letters, digits and hyphens, starting with a letter or digit. Unique within the file, since a claim names its rule by id.
description yes 4 to 240 characters.
lhs, rhs yes An operand.
op yes ==, !=, >=, <=, > or <.
severity no Critical, High, Medium or Low. The rubric rates a broken rule without one as High.

An operand is exactly one of these:

  • { "call": { "target": "0x…", "fn": "…", "args": [] } } reads a view function. fn is a function signature that returns exactly one value, and args holds one string per input, each valid for its type (true or false for a bool). A call that reverts counts as a broken rule.
  • { "const": "12000000000000000000" } is a constant: a decimal integer in a string, negative when it is compared with a signed return. It has no leading zeros: "012" and "-0" are refused, so one rule cannot have two roots.
  • { "probe": { … } } measures a Uniswap v4 pool, as the next section describes.

Every comparison is between integers. A bool return is 1 for true and 0 for false, and an address return is the address as a number, so a rule that pins an owner compares the call with the owner's address written in decimal. A rule or operand with a key not shown here, or an operand with more than one of call, const and probe, is refused.

The rules root is a sorted-pair keccak Merkle root over the keccak hash of each rule's canonical JSON (keys sorted, addresses lowercased), the layout OpenZeppelin's MerkleProof verifies.

Uniswap v4 hooks (0.2.0)

A hook can lose a pool's money without any view function changing. For those, an operand can be a probe: a number the engine measures by trading against the pool through a fixed helper contract.

{
  "probe": {
    "kind": "uniswap-v4",
    "measure": "withdrawable",
    "manager": "0x…",
    "pool": { "currency0": "0x0000000000000000000000000000000000000000", "currency1": "0x…", "fee": 3000, "tickSpacing": 60, "hooks": "0x…" },
    "hookData": "0x"
  }
}
measure Value
swap-shortfall What exact-input swaps in both directions paid beyond their input, plus what they received below the quote from quoter (Uniswap's V4Quoter).
withdrawable 1 when a full-range position comes out whole, 0 when removing it reverts.
hook-excess Pool currency the hook gained over two swaps and a full withdrawal beyond feeBps of the flow, valued in currency1.
swappable 1 when an exact-input swap in each direction completes.

Before the bundle runs, the engine places the probe at 0x5a99e70000000000000000000000000000000001, funds it, and seeds one full-range position per pool, creating the pool at a 1:1 price if it does not exist. Each measurement runs inside a call that reverts with its result, so it leaves no state behind. A replay whose rules use no probe skips all of this.

expandPack in src/packs.ts writes the four standard hook rules for a pool on Robinhood Chain or Elysium. They hash into the rules root like any other rule. The probe's bytecode is part of the engine: bun run build:v4 rebuilds it from src/v4/, and the tests check that the committed copy matches its source.

Bundles

Version 1

{
  "version": 1,
  "chainId": 4663,
  "target": "0x…",
  "forkBlock": 117461535,
  "attacker": "0x…",
  "calls": [
    { "to": "0x…", "data": "0x…", "value": "0" },
    { "create": "0x6080…", "data": "0x", "value": "1000000000000000000" }
  ],
  "claim": { "kind": "invariant", "invariantId": "assets-floor" }
}
  • chainId is the chain the target lives on. It is part of the bundle hash, so a finding claimed for one chain cannot be replayed against another.
  • target must have code at forkBlock, or, in version 2, once the deploy calls or the queued operation have run. A contract the attacker creates is never the target.
  • attacker must have no transactions, no code and none of the watched assets (ETH, each watched token and the claimed one) at forkBlock, and still have no code when its calls start. A chain accepts transactions only from accounts without code (EIP-3607), and nobody holds the key to an address a contract was created at, so the bundle does not confirm when anything that ran before the attacker's calls, such as a deploy call or the queued operation, created a contract at the attacker's address, even one that destroyed itself in the same transaction. It must not be the target's owner, pending owner, admin or default admin, its ERC-1967 proxy admin, or the owner of that admin.
  • The attacker starts with 1,000 ETH for gas and value, and nothing else. Every other asset has to be obtained inside the bundle.
  • Each call is one transaction, and call i is sent with nonce i. At most 24 calls. A call the node refuses to send, such as one whose value exceeds the attacker's balance or whose initcode is over the size limit, is recorded as rejected, the calls after it are not sent, and the bundle does not confirm.
  • claim is either a declared rule that held before the bundle and fails after it, or { "kind": "balance", "token": "eth" | "0x…" }. From 0.2.0 a balance claim confirms when the attacker ends with more of the asset, the watched contract ends with less of it (or the asset is the watched contract's own token), and no other asset the attacker holds fell.

Version 2 (0.2.0)

Version 2 adds one phase that runs before the attacker's calls, always from an account other than the attacker. A bundle carries one of the two.

Code that is not deployed yet. A check on code under review attacks contracts before they exist on chain:

{
  "version": 2,
  "chainId": 4663,
  "target": "0x…",
  "forkBlock": 124316004,
  "deployer": "0x…",
  "deploy": [
    { "create": "0x6080…", "data": "0x", "value": "0" },
    { "to": "0x…", "data": "0xc4d66de8…", "value": "0" }
  ],
  "attacker": "0x…",
  "calls": [{ "to": "0x…", "data": "0x…", "value": "0" }],
  "claim": { "kind": "invariant", "invariantId": "owner-fixed" }
}
  • deployer must have no transactions and no code at forkBlock, and must differ from attacker: a contract the attacker deployed would make the attacker its owner.
  • The deployer is funded with exactly the ETH its calls send, and sends them first, with nonces from 0, so contract addresses are known in advance. At most 32 deploy calls.
  • Every deploy call must succeed. Roles, rules and balances are measured from the deployed state.
  • No deploy call, and no log the deploy calls emit, may contain the attacker's address or the address of a contract its calls could create. A deployer can grant roles that no view function reveals.

An upgrade queued in a timelock. A setup names an operation pending in an OpenZeppelin TimelockController (v4.9 or v5):

{
  "version": 2,
  "chainId": 4663,
  "target": "0x…",
  "forkBlock": 124316004,
  "setup": {
    "timelock": "0x…",
    "targets": ["0x…"],
    "values": ["0"],
    "payloads": ["0x3659cfe6…"],
    "predecessor": "0x0000000000000000000000000000000000000000000000000000000000000000",
    "salt": "0x…",
    "executor": "0x…"
  },
  "attacker": "0x…",
  "calls": [{ "to": "0x…", "data": "0x…", "value": "0" }],
  "claim": { "kind": "invariant", "invariantId": "assets-floor" }
}
  • The operation must be pending at forkBlock (matched as schedule or scheduleBatch). Anything else is refused, so a setup can only apply what the timelock's proposers queued.
  • The engine moves time to the operation's ready timestamp and executes it from executor, which must hold EXECUTOR_ROLE. When that role is open to everyone, executor may be left out and a fixed setup account runs it.
  • An attacker holding any role on the timelock counts as privileged and cannot confirm, and so does an operation whose payloads or logs contain the attacker's address or the address of a contract its calls could create.

A bundle with neither phase must say "version": 1. One with a phase says "version": 2, which an engine that predates version 2 refuses, so no engine replays the attack without its phase.

Version 2 accepts one spelling of each replay, so the same replay cannot be resubmitted under another bundle hash. The hash covers the bundle's canonical JSON, so key order and whitespace never matter, and these forms hash the same as their plain spelling:

  • addresses in any case, checksummed or not, and predecessor and salt in any case;
  • a call without value, which is "0", and a call without data, which is "0x";
  • "data": "0x" on a create call, which is the same as leaving data out;
  • a whole JSON number written as 5.0 or 5e0, which JSON reads as 5.

These forms are refused: hex data, creation code or payloads with uppercase letters, a value with leading zeros ("007", "00"), a create call with non-empty data (append constructor arguments to the creation code), and any key the format does not define, at the top level or in claim, a call, a deploy call or setup.

Version 1 keeps the looser forms its existing hashes were computed from: hex in either case, values with leading zeros and data beside creation code (which the replay never sends) are hashed as written, and keys version 1 does not define are dropped before hashing, as v0.1.0 drops them.

Measurement and result hash

The result hash is the keccak hash of the measurement's canonical JSON. The measurement records:

  • the attacker's freshness and privileges;
  • deploy, the deployer's transactions, for a bundle with deploy calls, or setup, the queued operation, once it has run;
  • each transaction's status (success, reverted or rejected), gas and created address;
  • every rule before and after the bundle;
  • balances, the attacker's ETH and each watched token, and target, the watched contract's holdings of the same assets;
  • probes, the pools seeded for probe operands, when a rule uses one;
  • whether the claim is confirmed, and why;
  • hypercore, when the replay reached HyperCore.

A field whose condition does not hold is absent from the measurement.

Gas price and base fee are zero on the fork. Right after forking, the engine mines one empty block one second after the pinned block and measures from there, and transactions follow at one-second intervals. The measurement is therefore identical on every machine, and the fork works on Arbitrum Orbit chains such as Robinhood Chain, whose headers carry no blob fields.

Rules are listed in ascending order of their leaf hash, the value each contributes to the rules root, and assets as eth followed by token addresses in ascending order. The result does not depend on how the rules file or --tokens orders them.

HyperCore and evm_only (0.2.0)

On HyperEVM (chain 999), its testnet (998) and Elysium (99901), contracts can reach HyperCore through the read precompiles from 0x…0800 to 0x…08ff, the CoreWriter at 0x3333…3333 and the system address 0x2222…2222. A fork cannot copy HyperCore, so on those chains the engine traces every transaction and rule read, and lists any of those addresses it reached in hypercore. Such a replay can confirm on EVM state, but passes is false: Checkers vote it down, and the owner receives it as an advisory tagged evm_only. Forks of HyperEVM and of its testnet use their 30M large-block gas limit.

Use as a library

The engine runs on Bun. Install it from this repository:

bun add github:sapper-agents/sapper-replay
// bun replay.ts bundle.json rules.json [watched token ...]
import { bundle, fork, passes, replay, resultHash, ruleSet } from "@sapper-agents/replay";

const [bundlePath, rulesPath, ...watchTokens] = Bun.argv.slice(2);
const b = bundle.parse(await Bun.file(bundlePath!).json());
const rules = ruleSet.parse(await Bun.file(rulesPath!).json());

const lab = await fork({ upstream: process.env.RPC_URL!, block: b.forkBlock, chainId: b.chainId });
try {
  const measurement = await replay(lab, b, rules, watchTokens);
  console.log(passes(measurement), resultHash(measurement));
} finally {
  await lab.stop();
}

bundle.parse throws for a bundle the schema refuses. replay returns a measurement for every other refusal, with the reason in reason.

Tests

bun run fixtures
bun run typecheck
bun test

bun run fixtures compiles the test contracts and copies Uniswap's PoolManager and V4Quoter from Robinhood Chain into fixtures/out, checking each against its recorded code hash. Set RPC_URL_4663 to read them from another endpoint.

The suite seeds ten vulnerable contracts, one per common bug class (a re-runnable initializer, an unprotected setter, reentrancy, unbacked redemptions, signature replay, an unchecked underflow, an arbitrary external call, an unauthenticated delegatecall, a spot-price oracle and an upgrade that drops an access check), and seven vulnerable Uniswap v4 hooks. Each bug must reproduce from a fresh account, and a replay must give the same result hash on every fork. Privileged accounts and harmless bundles must never confirm, and version 1 bundle hashes must never move. The suite also replays examples/ with the commands in Try it on a local chain. These contracts exist only for testing: never deploy them outside a local test chain.

Related

License

MIT. See LICENSE.

About

Replay a Sapper finding on your own machine with the engine and formats Sapper's Checkers use.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages