Skip to content

Plugin Development Guide

Audience: Researchers and developers writing attack, bridge, or agent plugins for Crucible.


Overview

Crucible supports three plugin types:

Type Base Class Purpose
Attack AttackPlugin Reproduce a historical exploit
Bridge BridgePlugin Simulate a cross-chain bridge protocol
Agent AgentPlugin Create an LLM-driven autonomous agent

All plugins are Python classes that subclass the appropriate base class from crucible.sdk. They are discovered automatically by the PluginRegistry by scanning attacks/, bridges/, and plugins/ directories.


Plugin Structure

Every plugin follows this directory convention:

attacks/my_exploit/
├── plugin.yaml          # Plugin manifest (required)
├── evidence.yaml        # Evidence declaration (required for attacks)
├── my_exploit.py        # Plugin implementation
└── ...                  # Additional files (ABI, bytecode, etc.)

Plugin Manifest (plugin.yaml)

Crucible supports a modern manifest format that clearly declares dependencies. (The legacy format with class_name and chains_required is deprecated but still supported).

name: my_exploit
version: 1.0.0
type: attack           # attack | bridge | agent
entry: my_exploit.py
class: MyExploit       # The Python class name

# Optional metadata
author: "Security Researcher"
reproduction: {}       # Reserved for reproduction-specific metadata

# Dependency Requirements
requires:
  crucible: ">=0.1.0"
  chains: [ethereum]   # Required chains to run this plugin
  topology: single     # Required topology (e.g., single, bridge)

Evidence Declaration (evidence.yaml)

Every attack plugin must include an evidence.yaml:

incident:
  name: "My Exploit"
  date: "2024-01-01"
  affected_bridge: "MyBridge"
  funds_lost_usd: 1000000
  summary: "Description of the vulnerability"

sources:
  advisories:
    - "https://example.com/advisory"
  postmortems:
    - "https://example.com/postmortem"

historical_scope:
  chains: ["ethereum"]
  fork_blocks:
    ethereum: 15000000
  exploit_transactions:
    - "0xabc..."
  affected_contracts:
    VulnerableContract: "0x123..."
  attacker_addresses:
    - "0xabc..."

reproduction_scope:
  fidelity_level: L2
  exact_tx_replay: false
  modeled_components:
    - "Fork-state call to vulnerable contract"
  excluded_components:
    - "Non-EVM chain state"

acceptance:
  required_assertions:
    - name: vulnerability_exists
      description: "The vulnerable state exists at fork block"
      expected: true
    - name: exploit_succeeds
      description: "The exploit transaction does not revert"
      expected: true

Writing an Attack Plugin

Step 1: Scaffold

# Create from a real exploit transaction (populates evidence.yaml from on-chain data)
crucible attack extract 0xabc... --name my_exploit

# Or create from template (empty scaffold)
crucible attack init my_exploit --chain ethereum --fidelity L2 --author "Your Name"

Step 2: Implement the Plugin

from crucible.rpc import JsonRpcClient
from crucible.sdk import AttackPlugin, AttackResult, ExperimentContext, VerificationResult


