# Ctf Blockchain Foundry Workflows

> Use when a blockchain CTF exploit should be developed and tested with Foundry before it touches the challenge chain. Covers Foundry project setup, fork testing against a challenge RPC, writing exploit tests with cheatcodes, tracing failures with verbose test output, deploying attacker contracts, and replaying a proven exploit against the live challenge. Use when a challenge gives you contract source and an RPC endpoint, when an exploit needs iteration without spending challenge funds, or when you need a repeatable local workflow from first test to flag.

- Skill: `mizazhaider-ceh/ctf-blockchain-foundry-workflows` (Agent Skill)
- Install (CLI): `npx get-skill add mizazhaider-ceh/ctf-blockchain-foundry-workflows`
- Raw SKILL.md: https://api.skillmd.com/api/skills/mizazhaider-ceh/ctf-blockchain-foundry-workflows/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Security
- Author: mizazhaider-ceh (https://skillmd.com/u/mizazhaider-ceh)
- Updated: 2026-11-22
- Page: https://skillmd.com/skills/mizazhaider-ceh/ctf-blockchain-foundry-workflows

---


Foundry is the iteration engine for blockchain CTF work. The whole
workflow is: fork the challenge chain locally, write the exploit as
a test, watch it fail with a full trace, fix it, watch it pass, and
only then replay it against the real RPC. Players who skip the local
step burn challenge funds and challenge attempts on guesses. This
sub-skill covers the authorized Foundry workflow end to end, from
project setup to replay. Scope is CTF competitions, lab chains, and
systems you have explicit permission to test, using only the keys
and funds the challenge provides.

## Quick Workflow

1. Scaffold a project and add the challenge contracts and interfaces.
2. Start a local fork with Anvil pointed at the challenge RPC.
3. Write the exploit as a Foundry test with explicit assertions for
   the win condition.
4. Run with full traces, read the revert, and fix one thing at a time.
5. Prove the win condition passes locally with a clean test run.
6. Convert the passing test into a script or a cast sequence for
   the live chain.
7. Replay against the challenge RPC, verify the win condition on
   chain, and capture the flag.
8. Save the test, the script, and the traces for the writeup.

## 1. Project setup and fork testing

Keep one directory per challenge so addresses, keys, and traces do
not leak between challenges.

```bash
# Scaffold the project (run once per challenge)
mkdir -p chain-ctf && cd chain-ctf
forge init --no-git --force 2>/dev/null || true
mkdir -p src test script

# Start a fork at a fixed block so results are reproducible
anvil --fork-url https://chals.ctf:8545 --fork-block-number 1000000 --port 8545 &
echo $! > anvil.pid

# Confirm the fork serves the challenge state
curl -s -X POST http://127.0.0.1:8545 \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"eth_blockNumber","params":[]}'
```

```bash
# foundry.toml - pin the compiler and the RPC profiles for this challenge
cat > foundry.toml <<'EOF'
[profile.default]
solc = "0.8.28"
optimizer = true
optimizer_runs = 200

[rpc_endpoints]
local = "http://127.0.0.1:8545"
challenge = "https://chals.ctf:8545"
EOF
cat foundry.toml
```

## 2. Writing an exploit test with cheatcodes

Cheatcodes are the test superpowers: impersonate accounts, fund
them, warp time, and prank calls. Use them to set up exactly the
state the exploit needs.

```solidity
// test/Exploit.t.sol - template, adapt the interface, addresses,
// and win condition to the challenge.
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;

import "forge-std/Test.sol";

interface ITarget {
    function owner() external view returns (address);
    function deposit() external payable;
    function withdraw(uint256 amount) external;
}

contract ExploitTest is Test {
    ITarget public target;
    address public player = address(0xBEEF);

    function setUp() public {
        target = ITarget(address(0x0000000000000000000000000000000000000000));
        vm.deal(player, 100 ether);
        // Fund the target the way the challenge setup does, if the
        // challenge does not fund it already on the fork.
        vm.deal(address(target), 50 ether);
    }

    function testExploit() public {
        vm.startPrank(player);
        target.deposit{value: 1 ether}();
        target.withdraw(1 ether);
        vm.stopPrank();
        // Win condition goes here, for example ownership or balance.
        // assertEq(target.owner(), player);
        assertGe(address(player).balance, 1 ether);
    }

    function testTrace() public {
        // A second test that only prints state, useful when the
        // main test reverts and the trace alone is not enough.
        emit log_named_uint("player balance", address(player).balance);
        emit log_named_uint("target balance", address(target).balance);
    }
}
```

```bash
# Run, trace, and iterate (the core loop of this sub-skill)
forge test --match-test testExploit -vvvv 2>&1 | head -120
forge test --match-test testExploit -vvv 2>&1 | tail -30
```

Reading a trace in order: the last call before the revert is the
failing call, its arguments show what you sent, and the revert
reason (or the absence of one) tells you whether it was an access
check, a balance check, or a missing function.

## 3. Deploying the attacker and replaying live

Once the test passes, the same attacker contract and call sequence
become the live exploit. Deploy from the player key the challenge
gave you, never from a personal key.

```bash
# Deploy the attacker contract to the local fork first
forge create src/Attacker.sol:Attacker \
  --rpc-url http://127.0.0.1:8545 \
  --private-key 0x0000000000000000000000000000000000000000000000000000000000000001 \
  --constructor-args 0x0000000000000000000000000000000000000000

# Drive the attacker with cast, logging every call
ATTACKER="0x0000000000000000000000000000000000000000"
PLAYER_KEY="0x0000000000000000000000000000000000000000000000000000000000000001"
cast send "$ATTACKER" "attack()()" \
  --rpc-url http://127.0.0.1:8545 \
  --private-key "$PLAYER_KEY" --value 1ether

# Verify the win condition on the fork before touching the live chain
cast call "$ATTACKER" "count()(uint256)" --rpc-url http://127.0.0.1:8545
```

```bash
# Replay against the challenge RPC only after the fork run passes.
# Replace the RPC URL and the key with the challenge provided values,
# and keep the exact same call order and values as the local run.
cast send "$ATTACKER" "attack()()" \
  --rpc-url https://chals.ctf:8545 \
  --private-key "$PLAYER_KEY" --value 1ether

# Verify the win condition on the challenge chain
cast call "$ATTACKER" "count()(uint256)" --rpc-url https://chals.ctf:8545
```

A Foundry script (`forge script`) is the better replay vehicle when
the exploit has several ordered calls, since it runs them in one
process with explicit broadcast logging. Keep the script next to
the test so the writeup can reproduce both.

## Edge cases

- The fork block number is stale and the challenge state moved.
  Re-fork at a recent block and re-run the test before replaying.
- The test passes locally but the live call reverts. Compare
  chain ID, addresses, balances, and gas, and check whether the
  live chain has a different deployment of the same contract.
- Cheatcode state leaks between tests. Reset state in `setUp`
  and avoid relying on a previous test having run first.
- The compiler version in `foundry.toml` differs from the
  challenge build. Match the challenge pragma exactly, since
  optimizer and version differences change behavior at the edges.
- Anvil fork rate limits against the challenge RPC. Cache the
  fork, run tests offline against the local node, and only refetch
  when the challenge state actually changes.
- The attacker contract needs ether on the live chain. Use only
  the funds the challenge provides, and check the balance before
  the replay so a failed send does not hide behind a gas error.

## Escalation

- Traces do not explain the revert. Add `emit log` statements
  around each call, shrink the test to one call, and bisect which
  call reverts.
- The exploit needs a flash loan or a multi contract dance.
  Build it as an attacker contract method, test it on the fork,
  and only then script the live calls in the same order.
- Fork testing is impossible because the RPC is closed. Deploy
  the challenge contracts locally from source and test against
  that deployment, noting any setup differences.
- The live replay succeeds but the checker still says unsolved.
  Re-read the setup contract win condition, it may require a
  separate `solve` or `claim` call after the drain.

## Key references

- Foundry book, the canonical guide to forge, cast, and Anvil:
  https://getfoundry.sh/
- Solidity documentation: https://docs.soliditylang.org/
- CWE-841 (Improper Enforcement of Behavioral Workflow) for
  reentrancy ordering bugs.
- CWE-862 (Missing Authorization) for access control failures.
- OpenZeppelin Contracts security guidance:
  https://docs.openzeppelin.com/contracts/

