Technical Overview¶
Audience: Researchers and developers who want to understand how Crucible works, why it was built this way, and how the pieces fit together.
Architectural Philosophy¶
Crucible's architecture is guided by four core design principles:
1. Separation of Exploit Logic from Infrastructure¶
Crucible isolates artifact collection and chain management from the core exploit logic. Researchers authoring attack plugins can focus exclusively on exploit mechanics (e.g., crafting calldata, invoking contracts, and asserting state changes) without managing underlying infrastructure. The framework abstracts away:
- Historical chain fork synchronization
- Transaction instrumentation (event and storage diff capture)
- Cross-run determinism verification
- Artifact packaging for publication
2. Default Determinism¶
Blockchain state forks inherently exhibit non-deterministic properties due to RPC provider variations, transaction ordering, and fluctuating gas prices. Crucible enforces deterministic execution by default through the following mechanisms:
- Fixed gas price (
--gas-price 0) to eliminate gas-based variability. - FIFO transaction ordering (
--order fifo) to bypass mempool sorting behavior. - Pinned fork blocks to ensure every run originates from an identical historical state.
- Static fork-block timestamps to eliminate time-dependent execution divergence.
- Auto-mine execution to resolve block timing variance.
These constraints ensure that unaltered execution paths yield identical artifacts across successive runs.
3. Transparent and Universal Instrumentation¶
A significant source of friction in blockchain security research is the overhead of instrumenting transaction logic to capture execution traces. Crucible utilizes an RPC proxy layer that intercepts communication between the attack execution and the local chain fork.
This proxy architecture enables universal artifact capture (gas profiles, event emissions, storage diffs, and balance changes) regardless of the attack's implementation language or tooling (e.g., Python, forge script, or cast), without requiring explicit instrumentation code within the attack logic.
4. Self-Validating Publication Artifacts¶
Every experiment run generates a standardized, self-validating artifact bundle. These bundles employ SHA-256 hashing to ensure data integrity and include comprehensive run manifests that capture the execution provenance (git commit hash, Foundry version, and configuration fingerprint). Furthermore, automated fidelity enforcers verify that the empirical behavior of the run aligns with its declared reproducibility level.
Architecture at a Glance¶
flowchart TD
subgraph L4 ["CLI Layer"]
A["crucible/commands/ (20 modules)<br>Thin wrappers, zero business logic"]
end
subgraph L3 ["Orchestration Layer"]
B["ExperimentRunner, ScenarioEngine, BaselineManager<br>PublicationGate, HistoryIndex, ExportBundle<br>FidelityEnforcer, CheckpointManager"]
end
subgraph L2 ["Runtime Layer"]
C["ChainManager, PluginRegistry, JsonRpcClient<br>RpcProxy, BridgeLifecycle, LLMAgentPlugin<br>RpcProviderManager"]
end
subgraph L1 ["Foundation Layer"]
D["config.py, sdk.py, logging.py, errors.py<br>provenance.py, evidence.py, hashing.py, filesystem.py<br>env.py, ids.py, utils.py"]
end
L4 --> L3
L3 --> L2
L2 --> L1
Layer Rules¶
| Layer | Imports From | Responsibility |
|---|---|---|
| CLI (L4) | All lower layers | Command parsing, delegation — zero business logic |
| Orchestration (L3) | L2, L1 | Coordinates multi-step workflows, manages state transitions |
| Runtime (L2) | L1 only | Manages external processes (Anvil), I/O, plugin lifecycle |
| Foundation (L1) | stdlib only | No upward imports, no external process dependencies |
Core Concepts¶
Experiment¶
An experiment is a YAML file that wires together a topology, scenario, and attack plugin:
# experiments/nomad_replay.yaml
name: nomad_replay
scenario: nomad_pre_exploit
attack: nomad_replica_fraud
topology: single
Running crucible experiment run experiments/nomad_replay.yaml triggers the full experiment lifecycle: fork chains → validate evidence → deploy bridge → run scenario steps → start instrumentation → execute attack → verify fidelity → capture artifacts.
Topology¶
A topology declares which chains to fork and (optionally) which bridge plugin to deploy:
Topologies are reusable — the same attack can run on different topologies without modification. Adding a new chain config doesn't affect existing experiments.
Scenario¶
A scenario defines the chain environment before the attack runs — contract state, impersonated accounts, initial conditions:
# scenarios/nomad_pre_exploit/scenario.yaml
phases:
- name: setup
steps:
- type: log
message: "Setting up Nomad Replica contract state"
- type: impersonate
chain: ethereum
account: "0x..."
- type: send_tx
chain: ethereum
to: "0xB92..."
data: "0x..."
Scenarios use a registry-based step dispatcher — each step type (log, send_tx, impersonate, forge_script, assert_balance, etc.) is registered via a decorator. New step types can be added without modifying the engine.
Attack Plugin¶
An attack plugin is a Python class that subclasses AttackPlugin and implements:
class MyExploit(AttackPlugin):
def execute(self, context, phase=None):
# Forge calldata, send transactions, check results
return AttackResult(success=True, ...)
def verify(self, context):
# Check on-chain state matches expectations
return VerificationResult(passed=True, ...)
The plugin receives an ExperimentContext through which it accesses chain state (context.chains.runtime_for("ethereum") → JsonRpcClient), logs events, and reads configuration.
Evidence¶
Every attack plugin must include an evidence.yaml that documents:
- Incident metadata — name, date, affected bridge, damage
- Sources — advisories, postmortems, transaction explorers
- Historical scope — chains, fork blocks, exploit transactions, affected contracts
- Reproduction scope — fidelity level (L0–L4), modeled components, excluded components
- Acceptance criteria — required assertions that must pass
Evidence is validated against live chain state before every run — fork blocks are checked via eth_getBlockByNumber, contract addresses via eth_getCode.
Fidelity Levels¶
The L0–L4 fidelity system is enforced at runtime, not just documented. Each level has specific requirements:
| Level | Name | Requirements | Runtime Checks |
|---|---|---|---|
| L0 | Narrative | Description | None |
| L1 | Conceptual | Plugin returns a result | Result exists |
| L2 | Fork-State | Chains + contracts verified | Trace artifacts exist, chains match topology |
| L3 | Exact Replay | Exploit transactions declared | Transaction actions in run.jsonl |
| L4 | Multi-Chain | 2+ chains, bridge, excluded_components | Cross-chain artifacts, bridge plugin loaded |
Instrumentation Proxy¶
The instrumentation proxy is a transparent HTTP proxy that sits between the attack plugin and Anvil:
After every eth_sendTransaction, the proxy automatically:
- Polls
eth_getTransactionReceiptto get the receipt (gas used, logs) - Calls
debug_traceTransactionwithprestateTracerindiffModeto get storage diffs and balance changes - Emits all data to JSONL artifact streams
The attack plugin never knows it's being instrumented. ChainManager.runtime_for() silently returns the proxy URL instead of the direct Anvil URL.
Data Flow: Experiment Lifecycle¶
Phase 1: Setup¶
- Load config —
testbed.yaml+testbed.local.yaml→ Pydantic-validatedTestbedConfig - Load experiment YAML — topology, scenario, attack plugin specified
- Auto-merge fork blocks — if evidence.yaml specifies a different fork block, update config automatically
- Verify Foundry version — check
forge --versionagainstrequired_version - Run publication gates — if in publication mode, check evidence completeness, baseline existence, git provenance
- Execute scenario — chain forking starts here. The scenario engine executes YAML steps (log, impersonate, send_tx, forge_script, etc.)
Phase 2: Instrumentation¶
ExperimentRunner → ChainManager.start_instrumentation()
→ RpcProxy (per chain)
→ HTTPServer on random port
→ ThreadPoolExecutor (max 10 workers)
Each chain gets its own proxy instance with its own handler class (via _make_handler() closure). The proxy:
- Forwards all JSON-RPC requests to Anvil
- Detects
eth_sendTransaction/eth_sendRawTransaction - Schedules background trace tasks via
ThreadPoolExecutor
Phase 3: Attack Execution¶
ExperimentRunner → PluginRegistry.load("attack", name)
→ AttackPlugin.run(context)
→ AttackPlugin.execute(context)
→ eth_sendTransaction (via proxy URL)
→ Proxy captures: gas, events, storage diffs, balance diffs
The attack plugin interacts with the chain through context.chains.runtime_for("ethereum").rpc_url, which points to the proxy, not directly to Anvil. Every transaction is automatically instrumented.
Phase 4: Teardown¶
ExperimentRunner → ChainManager.stop_instrumentation()
→ Proxy.drain() — wait for pending traces
→ Proxy.stop() — shutdown HTTP server
→ LogManager.write_report()
→ LogManager.write_integrity()
→ FidelityEnforcer.check()
→ write run_manifest.json
The shutdown sequence is critical: drain() must be called before stop() and before log handles close. This ensures all async trace tasks complete before artifacts are finalized.
Configuration System¶
Configuration Hierarchy¶
.env ↠RPC URLs, secrets
↓ load_dotenv()
testbed.yaml ↠Committed to git (base config)
↓
testbed.local.yaml ↠Gitignored (per-user overrides)
↓ deep_merge()
↓ expand_env()
↓ Pydantic model_validate()
→ TestbedConfig
Key Config Models¶
class TestbedConfig:
workspace: str
active_topology: str
foundry: FoundryConfig
publication: PublicationConfig
chains: dict[str, ChainConfig] # Per-chain configuration
rpc_providers: dict[str, list] # Per-chain RPC failover list
fork_cache: ForkCacheConfig
logging: LoggingConfig
cleanup: CleanupConfig
rpc_budget: RpcBudgetConfig
notifications: NotificationConfig
class ChainConfig:
rpc_url: str
fork_block: int | None # None = blank fork (no remote)
chain_id: int
port: int
host: str
determinism: DeterminismConfig
class DeterminismConfig:
gas_price: int = 0
block_base_fee: int = 1_000_000_000
timestamp: int | Literal["fork_block"] = "fork_block"
auto_mine: bool = True
order: str = "fifo"
Built-In Validations¶
- Port uniqueness — no two chains can share a port
- Chain ID uniqueness — no two chains can share a chain_id
- Port range — must be 1–65535
- Matrix detection —
load_experiment()rejects matrix files with a helpful error message
Key Design Decisions¶
CLI-First Architecture¶
Every action is available via crucible <command>. The Streamlit dashboard is a separate read-only viewer. This makes experiments scriptable, Docker-friendly, and automatable.
Topology-Driven Composition¶
Topology YAML files declare which chains to fork. The same attack can run on different topologies. Adding a new chain config doesn't affect existing experiments.
Transparent Instrumentation¶
The proxy intercepts all RPC traffic. Researchers never add logging code. Any attack method (Python, Forge, cast send) produces complete artifacts.
Snapshot-Driven Reset¶
Baselines are captured once after setup. Soft resets use anvil_loadState — no chain restart needed. This enables fast iteration during development.
Determinism by Default¶
Deterministic flags are opt-out, not opt-in. If a researcher does nothing, their experiments are deterministic.
Plugins for Capabilities¶
New functionality arrives as plugins, not core rewrites:
- attack — exploit reproductions
- bridge — bridge protocol simulation
- agent — LLM-driven autonomous agents
Fidelity Levels Are Enforced¶
The L0–L4 fidelity system isn't just documentation — publication gates and runtime enforcers check requirements programmatically.
Separation of Scenario and Experiment¶
Scenarios define environments (chain state, setup). Experiments pair a scenario + attack plugin for formal runs. The same scenario can be used with different attacks, and the same attack can run against different scenarios.
Plugin System¶
Three Plugin Types¶
| Type | Base Class | Purpose | Lifecycle |
|---|---|---|---|
| Attack | AttackPlugin |
Exploit reproduction | prepare() → execute() → verify() → rollback() → cleanup() |
| Bridge | BridgePlugin |
Cross-chain simulation | deploy() → configure() → connect() → send_message() → reset() → destroy() |
| Agent | AgentPlugin |
LLM-driven agents | prepare() → observe() → think() → respond() (loop) → verify() |
Discovery¶
Plugins are discovered from attacks/, bridges/, and plugins/ directories. Each plugin must include a plugin.yaml manifest:
name: nomad_replica_fraud
version: 1.0.0
type: attack
entry: nomad_replica_fraud.py
class: NomadReplicaFraud
Attack plugins must also include evidence.yaml. The registry validates evidence structure during discovery.
ExperimentContext¶
Every plugin method receives an ExperimentContext through which it accesses:
- Chain state —
context.chains.runtime_for("ethereum")→JsonRpcClient - Logging —
context.log.step("message"),context.log.event(...) - Configuration —
context.config.chains["ethereum"].fork_block - Bridges —
context.bridge_plugin.send_message(...)(if bridge plugin deployed)
Chain Management¶
Anvil Subprocess Lifecycle¶
Configured → Starting (Popen) → WaitingReady (poll eth_blockNumber)
→ Running → Instrumented (proxy attached)
→ Draining (flush traces) → Running → Stopped
Blank Fork Mode¶
When fork_block: null, Anvil starts without --fork-url as a standalone local EVM. This enables:
- Fully offline operation — no RPC provider needed
- Instant startup — <1 second instead of 30s–5min
- Full determinism — no archive state variability
- CI/hermetic testing — zero external dependencies
The instrumentation proxy works identically in both modes — no code changes needed.
3-Tier Reset¶
| Tier | Method | Speed | Use Case |
|---|---|---|---|
| Soft | anvil_loadState snapshot |
<5s | Matrix runs, parameter sweeps |
| Medium | Kill → restart → restore | <30s | After process corruption |
| Hard | Re-fork from archive RPC | <5min | After cache corruption, topology change |
Artifact System¶
7 JSONL Streams¶
| Stream | Content | Source |
|---|---|---|
run.jsonl |
Experiment lifecycle events | LogManager.step() |
events.jsonl |
Contract events (Transfer, Approval, etc.) | Proxy via LogEmitter.event() |
storage_diffs.jsonl |
Storage slot changes (contract, slot, before, after) | Proxy via LogEmitter.storage_diff() |
gas_profile.jsonl |
Gas used per transaction | Proxy via LogEmitter.gas() |
balance_diffs.jsonl |
ETH/token balance changes | Proxy via LogEmitter.balance_diff() |
cross_chain.jsonl |
Bridge message correlation IDs | LogEmitter.cross_chain() |
agent_reasoning.jsonl |
LLM agent reasoning traces | LLMAgentPlugin._log_reasoning_step() |
Log Directory Structure¶
logs/
nomad_replay/
DS-2026-00042/ ↠Run directory
run.jsonl ↠Lifecycle events
run_manifest.json ↠Provenance + outcome
log_integrity.json ↠SHA-256 hashes
report.md ↠Human-readable summary
chain_ethereum/ ↠Per-chain artifacts
events.jsonl
gas_profile.jsonl
storage_diffs.jsonl
balance_diffs.jsonl
chain_bsc/
...
bridge/
cross_chain.jsonl
Integrity Verification¶
Every run produces a log_integrity.json with SHA-256 hashes of all artifact files, and an artifact_bundle_manifest.json with hashes of all run files. These enable crucible verify <run-id> to detect tampering or data corruption.
Fidelity Enforcement¶
Fidelity enforcement runs after the attack executes but before the run manifest is written. This means the manifest reflects the fidelity check outcome.
The FidelityEnforcer runs cumulative checks:
- L0 — Always passes (narrative only)
- L1 — Verifies the plugin returned a result
- L2 — Verifies chains match topology, trace artifacts exist, no auto-trace failures
- L3 — Verifies exploit transactions declared, transaction actions in run.jsonl
- L4 — Verifies 2+ chains, bridge plugin loaded, excluded_components declared
Docker Architecture¶
Two Operational Modes¶
| Mode | Command | When to Use |
|---|---|---|
| Single-container | docker compose run orchestrator ... |
Most experiments — Anvil runs inside orchestrator |
| Daemon + orchestrator | docker compose up -d anvil-ethereum && docker compose run orchestrator ... |
Multi-session workflows |
Container Composition¶
orchestrator — Python 3.12 + Foundry + uv | Entrypoint: uv run crucible
dashboard — Streamlit UI | Port 8501
anvil-ethereum — Foundry Anvil daemon | Port 8545
anvil-polygon — Foundry Anvil daemon | Port 8546
anvil-bsc — Foundry Anvil daemon | Port 8547
anvil-harmony — Foundry Anvil daemon | Port 8548
Named volumes (states_data, logs_data) persist chain state and experiment artifacts across container restarts.
See Also¶
| Doc | What It Covers |
|---|---|
| Architecture Deep Dive | Complete component map, all 39 modules |
| Design Decisions | Key tradeoffs and rationale |
| Instrumentation Architecture | RPC proxy design in detail |
| Plugin Development Guide | Writing attack, bridge, and agent plugins (in website/) |
| Fidelity Guide | L0–L4 fidelity levels and enforcement |
| Reproducibility Guide | Provenance, determinism, bug log |