class MyExploit(AttackPlugin):
    def metadata(self) -> dict:
        return {
            "name": "my_exploit",
            "version": "1.0.0",
            "type": "attack",
            "fidelity_level": "L2",
            "damage_usd": 1000000,
        }

    def execute(self, context: ExperimentContext, phase: int | None = None) -> AttackResult:
        # 1. Get a client for the forked chain
        rpc_url = context.chains.runtime_for("ethereum").rpc_url
        client = JsonRpcClient(rpc_url)

        # 2. Check contract exists
        code = client.get_code("0x123...")
        if not code or code == "0x":
            return AttackResult(success=False, phase_results=[
                {"step": "check_contract", "passed": False, "detail": "no code"}
            ])

        # 3. Forge exploit calldata
        calldata = "0x..."

        # 4. Send exploit transaction
        tx_hash = client.call("eth_sendTransaction", [{
            "to": "0x123...",
            "data": calldata,
        }])

        # 5. Check result
        receipt = client.call("eth_getTransactionReceipt", [tx_hash])
        success = receipt and receipt.get("status") == "0x1"

        return AttackResult(success=success, phase_results=[
            {"step": "check_contract", "passed": True},
            {"step": "send_exploit", "passed": success},
        ])

    def verify(self, context: ExperimentContext) -> VerificationResult:
        client = JsonRpcClient(context.chains.runtime_for("ethereum").rpc_url)

        # Check on-chain state matches expectations
        balance = client.get_balance("0xattacker...")
        assertions = []
        errors = []

        if balance > 0:
            assertions.append({"name": "attacker_balance", "passed": True})
        else:
            errors.append("attacker balance did not increase")

        return VerificationResult(
            passed=len(errors) == 0,
            assertions=assertions,
            errors=errors,
        )

Step 3: Create the Experiment

# experiments/my_exploit.yaml
name: my_exploit
scenario: my_scenario
attack: my_exploit
topology: single

Step 4: Create the Scenario

# scenarios/my_scenario/scenario.yaml
phases:
  - name: setup
    steps:
      - type: log
        message: "Setting up exploit environment"
      - type: impersonate
        chain: ethereum
        account: "0xattacker..."
      - type: assert_balance
        chain: ethereum
        account: "0xattacker..."
        min_value: "1000000000000000000"  # 1 ETH

Step 5: Run

crucible fork --topology single
crucible experiment run experiments/my_exploit.yaml

The ExperimentContext

Every plugin method receives an ExperimentContext with these fields:

@dataclass
class ExperimentContext:
    config: TestbedConfig          # Full testbed configuration
    topology: TopologyConfig       # Active topology definition
    chains: ChainManager           # Chain lifecycle management
    log: LogEmitter | LogManager   # Artifact logging
    workspace: Path                # Project root path
    run_id: str                    # Unique run identifier (e.g., DS-2026-00042)
    run_config: dict               # Experiment-specific run config
    bridge_plugin: Any             # Deployed bridge plugin (if any)

Accessing Chain State

# Get a JSON-RPC client for a chain
runtime = context.chains.runtime_for("ethereum")
client = JsonRpcClient(runtime.rpc_url)

# Read chain state
balance = client.get_balance("0x...")
code = client.get_code("0x...")
storage = client.get_storage_at("0x...", "0x0")
block = client.call("eth_getBlockByNumber", ["0x...", False])

# Send transactions
tx_hash = client.send_transaction({
    "to": "0x...",
    "data": "0x...",
    "from": "0x...",
})
receipt = client.call("eth_getTransactionReceipt", [tx_hash])

# Impersonate accounts (requires --auto-impersonate or manual anvil_impersonate)
client.impersonate_account("0x...")

Logging

# Step logging (appears in run.jsonl)
context.log.step("message", phase="attack", action="exploit_execution", status="success")

# Event logging (appears in events.jsonl)
context.log.event(
    chain="ethereum",
    event_name="Transfer",
    address="0x...",
    topics=["0x..."],
    data="0x...",
)

# Storage diff logging
context.log.storage_diff(
    chain="ethereum",
    contract="0x...",
    slot="0x...",
    before="0x...",
    after="0x...",
)

# Gas logging
context.log.gas(step="exploit_tx", gas_used=21000, chain="ethereum")

Writing a Bridge Plugin

Bridge plugins simulate cross-chain bridge protocols. They follow a full lifecycle:

from crucible.sdk import BridgePlugin, ExperimentContext


