如何为 ERC20 转账写 fuzz 测试?

解读

国内 DeFi 团队面试时,面试官真正想确认的是:

  1. 你是否理解“ERC20 转账”在业务层、合约层、Python 测试层的三层边界;
  2. 能否用 Pytest 生态把“随机输入→链上调用→断言不变量”封装成可持续集成、可本地复现的自动化用例;
  3. 是否知道怎么把 fuzz 结果与覆盖率、gas 消耗、事件日志一起归档,供审计与回归使用。

因此,回答必须体现:Pytest 插件化设计、hypothesis 策略、web3.py 链交互、不变量断言、失败用例最小化、CI 本地一致性六要素。

知识点

  1. Pytest 基础:conftest.py、fixture 作用域、hook 定制、参数化、replay 文件。
  2. hypothesis 核心:@given 装饰器、strategies、assume()、event()、target()、database 目录、example 最小化。
  3. web3.py:EthereumTesterProvider、eth-tester 后端、py-evm 沙盒、time_travel、snapshot/revert。
  4. ERC20 不变量:totalSupply 守恒、balance 非负、transfer/transferFrom 返回值 true、Approval 事件完整性、allowance 精确扣减、溢出回滚。
  5. 国内合规:不连公链,用本地链;私钥与助记词走环境变量,禁止硬编码。
  6. 性能:pytest-xdist 并行、pytest-cov 覆盖率、pytest-html 中文报告、allure 归档。

答案

项目结构(符合国内习惯,requirements.txt 已固定版本): tests/ ├── conftest.py ├── erc20/ │ ├── sol/ │ │ └── MockERC20.sol │ ├── abi/ │ │ └── MockERC20.json │ └── test_erc20_fuzz.py pytest.ini .gitlab-ci.yml

  1. 环境准备(conftest.py)
import os
import pytest
from web3 import Web3, EthereumTesterProvider
from eth_account import Account
from eth_utils import to_checksum_address
from solcx import compile_standard

SNAPSHOT_ID = "snapshot_id"

@pytest.fixture(scope="session")
def w3():
    w3 = Web3(EthereumTesterProvider())
    w3.eth.set_gas_price_strategy(lambda w, tx: 0)
    return w3

@pytest.fixture(scope="session")
def accounts(w3):
    return [to_checksum_address(acc) for acc in w3.eth.accounts]

@pytest.fixture(scope="session")
def erc20_bytecode():
    return compile_standard({
        "language": "Solidity",
        "sources": {"MockERC20.sol": {"content": open("tests/erc20/sol/MockERC20.sol").read()}},
        "settings": {"outputSelection": {"*": {"*": ["abi", "evm.bytecode"]}}}
    })["contracts"]["MockERC20.sol"]["MockERC20"]

@pytest.fixture
def erc20(w3, accounts, erc20_bytecode):
    Mock = w3.eth.contract(abi=erc20_bytecode["abi"], bytecode=erc20_bytecode["evm"]["bytecode"]["object"])
    tx_hash = Mock.constructor("Mock", "MOK", 18, 10**26).transact({"from": accounts[0]})
    address = w3.eth.get_transaction_receipt(tx_hash)["contractAddress"]
    yield w3.eth.contract(address=address, abi=erc20_bytecode["abi"])
  1. 核心 fuzz 用例(test_erc20_fuzz.py)
import pytest
from hypothesis import given, strategies as st, assume, event, target
from eth_utils import to_checksum_address

# 策略:地址从 20 个预生成账户里取,金额用 uint112 范围
addr_strategy = st.sampled_from([...])  # 20 个地址
amount_strategy = st.integers(min_value=0, max_value=2**112 - 1)

class Invariants:
    def __init__(self, w3, contract):
        self.w3 = w3
        self.c = contract

    def supply_constant(self):
        return self.c.functions.totalSupply().call()

    def balance_ge_zero(self, addr):
        return self.c.functions.balanceOf(addr).call() >= 0

@given(sender=addr_strategy, receiver=addr_strategy, amt=amount_strategy)
def test_transfer_invariants(w3, erc20, accounts, sender, receiver, amt):
    assume(sender != receiver)
    inv = Invariants(w3, erc20)
    supply_before = inv.supply_constant()
    bal_sender_before = erc20.functions.balanceOf(sender).call()
    bal_receiver_before = erc20.functions.balanceOf(receiver).call()

    # 快照
    snap = w3.testing.snapshot()

    tx_hash = erc20.functions.transfer(receiver, amt).transact({"from": sender})
    receipt = w3.eth.get_transaction_receipt(tx_hash)
    assert receipt["status"] == 1, "transfer must succeed"

    # 不变量
    assert inv.supply_constant() == supply_before, "totalSupply must be constant"
    assert inv.balance_ge_zero(sender) and inv.balance_ge_zero(receiver), "balance must >=0"
    assert erc20.functions.balanceOf(sender).call() == bal_sender_before - amt
    assert erc20.functions.balanceOf(receiver).call() == bal_receiver_before + amt

    # 事件检查
    logs = erc20.events.Transfer().process_receipt(receipt)
    assert len(logs) == 1
    assert logs[0]["args"]["from"] == sender
    assert logs[0]["args"]["to"] == receiver
    assert logs[0]["args"]["value"] == amt

    # 性能指标
    gas_used = receipt["gasUsed"]
    target(gas_used)  # hypothesis 会尝试最大化 gas 以找边界
    event(f"gas:{gas_used}")

    # 回滚保证用例独立
    w3.testing.revert(snap)
  1. 本地复现与 CI
# 本地
pytest tests/erc20/test_erc20_fuzz.py --hypothesis-show-statistics \
        --hypothesis-profile ci -n auto --dist loadscope \
        --cov=tests --cov-report=html --html=report.html

# .gitlab-ci.yml
test-fuzz:
  stage: test
  image: python:3.11-slim
  script:
    - pip install -r requirements.txt
    - pytest tests/erc20/test_erc20_fuzz.py --hypothesis-profile ci --junitxml=junit.xml
  artifacts:
    reports:
      junit: junit.xml
    paths:
      - htmlcov/
      - report.html
    expire_in: 7 days
  1. 失败最小化 hypothesis 自动把失败用例写入 .hypothesis/examples/;CI 失败后可本地执行:
pytest tests/erc20/test_erc20_fuzz.py::test_transfer_invariants \
     --hypothesis-seed=123456

即可 100% 复现,方便调试。

拓展思考

  1. 状态ful fuzz:若 ERC20 有 mint/burn,可用 hypothesis.stateful 把 transfer、approve、transferFrom、mint、burn 做成 RuleBasedStateMachine,检查“总供应量 = 各地址余额之和”这一全局不变量。
  2. 符号执行互补:用 mythril 做静态符号执行,把发现的“可能溢出路径”转成 hypothesis 策略的边界值,实现动静态混合。
  3. 多链适配:国内 BSN 文昌链、长安链都兼容 EVM,只需把 EthereumTesterProvider 换成对应测试网 JSON-RPC,其他代码零改动即可跑在国产链上。
  4. 回归加速:把每次 CI 的 .hypothesis/examples/ 目录缓存到 GitLab 缓存桶,下次跑先加载旧失败用例,实现“失败优先”回归,平均节省 30% 时间。
  5. 审计报告:用 pytest-allure-adaptor2 生成中文图文报告,把 gas 热点、路径覆盖、异常回滚截图自动插入,审计师可直接在页面上批注,满足国内券商 DeFi 审计合规要求。