Crucible Architecture¶
Version: 0.4.0 · Last Updated: June 2026 · Audience: Developers, contributors, reviewers
1. System Overview¶
graph TD
subgraph Inputs
YAML["Experiment YAML"]
TOPO["Topology YAML"]
ATTACK["Attack Plugin"]
end
subgraph Crucible
ER["Experiment Runner"]
CM["Chain Manager"]
SE["Scenario Engine"]
IP["Instrumentation Proxy"]
LM["Log Manager"]
end
subgraph External
ANVIL["Anvil Fork"]
RPC["Archive RPC"]
end
subgraph Outputs
LOGS["7 JSONL Streams"]
REPORT["report.md"]
MANIFEST["run_manifest.json"]
INTEGRITY["log_integrity.json"]
end
YAML --> ER
TOPO --> ER
ATTACK --> ER
ER --> CM
ER --> SE
CM --> ANVIL
ANVIL --> RPC
CM --> IP
IP --> LM
LM --> LOGS
LM --> REPORT
ER --> MANIFEST
LM --> INTEGRITY
Core principle: The researcher writes exploit logic. Crucible handles everything else - chain forking, instrumentation, artifact capture, integrity hashing, and provenance tracking.
2. Layered Architecture¶
Crucible is organized into four dependency layers. Each layer only imports from layers below it.
graph TB
subgraph "Layer 4 - CLI"
CLI["cli.py"]
CMD["commands/ (20 modules)"]
end
subgraph "Layer 3 - Orchestration"
ER["ExperimentRunner"]
SE["ScenarioEngine"]
BM["BaselineManager"]
CP["CheckpointManager"]
PG["PublicationGate"]
HI["HistoryIndex"]
EX["ExportBundle"]
end
subgraph "Layer 2 - Runtime"
CM["ChainManager"]
PR["PluginRegistry"]
RPC["JsonRpcClient"]
RPM["RpcProviderManager"]
IP["RpcProxy"]
BL["BridgeLifecycle"]
AL["LLMAgentPlugin"]
end
subgraph "Layer 1 - Foundation"
SDK["sdk.py"]
CFG["config.py"]
LOG["logging.py"]
ERR["errors.py"]
PROV["provenance.py"]
EV["evidence.py"]
HASH["hashing.py"]
FS["filesystem.py"]
ENV["env.py"]
IDS["ids.py"]
end
CLI --> CMD
CMD --> ER
CMD --> CM
ER --> SE
ER --> CM
ER --> BM
ER --> PR
ER --> PG
ER --> HI
ER --> CP
ER --> BL
ER --> LOG
SE --> CM
CM --> IP
CM --> RPC
PR --> SDK
BM --> CM
PG --> PROV
PG --> EV
EX --> HASH
AL --> SDK
ER --> CFG
SE --> CFG
CM --> CFG
SDK --> LOG
LOG --> HASH
LOG --> FS
PROV --> HASH
PROV --> ENV
CFG --> ENV
CFG --> ERR
Layer Rules¶
| Layer | May Import From | Module Count | Key Property |
|---|---|---|---|
| L4: CLI | L3, L2, L1 | 21 | Thin wrappers - zero business logic |
| L3: Orchestration | L2, L1 | 7 | Coordinates runtime, manages state transitions |
| L2: Runtime | L1 | 7 | Manages external processes and I/O |
| L1: Foundation | stdlib only | 12 | Zero upward imports, no external process deps |
3. Component Map¶
Core Modules (41 files in crucible/)¶
| Component | Module | Lines | Purpose |
|---|---|---|---|
| CLI Entry | cli.py |
10 | Delegates to commands/ |
| CLI Commands | commands/__init__.py |
107 | Typer app creation, CliState, sub-app registration |
| CLI: Lifecycle | commands/lifecycle.py |
240 | init, status, doctor, fork, setup, clean |
| CLI: Reset | commands/reset_cmd.py |
95 | reset (soft/medium/hard), hard-reset |
| CLI: Experiments | commands/experiment.py |
120 | experiment run, matrix, resume, checkpoints |
| CLI: Export | commands/export.py |
75 | export run as publication bundle |
| CLI: Verify | commands/verify.py |
120 | verify run/bundle/archive integrity |
| CLI: Evidence | commands/evidence.py |
60 | evidence check pre-flight validation |
| CLI: Analytics | commands/analytics.py |
70 | history, diff |
| CLI: Summary | commands/summary.py |
50 | One-shot workspace overview (chains, runs, disk usage) |
| Experiment Runner | experiment.py |
638 | Formal experiment lifecycle, manifest writing |
| Scenario Engine | scenario.py |
169 | Load YAML, execute phases, checkpoint |
| Scenario Steps | scenario_steps.py |
497 | Registry-based step dispatch (11 step types) |
| Chain Manager | chain_manager.py |
365 | Anvil subprocess lifecycle, health check, port mgmt |
| RPC Client | rpc.py |
185 | JsonRpcClient, RpcProviderManager, TokenBucket |
| Instrumentation | instrumentation.py |
322 | Transparent RPC proxy, auto-trace, artifact capture |
| Plugin Registry | plugin.py |
148 | Discovery, validation, dynamic import |
| Plugin Manifest | plugin_manifest.py |
119 | Canonical manifest model (legacy + modern formats) |
| SDK | sdk.py |
219 | AttackPlugin, BridgePlugin, AgentPlugin ABCs |
| Agent Tools | agent_tools.py |
298 | 9 tool defs, AgentContext, privilege enforcement |
| Agent Loop | agent_loop.py |
480 | LLMAgentPlugin, prompt construction, tool execution |
| LLM Providers | llm_providers.py |
399 | OpenAI/Anthropic provider abstraction |
| Log Emitter | logging.py |
416 | LogEmitter + LogManager, 7 JSONL streams, report |
| Baseline | baseline.py |
103 | Golden snapshot capture/verify/restore |
| Checkpoint | checkpoint.py |
74 | Phase-level state checkpointing |
| Diff Engine | diff.py |
91 | Canonical run comparison (storage, events, gas, balances) |
| History | history.py |
92 | SQLite-backed experiment index |
| Publication | publication.py |
228 | 7 research-quality gate checks |
| Evidence | evidence.py |
281 | Fidelity level validation, validate_evidence_against_chain() pre-flight |
| Provenance | provenance.py |
209 | Run manifest, git/foundry/platform info, version check |
| Config | config.py |
150 | Pydantic models, YAML deep merge, env expansion |
| Export | export.py |
182 | Publication bundles (tar-gz/zip) with integrity |
| Extract | extract.py |
739 | Auto-generate attack packs from on-chain txs |
| Matrix Runner | matrix.py |
78 | Sequential matrix experiment execution |
| Cache | cache.py |
231 | Fork cache fingerprinting and verification |
| ABI Registry | abi.py |
154 | ABI listing, validation, Etherscan/Sourcify fetch |
| Public API Re-exports | interfaces/__init__.py |
4 | Re-exports AttackPlugin, BridgePlugin, CruciblePlugin, ExperimentContext |
| Bridge Lifecycle | bridge_lifecycle.py |
95 | Helper functions for bridge deploy/destroy |
| Errors | errors.py |
73 | CrucibleError hierarchy with exit codes |
| Hashing | hashing.py |
14 | sha256_file(), sha256_json() |
| Environment | env.py |
32 | expand_env(), load_dotenv(), get_docker_mode() |
| IDs | ids.py |
33 | next_dataset_id() - monotonic DS-YYYY-NNNNN |
| Utils | utils.py |
70 | utc_now(), run_notification_hooks() |
| Cleanup | cleanup.py |
18 | Log retention, disk warnings |
| File Locking | filesystem.py |
145 | lock_file()/unlock_file(), ensure_dir(), cross-platform |
4. Data Flow: Experiment Lifecycle¶
A single crucible experiment run experiments/nomad_replay.yaml triggers this sequence:
sequenceDiagram
participant U as User / CLI
participant ER as ExperimentRunner
participant CFG as Config Loader
participant PG as Publication Gates
participant SE as ScenarioEngine
participant CM as ChainManager
participant IP as Instrumentation Proxy
participant PR as PluginRegistry
participant AP as AttackPlugin
participant LM as LogManager
participant PROV as Provenance
U->>CFG: load_config() + load_experiment()
U->>ER: run(experiment_path)
ER->>ER: _check_foundry_version()
ER->>ER: _enforce_cleanup()
ER->>PG: check_all() (if publication mode)
ER->>LM: new LogManager(run_dir)
rect rgb(230, 240, 255)
Note over SE,CM: Phase 1 - Environment Setup
ER->>SE: run(scenario_name, context)
SE->>CM: start_chain("ethereum")
CM->>CM: anvil_command() → Popen()
CM->>CM: _await_ready() (poll eth_blockNumber)
SE->>SE: execute YAML steps (log, assert, impersonate...)
end
rect rgb(230, 255, 230)
Note over CM,IP: Phase 2 - Instrumentation
ER->>CM: start_instrumentation("ethereum", chain_log)
CM->>IP: attach_instrumentation(upstream_url, log)
IP->>IP: HTTPServer.start() on random port
Note over CM: runtime_for() now returns proxy URL
end
rect rgb(255, 240, 230)
Note over PR,AP: Phase 3 - Attack Execution
ER->>PR: load("attack", attack_name)
PR->>AP: importlib → instantiate plugin class
ER->>AP: plugin.run(context)
AP->>CM: runtime_for("ethereum") → proxy URL
AP->>IP: eth_sendTransaction (via proxy)
IP->>IP: forward to Anvil → capture receipt → trace
IP->>LM: emit(gas, events, storage_diffs, balances)
end
rect rgb(245, 230, 255)
Note over ER,PROV: Phase 4 - Teardown & Artifacts
ER->>CM: stop_instrumentation() (drain + stop)
ER->>PROV: build_run_manifest()
ER->>LM: write_report()
ER->>LM: write_integrity()
end
Key Design Property: Transparent Auto-Instrumentation¶
Crucible removes the burden of manual telemetry from the researcher. The attack plugin operates completely unaware that it is being instrumented.
In traditional testbeds, researchers must write complex tracking logic inside their exploit scripts to capture gas usage, storage diffs, and events. Crucible eliminates this requirement through a transparent RPC Proxy.
graph LR
subgraph "Attack Phase"
AP[Attack Plugin<br/>(e.g., Python / cast)]
end
subgraph "Crucible Background"
PRX[Instrumentation Proxy<br/>Port 9545]
ANV[Anvil Node<br/>Port 8545]
ART[Artifact Logger<br/>JSONL Streams]
end
AP -- "1. eth_sendTransaction" --> PRX
PRX -- "2. Forward tx" --> ANV
ANV -- "3. Return receipt" --> PRX
PRX -- "4. eth_traceTransaction" --> ANV
ANV -- "5. Return trace data" --> PRX
PRX -- "6. Extract & Save" --> ART
PRX -- "7. Return result" --> AP
style AP fill:#f9d0c4,stroke:#333,stroke-width:2px
style PRX fill:#d4e6f1,stroke:#333,stroke-width:2px
style ANV fill:#d5f5e3,stroke:#333,stroke-width:2px
How it works under the hood:
When start_instrumentation() is called, the ChainManager launches the proxy and secretly updates the connection URL. When the attack plugin asks for the blockchain URL via context.runtime_for("ethereum").rpc_url, it is handed the Proxy URL instead of the direct Anvil URL:
# chain_manager.py — transparent URL substitution
def runtime_for(self, chain_name):
rpc_url = self._anvils[chain_name].rpc_url
# If a proxy is running, secretly intercept all traffic
if chain_name in self._proxies:
rpc_url = self._proxies[chain_name].proxy_url
return ChainRuntime(chain_name, rpc_url, ...)
Because of this seamless swap, any attack — whether it's written in Python using web3.py, a native Solidity forge script, or raw bash cast send commands — blindly sends its transactions to the proxy. The proxy captures publication-quality artifacts (gas profiles, balance diffs, storage diffs) in the background and returns the result to the plugin as if nothing happened.
5. Plugin System¶
Plugin Type Hierarchy¶
classDiagram
class CruciblePlugin {
<<abstract>>
+metadata() dict
}
class AttackPlugin {
+run(ctx)
+prepare(ctx)
+execute(ctx, phase) AttackResult
+verify(ctx) VerificationResult
+rollback(ctx)
+cleanup(ctx)
}
class BridgePlugin {
+deploy(ctx) dict
+configure(ctx, config)
+connect(ctx)
+send_message(ctx, src, dst, data) dict
+reset(ctx)
+destroy(ctx)
}
class AgentPlugin {
+run(ctx)
+prepare(ctx, agent_ctx)
+observe(ctx, agent_ctx) dict
+think(obs, ctx, agent_ctx) AgentAction
+respond(result, ctx, agent_ctx)
+is_done(ctx, agent_ctx) bool
+verify(ctx, agent_ctx) VerificationResult
}
CruciblePlugin <|-- AttackPlugin
CruciblePlugin <|-- BridgePlugin
CruciblePlugin <|-- AgentPlugin
Plugin Lifecycle Comparison¶
| Phase | AttackPlugin | BridgePlugin | AgentPlugin |
|---|---|---|---|
| Setup | prepare() |
deploy() → configure() → connect() |
prepare() |
| Execute | execute(phase) |
send_message() |
observe() → think() → call() (loop) |
| Verify | verify() |
- | verify() |
| Teardown | rollback() → cleanup() |
reset() → destroy() |
- |
| Convenience | run() calls prepare→execute→verify |
- | run() calls prepare→loop→verify |
Plugin Discovery & Loading¶
flowchart LR
subgraph Filesystem
A1["attacks/nomad_replay/plugin.yaml"]
A2["attacks/nomad_replay/nomad_replay.py"]
B1["bridges/demo_bridge/plugin.yaml"]
P1["plugins/agent_llm/plugin.yaml"]
end
subgraph PluginRegistry
DISC["discover()"]
VAL["validate()"]
LOAD["load()"]
end
A1 --> DISC
B1 --> DISC
P1 --> DISC
DISC --> VAL
VAL -->|"check manifest + entry + evidence"| LOAD
LOAD -->|"importlib.util.spec_from_file_location()"| INST["Plugin Instance"]
Search directories: attacks/, bridges/, plugins/
Manifest format (plugin.yaml):
name: nomad_replay
version: 1.0.0
type: attack
entry: nomad_replay.py
class: NomadReplayAttack # modern format
# class_name: NomadReplayAttack # legacy format (also supported)
Attack plugins must include evidence.yaml alongside plugin.yaml. The registry validates evidence structure during discovery.
Bridge plugins deployed:
| Plugin | Contracts | Vulnerability | Lifecycle |
|---|---|---|---|
| nomad_bridge | NomadReplica.sol | committedRoot == 0x00 | deploy -> configure -> connect -> send_message -> reset -> destroy |
| poly_network_bridge | EthCrossChainManager + EthCrossChainData | Hash collision selector dispatch | Same lifecycle |
| wormhole_bridge | WormholeCore + TokenBridge | Guardian bypass mode | Same lifecycle |
All three are discovered and loaded by the PluginRegistry, validated against evidence.yaml, and wired into the experiment lifecycle via bridge_lifecycle.py.
ExperimentContext - The Plugin's Interface to Crucible¶
classDiagram
class ExperimentContext {
+config: TestbedConfig
+topology: TopologyConfig
+chains: ChainManager
+log: LogEmitter
+workspace: Path
+run_id: str
+run_config: dict
+bridge_plugin: BridgePlugin?
}
Every plugin method receives an ExperimentContext. Through it, the plugin can:
- Read chain state: context.chains.runtime_for("ethereum") → JsonRpcClient
- Log events: context.log.step("message"), context.log.event(...)
- Access config: context.config.chains["ethereum"].fork_block
- Use bridges: context.bridge_plugin.send_message(...)
6. Chain Lifecycle & Fork Management¶
Anvil Subprocess Lifecycle¶
stateDiagram-v2
[*] --> Configured: load testbed.yaml
Configured --> Starting: start_chain()
Starting --> WaitingReady: Popen(anvil ...)
WaitingReady --> Running: _await_ready() (poll eth_blockNumber)
Running --> Instrumented: start_instrumentation()
Instrumented --> Draining: drain() (flush traces)
Draining --> Running: stop_instrumentation()
Running --> Stopped: stop_all()
Stopped --> [*]: meta.json deleted
Anvil Command Construction¶
ChainManager.anvil_command() builds a deterministic Anvil command:
anvil \
--fork-url ${ETH_RPC_URL} \
--fork-block-number 15259100 \
--host 127.0.0.1 \
--port 8545 \
--chain-id 1 \
--gas-price 0 \
--block-base-fee-per-gas 1000000000 \
--auto-impersonate \
--order fifo \
--cache-path .fork_cache/ethereum/15259100
3-Tier Reset System¶
flowchart LR
SOFT["Soft Reset<br/>< 5 seconds"]
MED["Medium Reset<br/>< 30 seconds"]
HARD["Hard Reset<br/>< 5 minutes"]
SOFT -->|"anvil_loadState"| STATE["Restore from snapshot"]
MED -->|"kill + relaunch + restore"| RELAUNCH["Fresh Anvil + restore"]
HARD -->|"re-fork from RPC"| REFORK["Full re-fork + bootstrap"]
| Tier | Method | Speed | Fidelity | Use Case |
|---|---|---|---|---|
| Soft | anvil_loadState |
<5s | Snapshot-perfect | Matrix runs, parameter sweeps |
| Medium | Kill → restart → restore | <30s | Clean process | After process corruption |
| Hard | Re-fork from upstream RPC | <5min | Full re-fetch | After cache corruption, topology change |
RPC Provider Failover¶
flowchart TD
REQ["RPC Request"]
P1["Provider 1 (primary)"]
P2["Provider 2 (llamarpc)"]
P3["Provider 3 (ankr)"]
P4["Provider 4 (publicnode)"]
REQ --> P1
P1 -->|"429 / timeout"| P2
P2 -->|"429 / timeout"| P3
P3 -->|"429 / timeout"| P4
P4 -->|"all failed"| ERR["RpcError"]
P1 -->|"success"| OK["JsonRpcClient"]
P2 -->|"success"| OK
P3 -->|"success"| OK
Providers are configured per-chain in testbed.yaml and tried in priority order. Each provider has its own TokenBucket rate limiter.
7. Instrumentation Proxy¶
The instrumentation proxy is the architectural centerpiece - it makes artifact capture automatic and universal.
How It Works¶
flowchart LR
subgraph "Attack Plugin"
SEND["eth_sendTransaction"]
end
subgraph "Instrumentation Proxy (HTTPServer thread)"
FWD["Forward to Anvil"]
SCHED["Schedule trace"]
end
subgraph "ThreadPoolExecutor"
RECEIPT["eth_getTransactionReceipt"]
TRACE["debug_traceTransaction<br/>(prestateTracer diffMode)"]
PARSE["Parse trace → artifacts"]
end
subgraph "Anvil Fork"
ANVIL["Process TX"]
end
subgraph "LogEmitter"
GAS["gas_profile.jsonl"]
EVENTS["events.jsonl"]
STORAGE["storage_diffs.jsonl"]
BALANCE["balance_diffs.jsonl"]
end
SEND --> FWD
FWD --> ANVIL
ANVIL --> FWD
FWD --> SCHED
SCHED --> RECEIPT
RECEIPT --> TRACE
TRACE --> PARSE
PARSE --> GAS
PARSE --> EVENTS
PARSE --> STORAGE
PARSE --> BALANCE
What Gets Captured Per Transaction¶
| Artifact | Source | Stream |
|---|---|---|
| Gas used | eth_getTransactionReceipt → gasUsed |
gas_profile.jsonl |
| Contract events | Receipt → logs[] → decode topic[0] |
events.jsonl |
| Storage diffs | debug_traceTransaction → pre/post storage |
storage_diffs.jsonl |
| Balance changes | debug_traceTransaction → pre/post balance |
balance_diffs.jsonl |
Multi-Chain Proxy Isolation¶
Each chain gets its own proxy instance with its own handler class:
Ethereum: Attack → Proxy :9001 → Anvil :8545
BSC: Attack → Proxy :9002 → Anvil :8547
Polygon: Attack → Proxy :9003 → Anvil :8546
The _make_handler() closure captures upstream_url, log, and chain per instance, preventing shared-state bugs across chains.
Shutdown Sequence¶
1. proxy.drain() → ThreadPoolExecutor.shutdown(wait=True)
(all pending traces complete)
2. proxy.stop() → HTTPServer.shutdown() + server_close()
3. log.write_integrity() → close file handles + hash files
drain() must be called before stop() and before log handles close. This ensures all async trace tasks complete before artifacts are finalized.
8. Observability Pipeline¶
Log Directory Structure¶
logs/
nomad_experiment/
DS-2026-00042/ ↠run directory
run.jsonl ↠experiment lifecycle events
run_manifest.json ↠provenance, config, outcome
log_integrity.json ↠SHA-256 hashes of all streams
report.md ↠human-readable summary
chain_ethereum/ ↠per-chain artifacts
run.jsonl ↠chain-specific lifecycle
events.jsonl ↠contract events
gas_profile.jsonl ↠gas usage per transaction
storage_diffs.jsonl ↠storage slot changes
balance_diffs.jsonl ↠ETH/token balance changes
chain_bsc/
...
bridge/ ↠cross-chain correlation
cross_chain.jsonl ↠bridge message tracking
events.jsonl
7 JSONL Artifact Streams¶
The testbed produces 6 core streams managed by LogEmitter through the standard emit API, plus 1 agent-specific stream written directly by the LLM agent plugin:
| Stream | Content | Written By |
|---|---|---|
run.jsonl |
Experiment lifecycle (phase start/end, errors) | LogManager.step() |
events.jsonl |
Contract events (Transfer, Approval, custom) | LogEmitter.event() via proxy |
storage_diffs.jsonl |
Storage slot changes (contract, slot, before, after) | LogEmitter.storage_diff() via proxy |
gas_profile.jsonl |
Gas used per transaction | LogEmitter.gas() via proxy |
balance_diffs.jsonl |
Balance changes (ETH and token) | LogEmitter.balance_diff() via proxy |
cross_chain.jsonl |
Bridge message correlation IDs | LogEmitter.cross_chain() |
agent_reasoning.jsonl |
LLM agent reasoning traces (observation, action, conversation snapshot) - written outside the standard LogEmitter system, so not tracked in log_integrity.json |
LLMAgentPlugin._log_reasoning_step() |
LogManager vs LogEmitter¶
classDiagram
class LogManager {
-_root: LogEmitter
-_chain_emitters: dict
-_bridge_emitter: LogEmitter
+step(message)
+for_chain(name) LogEmitter
+bridge() LogEmitter
+write_report()
+write_integrity()
}
class LogEmitter {
-_handles: dict[stream, file]
+emit(stream, fields)
+step(message)
+event(chain, event_name)
+storage_diff(chain, contract, slot, before, after)
+gas(step, gas_used)
+balance_diff(chain, contract, account, before, after)
+cross_chain(correlation_id, source, dest)
+close()
+write_integrity()
}
LogManager --> LogEmitter : root
LogManager --> LogEmitter : chain_ethereum
LogManager --> LogEmitter : chain_bsc
LogManager --> LogEmitter : bridge
LogManager is the experiment-level orchestrator. It creates per-chain LogEmitter instances lazily via for_chain(). Attack plugins interact with context.log (which is a LogManager) - lifecycle events go to the root emitter, while chain-specific data routes to the per-chain subdirectory.
Diff Engine - Determinism Verification¶
crucible diff <run-a> <run-b> canonicalizes and compares four metrics:
flowchart LR
A["Run A"] --> CA["Canonical Sort"]
B["Run B"] --> CB["Canonical Sort"]
CA --> CMP["Compare"]
CB --> CMP
CMP --> S["storage_equal: true/false"]
CMP --> E["events_equal: true/false"]
CMP --> G["gas_equal: true/false"]
CMP --> BL["balances_equal: true/false"]
All four must be true for deterministic reproduction.
Note: The 6 core streams appear in
STREAMSincrucible/logging.py. The 7th (agent_reasoning.jsonl) is emitted byLLMAgentPlugindirectly and bypasses integrity hashing - this is a known gap.
9. Configuration System¶
Configuration Hierarchy¶
flowchart TD
ENV[".env file<br/>(ETH_RPC_URL, BSC_RPC_URL...)"]
BASE["testbed.yaml<br/>(committed to git)"]
LOCAL["testbed.local.yaml<br/>(gitignored, per-user)"]
TOPO["topologies/*.yaml<br/>(chain composition)"]
EXP["experiments/*.yaml<br/>(experiment definition)"]
ENV -->|"load_dotenv()"| MERGE
BASE -->|"read_yaml()"| MERGE["deep_merge()"]
LOCAL -->|"override"| MERGE
MERGE -->|"expand_env()"| VALIDATE["Pydantic validation"]
VALIDATE --> CFG["TestbedConfig"]
TOPO --> TCFG["TopologyConfig"]
EXP --> ECFG["ExperimentConfig"]
Pydantic Config Model Hierarchy¶
classDiagram
class TestbedConfig {
+workspace: str
+active_topology: str
+foundry: FoundryConfig
+publication: PublicationConfig
+chains: dict[str, ChainConfig]
+rpc_providers: dict[str, list]
+fork_cache: ForkCacheConfig
+logging: LoggingConfig
+cleanup: CleanupConfig
+rpc_budget: RpcBudgetConfig
+notifications: NotificationConfig
}
class ChainConfig {
+rpc_url: str
+fork_block: int?
+chain_id: int
+port: int
+host: str
+determinism: DeterminismConfig
}
class DeterminismConfig {
+gas_price: int = 0
+block_base_fee: int = 1_000_000_000
+timestamp: "fork_block"
+auto_mine: bool = true
+order: "fifo"
}
class TopologyConfig {
+name: str
+description: str
+chains: list[str]
+bridge: str?
}
class ExperimentConfig {
+name: str
+scenario: str
+attack: str
+topology: str = "single"
+run: dict
+tags: list[str]
}
TestbedConfig --> ChainConfig
ChainConfig --> DeterminismConfig
Built-In Validations¶
- Port uniqueness - no two chains can share a port (model-level validator)
- 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
10. Scenario Engine¶
Scenarios define the chain environment before the attack runs. They set up contract state, impersonate accounts, and configure initial conditions.
Scenario Structure¶
# scenarios/nomad_replay/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..."
- type: assert_balance
chain: ethereum
account: "0xB92..."
min_value: "1000000000000000000"
- name: attack_ready
steps:
- type: log
message: "Environment ready for attack"
Step Dispatch (Registry Pattern)¶
flowchart LR
YAML["YAML Step<br/>{type: 'send_tx', ...}"] --> DISPATCH["handle_step()"]
DISPATCH --> REG["Step Registry"]
REG --> H1["@register_step('log')"]
REG --> H2["@register_step('send_tx')"]
REG --> H3["@register_step('impersonate')"]
REG --> H4["@register_step('assert_balance')"]
REG --> H5["@register_step('forge_script')"]
REG --> H6["@register_step('python_script')"]
REG --> H7["@register_step('advance_time')"]
REG --> H8["@register_step('assert')"]
REG --> H9["@register_step('verify_tracing')"]
REG --> H10["@register_step('bridge_action')"]
REG --> H11["@register_step('plugin')"]
Step handlers are registered via decorator - no if/elif chain:
New step types can be added by registering a new handler without modifying the engine.
11. Agent System¶
Agent Architecture¶
flowchart TB
subgraph "Experiment Runner"
ER["_load_plugin()"]
end
subgraph "AgentPlugin (sdk.py)"
RUN["run()"]
LOOP["observe → think → act loop"]
VERIFY["verify()"]
end
subgraph "LLMAgentPlugin (agent_loop.py)"
PROMPT["build_system_prompt()"]
LLM["LLM API Call"]
PARSE["Parse tool_calls"]
end
subgraph "AgentContext (agent_tools.py)"
TOOLS["9 Tools + Privilege Gate"]
HISTORY["Tool Call History"]
end
subgraph "LLM Provider (llm_providers.py)"
OAI["OpenAI"]
ANT["Anthropic"]
end
ER -->|"agent_provider in config"| RUN
RUN --> LOOP
LOOP --> PROMPT
PROMPT --> LLM
LLM --> OAI
LLM --> ANT
LLM --> PARSE
PARSE --> TOOLS
TOOLS --> HISTORY
LOOP --> VERIFY
Agent Tool Registry¶
| Tool | Privilege | Description |
|---|---|---|
chain_id |
LOW | Get chain ID of running fork |
get_balance |
LOW | Get ETH balance (wei) |
get_code |
LOW | Get runtime bytecode |
get_storage |
LOW | Get storage at slot |
call_contract |
LOW | Read-only eth_call |
get_logs |
LOW | Get event logs for address |
impersonate |
MEDIUM | Impersonate an account |
send_transaction |
MEDIUM | Send a transaction |
advance_time |
HIGH | Advance EVM timestamp |
Privilege Levels¶
LOW → Read-only queries (5 tools)
MEDIUM → Impersonate + transact (7 tools, default)
HIGH → Full access including time manipulation (9 tools)
Configured per-experiment in the YAML:
12. Determinism & Reproducibility¶
Determinism Boundary¶
flowchart LR
subgraph "Crucible Guarantees"
DET1["Fixed gas price (0)"]
DET2["Fixed block base fee"]
DET3["FIFO tx ordering"]
DET4["Pinned fork block"]
DET5["Fork-block timestamp"]
DET6["Auto-mine (instant)"]
end
subgraph "Not Guaranteed"
ND1["Cross-RPC-provider<br/>response ordering"]
ND2["Multi-chain relay<br/>timing"]
ND3["Python dict ordering<br/>(mitigated by sort_keys)"]
end
Provenance Tracking¶
Every run produces a run_manifest.json:
{
"run_id": "DS-2026-00042",
"scenario": "nomad_replay",
"attack": "nomad_replay",
"topology": "single",
"outcome": "success",
"provenance": {
"git_commit": "a1b2c3d...",
"git_dirty": false,
"foundry_version": "forge 0.2.0 (nightly)",
"python_version": "3.12.4",
"platform": "Linux-x86_64",
"docker_mode": "container",
"config_fingerprint": "sha256:abc123..."
}
}
Integrity Verification¶
log_integrity.json contains SHA-256 hashes of every artifact file:
{
"files": {
"run.jsonl": "sha256:...",
"events.jsonl": "sha256:...",
"storage_diffs.jsonl": "sha256:...",
"gas_profile.jsonl": "sha256:...",
"balance_diffs.jsonl": "sha256:..."
}
}
13. Publication Pipeline¶
Fidelity Levels¶
flowchart TB
L0["L0 - Narrative Only<br/>No code, description only"]
L1["L1 - Conceptual<br/>Deploys vulnerable contract"]
L2["L2 - Fork-State Behavioral<br/>Fork at historical block, check behavior"]
L3["L3 - Exact Transaction Replay<br/>Replay real exploit tx on fork"]
L4["L4 - Multi-Chain Full<br/>Multiple chains + bridge simulation"]
L0 --> L1 --> L2 --> L3 --> L4
L2 -.->|"requires"| REQ2["chains + affected_contracts"]
L3 -.->|"requires"| REQ3["exploit_transactions"]
L4 -.->|"requires"| REQ4["excluded_components declared"]
7 Publication Gates¶
| Gate | What It Checks |
|---|---|
| Evidence | evidence.yaml has all required sections |
| Fidelity | Fidelity-level-specific requirements met |
| Baseline | Golden baseline exists and verifies |
| Foundry | Foundry version pinned (no nightly drift) |
| Git Provenance | Workspace is a git repo with a known commit |
| Artifacts Complete | All expected trace artifacts were captured (no auto-trace failures) |
| Provenance | Git commit clean, platform recorded |
All 7 gates must pass before a run can be exported for publication.
Export Bundle¶
datasets/DS-2026-00042/
run_manifest.json ↠provenance + outcome
log_integrity.json ↠artifact hashes
report.md ↠human-readable summary
run.jsonl ↠lifecycle events
chain_ethereum/ ↠per-chain artifacts
REPRODUCE.md ↠step-by-step reproduction guide
CITATION.cff ↠citation metadata
artifact_bundle_manifest.json ↠SHA-256 of every file
14. CLI Architecture¶
Command Registration Pattern¶
flowchart TD
CLI["cli.py<br/>app()"]
INIT["commands/__init__.py<br/>Typer apps + CliState"]
CLI --> INIT
INIT --> LC["lifecycle.py<br/>init, status, fork, setup, clean"]
INIT --> DR["doctor.py<br/>doctor"]
INIT --> RS["reset_cmd.py<br/>reset, hard-reset"]
INIT --> BL["baseline.py<br/>baseline capture/verify"]
INIT --> SN["snapshot.py<br/>snapshot create/restore"]
INIT --> PL["plugin.py<br/>plugin list/validate"]
INIT --> EX["experiment.py<br/>experiment run/matrix/resume"]
INIT --> LG["logs.py<br/>logs list"]
INIT --> AB["abi.py<br/>abi list/validate/fetch"]
INIT --> AT["attack.py<br/>attack init/extract"]
INIT --> CA["cache.py<br/>cache inspect/clean"]
INIT --> BU["bundle.py<br/>bundle hash/verify"]
INIT --> VE["verify.py<br/>verify run/bundle/archive"]
INIT --> EC["evidence.py<br/>evidence check pre-flight"]
INIT --> EP["export.py<br/>export run"]
INIT --> AN["analytics.py<br/>history, diff"]
INIT --> IN["instrument.py<br/>standalone proxy"]
INIT --> SM["summary.py<br/>summary"]
INIT --> DB["dashboard.py<br/>dashboard launch"]
INIT --> NB["notebook.py<br/>notebook launch"]
CLI Command Tree¶
crucible
├── init # Initialize workspace
├── status # Show running chains
├── doctor # Environment health check
├── fork # Fork chains from topology
├── setup # Fork + bootstrap
├── clean # Remove old logs/caches
├── reset [soft|medium|hard]
├── baseline
│ ├── capture # Save golden baseline
│ └── verify # Verify baseline integrity
├── snapshot
│ ├── create # Manual snapshot
│ └── restore # Restore snapshot
├── plugin
│ ├── list # List discovered plugins
│ └── validate # Validate a plugin
├── experiment
│ ├── run # Run single experiment
│ ├── matrix # Run experiment matrix
│ ├── resume # Resume from checkpoint
│ └── checkpoints # List checkpoints
├── attack
│ ├── init # Scaffold new attack plugin from template (--from-tx populates real data)
│ └── extract # Auto-generate attack from on-chain tx (with ABI decoding)
├── cache
│ ├── inspect # Show cache contents
│ ├── fingerprint # Compute cache fingerprint
│ ├── verify # Verify cache integrity
│ └── clean # Clean cache
├── evidence
│ └── check # Validate evidence.yaml claims against live (forked) chain state
├── bundle
│ ├── hash # Compute bundle hash
│ └── verify # Verify bundle integrity
├── verify # Verify run/bundle/archive integrity (auto-detect)
├── export # Export run as publication bundle
├── publish # Mark run as published (indefinite preservation)
├── history # Query experiment history
├── summary # One-shot workspace overview (chains, runs, disk usage)
├── diff # Compare two runs
├── abi
│ ├── list # List known ABIs
│ ├── validate # Validate ABI file
│ └── fetch # Fetch from Etherscan/Sourcify
├── logs
│ └── list # List run log directories
├── instrument # Standalone instrumentation proxy for ad-hoc tx instrumentation
├── dashboard # Launch Streamlit UI
└── notebook # Launch Jupyter notebook
15. Docker Architecture¶
Container Topology¶
graph TB
subgraph "docker-compose.yml"
ORCH["orchestrator<br/>Python 3.12 + Foundry + uv<br/>ENTRYPOINT: uv run crucible"]
DASH["dashboard<br/>Streamlit UI<br/>Port 8501"]
AE["anvil-ethereum<br/>(optional daemon)<br/>Port 8545"]
AP["anvil-polygon<br/>(optional daemon)<br/>Port 8546"]
AB["anvil-bsc<br/>(optional daemon)<br/>Port 8547"]
end
subgraph "Docker Volumes"
V1["states_data → /workspace/states"]
V2["logs_data → /workspace/logs"]
V3["fork_cache → /workspace/.fork_cache"]
end
ORCH --> V1
ORCH --> V2
ORCH --> V3
DASH --> V2
Two Operational Modes¶
| Mode | Command | When to Use |
|---|---|---|
| Single-container (default) | docker compose run --rm --entrypoint bash orchestrator -c "fork && experiment run" |
Most experiments - Anvil runs inside orchestrator |
| Daemon + orchestrator | docker compose up -d anvil-ethereum && docker compose run orchestrator experiment run |
Multi-session workflows, streaming |
Recommended: Single-container mode. Simpler, fully isolated, avoids daemon fork-block mismatch.
16. Directory Structure¶
crucible-testbed/
├── crucible/ # Core Python package (41 modules)
│ ├── __init__.py # Public API + lazy imports
│ ├── cli.py # Entry point
│ ├── commands/ # CLI command modules (21 sub-modules + __init__.py)
│ ├── sdk.py # Plugin interfaces
│ ├── experiment.py # Experiment runner
│ ├── scenario.py # Scenario engine
│ ├── scenario_steps.py # Step handlers
│ ├── chain_manager.py # Anvil lifecycle
│ ├── instrumentation.py # RPC proxy
│ ├── logging.py # Artifact streams
│ ├── config.py # Pydantic models
│ ├── plugin.py # Plugin registry
│ ├── agent_tools.py # Agent tool definitions
│ ├── agent_loop.py # LLM agent loop
│ ├── llm_providers.py # OpenAI/Anthropic
│ ├── schema.py # JSONL schema validation
│ ├── enforcer.py # Fidelity-level runtime enforcement
│ ├── extract.py # Auto-generate attack packs from txs
│ ├── matrix.py # Sequential matrix experiment execution
│ ├── cache.py # Fork cache fingerprinting
│ ├── abi.py # ABI registry and Etherscan/Sourcify fetch
│ ├── bridge_lifecycle.py # Bridge deploy/destroy helpers
│ ├── errors.py # CrucibleError hierarchy
│ ├── hashing.py # SHA-256 helpers
│ ├── env.py # Environment variable expansion
│ ├── ids.py # Monotonic dataset IDs
│ ├── utils.py # utc_now, notification hooks
│ ├── cleanup.py # Log retention, disk warnings
│ └── filesystem.py # File locking, cross-platform paths
├── attacks/ # Attack plugins (8 packs)
│ ├── nomad_replica_fraud/ # L2 - Nomad Bridge (complete)
│ ├── wormhole_guardian_bypass/ # L2 - Wormhole (complete)
│ ├── poly_network_privkey/ # L2 - Poly Network (complete, ETH-only)
│ ├── horizon_multisig_drain/ # L2 - Horizon (complete)
│ ├── multichain_router_permit/ # L1 - Multichain (narrative, maxed at L1)
│ ├── bnb_token_hub_proof/ # L2 - BNB Bridge (complete)
│ ├── demo_attack/ # L0 - Reference implementation
│ └── demo_agent/ # Agent - LLM-driven demo
├── bridges/ # Bridge plugins (4 implementations)
│ ├── demo_bridge/ # Reference implementation (no-op)
│ ├── nomad_bridge/ # Nomad Replica (ethereum + polygon)
│ ├── poly_network_bridge/ # EthCrossChainManager/Data (ethereum + polygon + bsc)
│ └── wormhole_bridge/ # WormholeCore + TokenBridge (ethereum + polygon)
├── plugins/ # General plugins (agents)
├── scenarios/ # Scenario YAML definitions
├── experiments/ # Experiment YAML definitions
├── topologies/ # Topology profiles (9 files)
│ ├── single.yaml # Ethereum only
│ ├── dual.yaml # Ethereum + Polygon
│ ├── bridge.yaml # Two chains + demo_bridge plugin
│ ├── nomad_bridge.yaml # ethereum + polygon + nomad_bridge
│ ├── poly_network_bridge.yaml # ethereum + polygon + bsc + poly_network_bridge
│ ├── wormhole_bridge.yaml # ethereum + polygon + wormhole_bridge
│ ├── single_bsc.yaml # BSC only
│ ├── poly_network_full.yaml # Ethereum + Polygon + BSC (no bridge)
│ └── harmony_bridge.yaml # Ethereum + Harmony + bridge
├── states/ # Chain state (meta files, snapshots, baselines)
├── logs/ # Experiment output artifacts
├── datasets/ # Exported publication bundles
├── docs/ # Documentation (23 files + 2 case studies + 2 design docs + 12 internal)
├── tests/ # Test suite (798+ tests)
├── testbed.yaml # Main configuration
├── testbed.local.yaml # Per-user overrides (gitignored)
├── Dockerfile # Container definition
├── docker-compose.yml # Multi-container orchestration
└── pyproject.toml # Python package definition
17. Key Design Decisions¶
For a deeper treatment of each decision - including the tradeoffs considered and why the current path was chosen - see the Design Decisions document.
CLI-First, UI as Wrapper¶
Every action is available via crucible <command>. The Streamlit dashboard is a separate read-only viewer. This makes experiments scriptable, CI-able, and Docker-friendly.
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.
# topologies/single.yaml - Ethereum only
name: single
chains: [ethereum]
bridge: null
# topologies/bridge.yaml - Two chains + bridge (demo)
name: bridge
chains: [ethereum, polygon]
bridge: demo_bridge
# topologies/nomad_bridge.yaml - Two chains + Nomad bridge plugin
name: nomad_bridge
chains: [ethereum, polygon]
bridge: nomad_bridge
# topologies/wormhole_bridge.yaml - Two chains + Wormhole bridge plugin
name: wormhole_bridge
chains: [ethereum, polygon]
bridge: wormhole_bridge
# topologies/poly_network_bridge.yaml - Three chains + Poly Network bridge plugin
name: poly_network_bridge
chains: [ethereum, polygon, bsc]
bridge: poly_network_bridge
Transparent Instrumentation¶
The instrumentation proxy intercepts all RPC traffic. Researchers don't need to 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 (gas_price: 0, order: fifo, timestamp: fork_block) 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 check requirements programmatically. An L2 reproduction without affected_contracts will fail the gate.
Separation of Scenario and Experiment¶
Scenarios define environments (chain state, contract setup). Experiments pair a scenario + attack plugin for formal runs. This means the same scenario can be used with different attacks, and the same attack can run against different scenarios.
See Also¶
| Doc | What It Covers |
|---|---|
docs/TECHNICAL_OVERVIEW.md |
System philosophy, core concepts, data flow, design principles (broad overview) |
docs/internal/DESIGN_DECISIONS.md |
15 key architectural decisions with rationale, tradeoffs, and alternatives |
docs/internal/BRIDGE_PLUGIN_LIMITATIONS.md |
Bridge plugin coverage, limitations, and future improvement scope |
docs/REPRODUCTION_SCOPE.md |
Fidelity levels, in-scope vs out-of-scope attack types |
docs/ATTACK_PACK_GUIDE.md |
Creating attack plugins and scenarios |