class MyBridge(BridgePlugin):
    def metadata(self) -> dict:
        return {
            "name": "my_bridge",
            "version": "1.0.0",
            "type": "bridge",
        }

    def deploy(self, context: ExperimentContext) -> dict[str, str]:
        # Deploy bridge contracts on all chains
        # Returns dict of chain_name -> deployed_address
        eth_client = context.chains.runtime_for("ethereum")
        # ... deploy contract ...
        return {"ethereum": "0xdeployed..."}

    def configure(self, context, config=None):
        # Set validator set, relayer addresses, guardian keys
        pass

    def connect(self, context):
        # Start message-passing simulation
        pass

    def send_message(self, context, source_chain, dest_chain, data, correlation_id=None):
        # Send a cross-chain message
        client = context.chains.runtime_for(source_chain)
        tx_hash = client.send_transaction({
            "to": context.bridge_address,
            "data": data,
        })
        return {"source_tx_hash": tx_hash, "correlation_id": correlation_id}

    def reset(self, context):
        # Reset bridge state to post-deploy baseline
        pass

    def destroy(self, context):
        # Tear down relayer and deployed contracts
        pass

Bridge Plugin Manifest

# bridges/my_bridge/plugin.yaml
name: my_bridge
version: 1.0.0
type: bridge
entry: my_bridge.py
class: MyBridge

Bridge plugins also require evidence.yaml:

# bridges/my_bridge/evidence.yaml
protocol:
  name: "My Bridge Protocol"
  version: "1.0"

features:
  - "Cross-chain message passing"
  - "Validator set management"

limitations:
  - "No real relayer — simulation only"
  - "Single message per transaction"

chains: ["ethereum", "polygon"]

Writing an Agent Plugin

Agent plugins replace traditional attack plugins with LLM-driven autonomous agents:

from crucible.sdk import AgentPlugin, ExperimentContext, VerificationResult
from crucible.agent_tools import AgentAction, AgentContext


class MyAgent(AgentPlugin):
    def metadata(self) -> dict:
        return {
            "name": "my_agent",
            "version": "1.0.0",
            "type": "agent",
        }

    def think(self, observation, context, agent_ctx):
        # Given the current observation, decide what action to take
        # Return an AgentAction, or None to end the loop
        return AgentAction(
            tool="get_balance",
            params={"address": "0x..."},
            reasoning="Check attacker balance",
        )

    def verify(self, context, agent_ctx):
        return VerificationResult(passed=True)

Agent Experiment Config

# experiments/my_agent.yaml
name: my_agent
scenario: my_scenario
attack: my_agent
topology: single
run:
  agent_provider: openai        # openai | anthropic | ollama | mock
  agent_privilege: medium       # low | medium | high
  agent_allowed_accounts:
    - "0xattacker..."

Plugin Lifecycle

Attack Plugin

prepare() → execute() → verify() → rollback() → cleanup()
                      ↘ run() ↗          (convenience wrapper)
Method Called Purpose
prepare() Before execute Set up attacker accounts, approve tokens, deploy helpers
execute() Main execution Run the attack, return AttackResult
verify() After execute Check on-chain state against expected results
rollback() On failure Undo persistent changes not handled by snapshot restore
cleanup() Always Remove temp files, kill helper processes

Bridge Plugin

deploy() → configure() → connect() → send_message()* → reset() → destroy()
Method Called Purpose
deploy() Once Deploy bridge contracts to all chains
configure() After deploy Set validator set, relayer addresses, guardian keys
connect() Before messaging Start message-passing simulation / relayer process
send_message() Per message Send a cross-chain message
reset() Between runs Reset bridge state to post-deploy baseline
destroy() Teardown Tear down relayer and clean up deployed contracts

Agent Plugin

prepare() → [observe() → think() → respond()]* → verify()
Method Called Purpose
prepare() Once Set up agent environment
observe() Per iteration Gather observations from the environment
think() Per iteration Decide what action to take (return AgentAction or None)
respond() Per iteration Process the result of the action
verify() End Verify the agent achieved its objective

Best Practices

1. Always Return Structured Results

Always return AttackResult with phase_results containing individual step results:

return AttackResult(success=True, phase_results=[
    {"step": "check_contract", "passed": True, "detail": "Contract has code"},
    {"step": "exploit_execution", "passed": True, "detail": tx_hash},
])

Each phase result appears in the run manifest and is visible in crucible history.

2. Use the LogEmitter

Don't print() — use context.log.step():

context.log.step(
    "Verifying contract code at fork block",
    phase="attack", action="check_code", status="success",
    contract=CONTRACT_ADDRESS,
    fork_block=fork_block,
)

3. Handle Chain Unavailability Gracefully

When creating multi-chain plugins, wrap per-chain operations in try/except:

for chain_name in ["ethereum", "polygon"]:
    try:
        client = context.chains.runtime_for(chain_name)
        code = client.get_code(CONTRACT_ADDRESS)
        if code and code != "0x":
            results[chain_name] = True
    except Exception as exc:
        context.log.step(
            f"Skipping {chain_name}: {exc}",
            phase="attack", action="check_code", status="warning",
        )

4. Store Important Addresses as Constants

VULNERABLE_CONTRACT = "0x..."
ATTACKER_ADDRESS = "0x..."
FUNCTION_SELECTOR = "0x..."

5. Document Fidelity Constraints

In evidence.yaml, be honest about what your plugin cannot reproduce:

reproduction_scope:
  excluded_components:
    - "Solana-side validators (non-EVM — cannot fork)"
    - "Off-chain MPC key generation"

Common Pitfalls

1. Double 0x Prefix in Bytecode

When deploying contracts, Foundry .json artifacts already include the 0x prefix:

# WRONG — double 0x prefix
bytecode = "0x" + artifact["bytecode"]  # artifact["bytecode"] already starts with 0x

# RIGHT
bytecode = artifact["bytecode"]

2. EOA vs Contract Addresses

Always verify that target addresses are contracts, not EOAs:

code = client.get_code(address)
if not code or code == "0x":
    # This is an EOA, not a contract!
    raise ValueError(f"Expected contract at {address}, got EOA")

3. Archive RPC Limitations

Polygon and BSC archive RPCs at old fork blocks may not serve state for newly created addresses. This affects anvil_setBalance when bridge plugins try to fund deployer addresses. Always wrap per-chain deployment in try/except.

4. Non-EVM Boundaries

Crucible is EVM-only. Attacks involving Solana, Cosmos, Harmony ONE, or Substrate chains must be documented in excluded_components — they cannot be reproduced on-chain.


Testing Your Plugin

1. Validate the Plugin Loads

crucible plugin validate attacks/my_exploit

This checks: - Plugin manifest (plugin.yaml) is well-formed - Entry point file exists - Class can be imported and instantiated - Evidence (evidence.yaml) has all required sections

2. Check Evidence Against Live Chain

crucible evidence check my_exploit --fork

This forks the chain at the configured block and verifies: - Fork block exists via eth_getBlockByNumber - Declared contracts have non-empty code via eth_getCode

3. Run the Experiment

crucible fork --topology single
crucible experiment run experiments/my_exploit.yaml

4. Verify Determinism

# Run twice
crucible experiment run experiments/my_exploit.yaml --name run-a
crucible experiment run experiments/my_exploit.yaml --name run-b

# Compare
crucible diff <run-a-id> <run-b-id>

All four metrics must be true: - storage_equal - events_equal - gas_equal - balances_equal

5. Export for Publication

# Export bundle
crucible export <run-id>

# Verify bundle integrity
crucible verify datasets/<run-id>

See Also

Doc What It Covers
Attack Pack Guide Step-by-step attack creation from existing examples
Scenario Authoring Writing scenario YAML files
Custom Contract Testing Deploy and test your own Solidity contracts
Technical Overview System architecture and plugin system overview
SDK Reference Complete API reference for all plugin types