レッスン6 — Capstone — openhl-liquidation の InsuranceFund を Solidity へ port し 4 つの invariant を証明する
問い
Capstone = openhl-liquidation Stage 10b の InsuranceFund を Rust から Solidity へ port(EVM contract として adapt)、4 つの保存則 invariant を Foundry で書き、invariant テストで回す(default は 256 runs × depth 50、CI profile は 2,000 runs × depth 100)。同じ定理を 2 言語で mechanical に証明、規律の transfer 完了の証跡。
原理(最小モデル)
- Capstone target. openhl-liquidation Stage 10b の
InsuranceFund(Rust、openhl260883bのcrates/liquidation/src/insurance.rs:balance: i641 つ、deposit、withdraw_shortfall)→InsuranceFund.sol。withdraw_shortfallはabsorb(loss) returns (absorbed, remaining)になり、running total・owner・owner 限定withdrawは EVM 版での追加。 - 4 invariants(companion リポジトリの
examples/foundry-capstone/). ①invariant_Conservation:balance == deposits − withdrawn − absorbed、②invariant_DepositAccounting:totalDeposited == ghostSumDeposits、③invariant_WithdrawAccounting:totalWithdrawn == ghostSumWithdrawn、④invariant_AbsorbDecomposition:absorbed + unabsorbed == loss requested— liquidation コースのwithdraw_shortfallレッスンのamount + unfilled == shortfallの系列版。 InsuranceFund.solの構造.uint256state(balance/totalDeposited/totalWithdrawn/totalAbsorbed)+address immutable owner、deposit(uint256)/withdraw(uint256)(owner 限定)/absorb(uint256)。Rust のsaturating_addではなく Solidity 0.8 の checked arithmetic(overflow は revert)。- Test harness.
InsuranceFundHandlerがwrappedDeposit/wrappedWithdraw/wrappedAbsorbを公開し 5 つの ghost 変数を保持、InsuranceFundInvariantTestがtargetContract(address(handler))+ 4invariant_*関数。 - Run の規模. Default
[invariant] runs = 256, depth = 50→ invariant あたり 12,800 call、[profile.ci.invariant] runs = 2000, depth = 100→ invariant あたり 200,000 call。 - 答え合わせ. コースの companion リポジトリ(
psyto/rethlabのexamples/foundry-capstone/)に同じ 3 ファイルがある。companion リポジトリの commit を checkout すれば固定版が得られる。 - 規律の transfer 完了の証跡. 4 invariant pass = Rust proptest が検査した shortfall 法則を Solidity invariant test が call 系列で検査(invariant 4)、加えて EVM 版独自の bookkeeping も検査(invariant 1–3)、規律が言語境界を越えて transfer された証拠。
具体例 + ステップで組み立てる
レッスン 6 — Capstone — openhl-liquidation の InsuranceFund を Solidity へ port し、4 つの invariant を証明する
ゴール
このレッスンで掴む概念:
- Capstone は、コースの thesis を散文ではなくコードで証明する。 レッスン 0–レッスン5のすべては 1 つの主張のための setup だった。openhl liquidation コースで使った保存則(Conservation law)規律は Solidity に機械的に転写でき、invariant テストは
proptest!と同じやり方でそれを証明する — この主張だ。レッスン 6 はその主張を読むのをやめ、実行する 場所だ。openhl-liquidation Stage 10b のInsuranceFund(システムの最後の防衛線となる資本を保持する Rust の型) を取り、shortfall ロジックを保ったまま、EVM contract に必要な bookkeeping を加えて Solidity に port する。単発の operation をランダムな call 系列に変えるHandlerを書く (liquidation コースのwithdraw_shortfallレッスンのbalance_never_negativeproptest と同じ形状)。そして 4 つの保存則 invariant を証明する。そのうち 1 つは、liquidation コースのwithdraw_shortfallレッスンが Rust で証明した property の系列版だ。緑の(runs: 256, calls: 12800, reverts: 0)行が表示された瞬間にコースは終わる。規律転写(Discipline transfer)が言語境界を survive したと、その時に実演し終えている。 - 4 つの invariant、1 つの形状。contract state と ghost accounting の間の等価性として書かれた保存則だ。 この capstone のすべての invariant は
<contract observable> == <ghost variable の関数>の形を取る。(1) Conservation:fund.balance() == ghostSumDeposits - ghostSumWithdrawn - ghostSumAbsorbed。(2) Deposit accounting:fund.totalDeposited() == ghostSumDeposits。(3) Withdraw accounting:fund.totalWithdrawn() == ghostSumWithdrawn。(4) Absorb decomposition:ghostSumAbsorbed + ghostSumUnabsorbed == ghostSumLossRequested。Invariant 4 はliquidation コースのwithdraw_shortfallレッスンのamount + unfilled == shortfallを引き継ぐ。Invariant 1〜3 は Solidity 側の bookkeeping を check する (Rust の fund はbalanceしか持たないので、check すべき total がない)。1 つの保存則形状を、4 つの異なる observable に対して 4 回使う。 - Handler こそが Rust↔Solidity の同型対応(Isomorphism)が住む場所だ。
InsuranceFundHandlerは Solidity contract で、wrappedDeposit(uint256)/wrappedWithdraw(uint256)/wrappedAbsorb(uint256)を公開し、5 つの ghost 変数を維持する。各 method は入力を bound し (invariant テストのランダム parameter が常に productive な call を生むため、vm.assumerejection を避けるため)、ghost を target と lockstep で更新する。最も近い Rust 側の対応物はinsurance.rsのbalance_never_negativeproptest で、deposit と shortfall withdraw のランダムなVec<(bool, i64)>を走らせる。Handler はその発想を 3 operation + ghost accounting に拡張したものだ。同じ発想 — model に対するランダムな operation 系列 — を、bookkeeping を明示して書く。 - レッスンの deliverable は permanent。
examples/foundry-capstone/に住む。 このレッスンで build するすべて (src/InsuranceFund.sol、test/InsuranceFundHandler.sol、test/InsuranceFund.invariant.t.sol) は、コースの答え合わせとして in-repo に残る。レッスン5を卒業する将来の reader は、自分の作業をまさにこのディレクトリに対して check する。Capstone は disposable ではない。コースが動くことを証明する最終 artifact だ。
確認:
cd examples/foundry-capstone
forge test --match-contract InsuranceFundInvariantTest -vvv
…で 4 つの invariant それぞれに対して [PASS] invariant_Conservation() (runs: 256, calls: 12800, reverts: 0) が表示される。本レッスン完走後はこれらを手にする。Full な capstone を build した経験、12,800 ランダム call にわたって invariant が成立し続けるのを観察した経験、意図的に 1 つを壊して multi-call counterexample を読んだ経験、そして openhl の insurance.rs にある Rust proptest! property と side-by-side で比較した経験。
具体的な変更:
- 新規ディレクトリ
examples/foundry-capstone/— コースの pragma^0.8.35に pin したforge init形状の Foundry プロジェクト。Sub-project として扱い、レッスン Web サイトの build には含めない。 - そのディレクトリ内に新規 Solidity ファイル 3 つ —
src/InsuranceFund.sol(51 行)、test/InsuranceFundHandler.sol(57 行)、test/InsuranceFund.invariant.t.sol(58 行)。Capstone 全体で合計 ~166 行。
レッスン 6 は密度が高い。60 分が時間予算で、半分が Solidity port、半分が invariant テスト 実行と Rust ソースとの比較に充てる。Payoff は、4 つの緑の invariant が表示され、保存則規律が言語を超えて運ばれたと腹落ちする瞬間だ。
おさらい
レッスン5の後はこうなっている。
- レッスン0 — Foundry が commodity prerequisite として positioned + REVM が統一エンジン
- レッスン 1〜3 — Solidity testing 規律。
forge test、fuzz テスト、invariant テスト (Handler パターン、ghost 変数、sequence counterexample) - レッスン4 —
castがalloy::Provider上の CLI surface - レッスン5 —
anvilがローカル mainnet クローン + 3-surface REVM アーキテクチャ
レッスン 6 がループを閉じる。レッスン 0–レッスン5のすべての概念が capstone で使われる。
- レッスン1 / レッスン5 の
vm.prank— Handler が owner として withdraw する - レッスン3の invariant テスト — multi-call sequencing engine
- レッスン3の Handler パターン —
InsuranceFundHandlerがCounterHandlerの形状をミラーする - レッスン3の ghost 変数 accounting —
InsuranceFundHandlerの 5 つの ghost
コースは常にこの artifact を指していた。中間レッスンはすべて prerequisite だった。
計画
7 ステップ、3 つの Solidity ファイルにまたがる。
- Capstone プロジェクトをセットアップ —
mkdir examples/foundry-capstone && cd examples/foundry-capstone && forge init --no-git。Pragma を pin。Default の Counter を delete。 - openhl-liquidation Stage 10b の
InsuranceFundソースを読む —crates/liquidation/src/insurance.rsの Rust 型 (openhl commit260883b)。唯一のフィールド (balance: i64)、2 つの operation (deposit、withdraw_shortfall)、WithdrawOutcomeenum を特定する。 src/InsuranceFund.solを書く —absorbがwithdraw_shortfallを翻訳する。total、owner、withdrawは EVM 版での追加。test/InsuranceFundHandler.solを書く —wrappedDeposit/wrappedWithdraw/wrappedAbsorbと、5 つの ghost 変数 (ghostSumDeposits、ghostSumWithdrawn、ghostSumAbsorbed、ghostSumUnabsorbed、ghostSumLossRequested) を持つ Handler。test/InsuranceFund.invariant.t.solを書く — 4 つの invariant。invariant_Conservation、invariant_DepositAccounting、invariant_WithdrawAccounting、invariant_AbsorbDecomposition。- invariant テストを走らせる — 4 つの invariant すべてが default の 256 runs × 50 depth = 12,800 call で成立する。重い run には CI profile (invariant あたり 200,000 call) を使う。
- 意図的な break デモ + Rust proptest との side-by-side — Handler の ghost update を 1 つ壊し、multi-call counterexample が現れるのを見る。次に Solidity の invariant を
insurance.rsの Rustproptest!property と並べる。
確認問題: 「balance = deposit − withdraw − absorb」を Solidity の assertion で書くと?
(答え: assertEq(fund.balance(), handler.ghostSumDeposits() - handler.ghostSumWithdrawn() - handler.ghostSumAbsorbed());。Rust の prop_assert_eq!(left, right) と同じ形だ。主な違いは、ghost アクセサが明示的な handler.X() 呼び出しになること (Solidity は別 contract のフィールドを直接読めないため)。変換が機械的になるのは、下層の定理が言語非依存だからだ。保存則は構文ではなく数学だ。)
Deliverable ファイルツリー
examples/foundry-capstone/
├── foundry.toml ← invariant runs、depth、fail_on_revert
├── src/
│ └── InsuranceFund.sol ← 51 行 — Solidity port
├── test/
│ ├── InsuranceFundHandler.sol ← 57 行 — 3 wrapped method + 5 ghost を持つ Handler
│ └── InsuranceFund.invariant.t.sol ← 58 行 — 4 つの invariant_* 関数
└── lib/forge-std/ ← standard な forge-std submodule
レッスン6を完了したとき、このツリーのすべてのファイルが存在し、forge test が 12,800+ ランダム系列で 4 つの invariant assertion を pass させる。
Rust ↔ Solidity フィールド マッピング
┌────────────────────────────────────────┬──────────────────────────────────────────┐
│ openhl Stage 10b (Rust, 260883b) │ examples/foundry-capstone (Solidity) │
│ crates/liquidation/src/insurance.rs │ │
├────────────────────────────────────────┼──────────────────────────────────────────┤
│ struct InsuranceFund { balance: i64 } │ contract InsuranceFund │
│ │ uint256 public balance; │
│ (no counterpart) │ totalDeposited / totalWithdrawn / │
│ │ totalAbsorbed; immutable owner │
├────────────────────────────────────────┼──────────────────────────────────────────┤
│ fn deposit(&mut self, fee: i64) -> i64│ function deposit(uint256 amount) │
│ (fee <= 0 is a no-op; saturating) │ (reverts on 0; checked arithmetic) │
│ fn withdraw_shortfall(&mut self, │ function absorb(uint256 loss) │
│ shortfall: i64) -> WithdrawOutcome │ returns (absorbed, remaining) │
│ amount + unfilled == shortfall │ absorbed + remaining == loss │
│ (no counterpart) │ function withdraw(uint256) — owner-only │
├────────────────────────────────────────┼──────────────────────────────────────────┤
│ 4 proptest! properties in mod tests │ 4 invariant_* functions (this lesson) │
└────────────────────────────────────────┴──────────────────────────────────────────┘
マッピングは 1 対 1 ではない。保存則を運ぶ核 — withdraw_shortfall → absorb、amount + unfilled == shortfall → absorbed + remaining == loss — はそのまま翻訳される。running total、owner、owner 限定の withdraw は EVM 版での追加だ (invariant が check できる contract 側の bookkeeping を与える)。核は翻訳し、追加は追加と明記する。
手を動かす walk-through
Step 1: Capstone プロジェクトをセットアップする
companion リポジトリの root から実行する:
mkdir -p examples/foundry-capstone
cd examples/foundry-capstone
forge init --no-git
--no-git は、この capstone を companion リポジトリのサブディレクトリとして抱えたいからだ (それ自身の git project にはしたくない。lib/forge-std は forge が入れる)。結果 (ほかに README.md も生成される):
examples/foundry-capstone/
├── foundry.toml
├── src/Counter.sol ← これを削除
├── test/Counter.t.sol ← これを削除
├── script/Counter.s.sol ← これを削除 (option)
└── lib/forge-std/
Counter テンプレートを削除:
rm src/Counter.sol test/Counter.t.sol script/Counter.s.sol
foundry.toml を更新して pragma + invariant default を pin する:
[profile.default]
src = "src"
out = "out"
libs = ["lib"]
solc = "0.8.35"
[invariant]
runs = 256
depth = 50
fail_on_revert = false
[profile.ci.invariant]
runs = 2000
depth = 100
クリーンスレートの準備完了だ。
Step 2: Rust ソースオブトゥルースを読む
openhl の commit 260883b (Stage 10b) で crates/liquidation/src/insurance.rs を開く。構造要素を特定する:
- state フィールド 1 つ:
balance: i64(private、fn balance()で読む)。new(initial)は負の初期値を 0 に clamp する - 2 つの operation:
deposit(fee: i64) -> i64(feeが 0 以下なら no-op、saturating_addでi64::MAXに cap) とwithdraw_shortfall(shortfall: i64) -> WithdrawOutcome - error はない: 不正な入力は
Errではなく no-op (0 以下の shortfall はCovered { amount: 0 }を返す) withdraw_shortfallの decomposition 形状:Covered { amount }/PartiallyDrained { amount, unfilled }/Depleted { unfilled }、常にamount + unfilled == shortfall
Solidity 版はこの decomposition を absorb(loss) -> (absorbed, remaining) (absorbed = min(loss, balance)、remaining = loss - absorbed) として保ち、invariant test を持つ EVM contract に必要なもの — running total、owner、owner 限定の withdraw、custom error による revert — を加える。
Step 3: src/InsuranceFund.sol を書く
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.35;
/// @notice Solidity adaptation of openhl-liquidation Stage 10b's InsuranceFund.
/// `absorb` mirrors Rust's `withdraw_shortfall` (absorbed + remaining == loss);
/// the totals, `owner` and `withdraw` are Solidity-side additions.
contract InsuranceFund {
uint256 public balance;
uint256 public totalDeposited;
uint256 public totalWithdrawn;
uint256 public totalAbsorbed;
address public immutable owner;
error ZeroAmount();
error NotOwner();
error InsufficientBalance(uint256 requested, uint256 available);
constructor(address _owner) {
owner = _owner;
}
/// Counterpart of Rust's `fn deposit(&mut self, fee: i64) -> i64`.
/// Anyone can deposit; zero reverts (Rust treats fee <= 0 as a no-op).
function deposit(uint256 amount) external {
if (amount == 0) revert ZeroAmount();
balance += amount;
totalDeposited += amount;
}
/// No Rust counterpart: an owner-only withdrawal added for the EVM version.
/// Reverts on zero, non-owner, or insufficient balance.
function withdraw(uint256 amount) external {
if (msg.sender != owner) revert NotOwner();
if (amount == 0) revert ZeroAmount();
if (amount > balance) revert InsufficientBalance(amount, balance);
balance -= amount;
totalWithdrawn += amount;
}
/// Counterpart of Rust's `fn withdraw_shortfall(&mut self, shortfall: i64) -> WithdrawOutcome`.
/// Absorbs as much loss as the balance allows; returns (absorbed, remaining)
/// where absorbed + remaining == loss. Remaining is what the fund
/// couldn't cover — in the real system, this flows to ADL.
function absorb(uint256 loss) external returns (uint256 absorbed, uint256 remaining) {
if (loss == 0) revert ZeroAmount();
absorbed = loss > balance ? balance : loss;
remaining = loss - absorbed;
balance -= absorbed;
totalAbsorbed += absorbed;
}
}
押さえる点が 7 つ。load-bearing な翻訳決定だ。
-
i64→uint256。 Rust の fund はbalance: i64を持ち、負の入力を 0 に clamp する。Solidity 版は unsigned のuint256なので負の量はそもそも表現できない。保存則の形は変わらない。unsigned 型が Rust のbalance >= 0property を型の保証に変える。 -
Rust の no-op → Solidity の revert。 Rust の fund は error を返さない: 0 以下の deposit / shortfall は黙って no-op になる。Solidity 版は custom error (
ZeroAmount、NotOwner、InsufficientBalance) で revert する — EVM の通常スタイルで、2 つを比較するときに覚えておくべき意図的な挙動差だ。 -
WithdrawOutcomeenum →(absorbed, remaining)tuple。 Rust の 3 variant は 1 つの tuple に畳まれる:Covered { amount }=(loss, 0)、PartiallyDrained { amount, unfilled }=(balance, loss - balance)、Depleted { unfilled }=(0, loss)。等式amount + unfilled == shortfallはabsorbed + remaining == lossになる。 -
Rust の getter →
publicstorage。 Rust はbalanceを private にしてfn balance()で読ませる。Solidity のpublicキーワードは同種の getter (balance()) を自動生成するので、Handler と invariant contract がカスタム view 関数なしで state を読める。 -
ownerは新規。 Rust の fund には owner がない (Stage 10c ではLiquidationScannerが所有する)。Solidity contract はwithdrawを access control するためにimmutable ownerを加える。 -
Saturating vs checked arithmetic。 Rust の
depositはsaturating_add(i64::MAXで cap) を使う。Solidity 0.8 の算術は checked で、overflow は saturate せずPanic(0x11)で revert する。Handler は入力をtype(uint96).maxに bound するので、この test では overflow は起きない。目的 (黙った wrap-around を防ぐ) は同じ、失敗の仕方が違う。[!NOTE]
uncheckedブロックによる Rust の wrapping 挙動の模倣とガス最適化 Solidity 0.8+ では、オーバーフロー/アンダーフローを許容する wrapping 算術(Rust のwrapping_addやwrapping_subに相当)を行いたい場合、あるいはガス効率を極限まで高めて Rust 実装と同等のガスプロファイルに近づけたい場合、unchecked { ... }ブロックを使用します:unchecked { balance -= amount; // ガス節約、または意図的な wrapping 動作 }uncheckedは Solidity の標準的なオーバーフローチェックコード生成(Panic(0x11)をスローする条件分岐)を無効化するため、ガスコストを削減できる。インフラエンジニアとしては、安全性が必要な場所(デフォルトの安全な算術評価)と、すでに手動で境界値チェック(bounds check)を済ませてオーバーフローが絶対に起き得ないためガスを節約したい場所(unchecked)を厳格に区別して設計する習慣が重要だ。 -
uint256 public balanceは意図的に storage 変数 であって、EVM ネイティブのaddress(this).balanceではない。 Rust ソースが自身の明示的なbalanceフィールドを保持しているから、port はそのフィールドをミラーする。これは冗長ではない — 隔離 だ。Contract address への強制的な ETH 送金 (別 contract からのselfdestruct経由など) はdepositを通らずにaddress(this).balanceを mutate する。Fund が EVM ネイティブな balance に依存していたら、保存則が壊れる。balanceを private な bookkeeping 変数として track することで、保存則 invariant は fund 自身の会計 を検証する。外部 ETH 注入の副作用に対して immune だ。Rust に忠実な storage 変数は意図的な safety 選択でもある — EVM ネイティブの balance は contract の invariant を bypass する外部 mutator から触れられる。
Step 4: test/InsuranceFundHandler.sol を書く
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.35;
import {Test} from "forge-std/Test.sol";
import {InsuranceFund} from "../src/InsuranceFund.sol";
/// @notice Handler for InsuranceFund invariant testing.
/// Wraps the 3 fund operations, bounds inputs to productive ranges,
/// maintains 5 ghost variables that mirror the conservation-law expectations.
contract InsuranceFundHandler is Test {
InsuranceFund public fund;
address public immutable owner;
// Five ghost variables — the shadow specification of the fund's accounting.
uint256 public ghostSumDeposits;
uint256 public ghostSumWithdrawn;
uint256 public ghostSumAbsorbed;
uint256 public ghostSumUnabsorbed; // total of `remaining` returns from absorb
uint256 public ghostSumLossRequested; // total of `loss` parameters passed to absorb
constructor(InsuranceFund _fund, address _owner) {
fund = _fund;
owner = _owner;
}
/// Wraps fund.deposit(). Bounds input to a reasonable range so the
/// random uint256 from forge-invariant doesn't blow past uint96.
/// Updates the deposit ghost in lockstep.
function wrappedDeposit(uint256 amount) public {
amount = bound(amount, 1, type(uint96).max);
fund.deposit(amount);
ghostSumDeposits += amount;
}
/// Wraps fund.withdraw(). Only callable when there's balance to withdraw.
/// Uses vm.prank to simulate owner authorization (the handler is not the
/// owner; the owner is a separate constructor-set address).
function wrappedWithdraw(uint256 amount) public {
uint256 currentBalance = fund.balance();
if (currentBalance == 0) return; // can't withdraw from empty fund
amount = bound(amount, 1, currentBalance);
vm.prank(owner);
fund.withdraw(amount);
ghostSumWithdrawn += amount;
}
/// Wraps fund.absorb(). Tracks both the requested loss and the actual
/// decomposition (absorbed + remaining). This is the trickiest ghost
/// update — three counters must move in lockstep.
function wrappedAbsorb(uint256 loss) public {
loss = bound(loss, 1, type(uint96).max);
ghostSumLossRequested += loss;
(uint256 absorbed, uint256 remaining) = fund.absorb(loss);
ghostSumAbsorbed += absorbed;
ghostSumUnabsorbed += remaining;
}
}
押さえる点が 5 つ。Handler 規律のパターンだ。
- Handler は
Testを継承してbound()とvm.*アクセスを得る。bound(x, min, max)は forge-std のヘルパーで、任意の uint256 を[min, max]に map する (範囲内の値はそのまま、範囲外は modulo で折り返す)。vm.prank(owner)が次の call を owner address から来たかのように見せる (レッスン 1 + レッスン 5で学んだ test 内 impersonation)。Test継承が標準 Handler パターン。入力 bounding と認可 simulation のための cheatcode アクセスを与える。 - すべての wrapped method が call と lockstep で ghost を更新する。
wrappedDepositはfund.deposit(amount)が成功した後にghostSumDepositsを増分する。Call が revert すれば increment は起きない。これが正しい挙動だ。Fund の state も変わっていないからだ。Lockstep は per-method。Revert は fund state と would-be ghost update の両方を unwind する。 wrappedWithdrawは balance がゼロのとき short-circuit する。 これがないと[1, currentBalance=0]への bound が失敗するか (min > max)、fund.withdraw(amount)がInsufficientBalanceで revert し、fail_on_revert = falseが単に revert を数えて先に進む (これは fine だが iteration を無駄にする)。Handler 内部の defensive short-circuit が無駄な iteration に勝つ。wrappedAbsorbは 3 つの ghost を更新する。ghostSumLossRequested(入力)、ghostSumAbsorbed(fund が実際に absorb したもの)、ghostSumUnabsorbed(remaining = fund がカバーできなかった超過 loss)。これがinvariant_AbsorbDecompositionを provable にする。handler が 3 量すべてを track するから、invariant がその conservation を assert できる。Ghost が多いことは code smell ではない。それが invariant を provable にする方法だ。- Owner は constructor-set で immutable だ。 Handler は owner になる のではない。各 withdraw 用に
vm.prank経由で owner を impersonate する。test も handler も owner である べきではない。それが access-control バグを mask してしまうからだ。認可の simulation であって、認可の replacement ではない。
Step 5: test/InsuranceFund.invariant.t.sol を書く
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.35;
import {Test} from "forge-std/Test.sol";
import {InsuranceFund} from "../src/InsuranceFund.sol";
import {InsuranceFundHandler} from "./InsuranceFundHandler.sol";
/// @notice 4 conservation invariants for the Solidity InsuranceFund.
/// Invariant 4 is the sequence-level form of the Rust
/// `withdraw_amount_plus_unfilled_equals_shortfall` proptest.
contract InsuranceFundInvariantTest is Test {
InsuranceFund public fund;
InsuranceFundHandler public handler;
address constant OWNER = address(0xBABE);
function setUp() public {
fund = new InsuranceFund(OWNER);
handler = new InsuranceFundHandler(fund, OWNER);
targetContract(address(handler));
}
/// Invariant 1: Conservation of capital.
/// fund.balance() == ghostSumDeposits - ghostSumWithdrawn - ghostSumAbsorbed
/// This is the load-bearing conservation law — every wei that entered as a
/// deposit either still sits in the fund, or left via withdraw, or was
/// consumed by absorb. No wei appears or disappears unaccounted-for.
function invariant_Conservation() public view {
assertEq(
fund.balance(),
handler.ghostSumDeposits() - handler.ghostSumWithdrawn() - handler.ghostSumAbsorbed()
);
}
/// Invariant 2: Deposit-side accounting consistency.
/// The fund's view of total deposits matches the handler's accounting.
/// Catches: double-counting in deposit, ghost update missing or wrong scale.
function invariant_DepositAccounting() public view {
assertEq(fund.totalDeposited(), handler.ghostSumDeposits());
}
/// Invariant 3: Withdraw-side accounting consistency.
/// The fund's view of total withdrawals matches the handler's accounting.
/// Catches: similar bugs on the withdraw path.
function invariant_WithdrawAccounting() public view {
assertEq(fund.totalWithdrawn(), handler.ghostSumWithdrawn());
}
/// Invariant 4: Absorb-decomposition equivalence.
/// For every absorb(loss): absorbed + remaining == loss.
/// Aggregated: ghostSumAbsorbed + ghostSumUnabsorbed == ghostSumLossRequested.
/// Catches: the fund's absorb math being wrong (e.g., remaining = loss - balance
/// instead of loss - absorbed), or the handler forgetting to track unabsorbed.
function invariant_AbsorbDecomposition() public view {
assertEq(
handler.ghostSumAbsorbed() + handler.ghostSumUnabsorbed(),
handler.ghostSumLossRequested()
);
}
}
押さえる点が 4 つ。load-bearing な invariant パターンだ。
-
各
invariant_*は 1 行のassertEq。 Control flow なし、branching なし、exception handling なし。ただの算術等価性だ。これが Solidity で concrete になった保存則形状だ。保存則は等価性。等価性は one-liner。 -
Invariant は fund state と ghost state の 両方 を参照する。 Invariant 1 は
fund.balance()(実際の contract observable) と 3 つの ghost を読む。2 つの surface の間の不一致こそがバグを catch する。Ghost は spec。Contract は implementation。Invariant は両者の間の等価性。 -
Invariant 2 と 3 は accounting の cross-check だ。 Fund は独自の
totalDepositedとtotalWithdrawnフィールドを持つ (Solidity 版での追加)。Invariant 2 と 3 は handler と fund がこれらの値で agree していることを検証する。Fund のdepositが誤ってtotalDepositedを double-increment したら、invariant 2 が catch する。Contract 自身の bookkeeping を handler の bookkeeping に対して cross-check することが、contract-internal なバグを catch する。 -
「多層的インバリアント(Multi-Layered Invariants)」の設計パターン
このテスト設計では、異なる階層の性質を持つインバリアントを意図的に組み合わせており、これを**「多層的インバリアント」**と呼ぶ。デバッグの効率化と偽陽性の排除において強力な力を発揮する:
-
システムレベルの保存則(System-Level Conservation Laws - Invariant 1): コントラクト自体の残高(リアルな状態)と、外部とのすべての入出力の総和(ゴースト状態)を突き合わせる最もマクロな不変条件。システム全体の経済的合理性(「資金がどこからも現れず、どこにも消えない」こと)を検証する。
-
コンポーネントレベルの内部インバリアント(Component-Level Invariants - Invariant 4): コントラクトの状態は参照せず、ハンドラー(ゴースト変数)の内部状態のみを相互検証するミクロな不変条件。今回の例では、
ghostSumAbsorbed + ghostSumUnabsorbed == ghostSumLossRequested(吸い込まれた損失とカバーされなかった損失の和は、発生した総損失と等しい)がこれに相当する。 -
「監視者を監視する(Who watches the watchers?)」防衛ライン: インバリアントテスト自体のバグ(ゴースト変数の更新ロジック自体の誤り)は、テストの有効性を無効化する最大の要因だ。Invariant 4 は純粋にハンドラー側の記録整合性をアサートしているため、「テストロジックが仕様通りに機能しているか」を自己検証する。
-
失敗箇所の絞り込み: テストが失敗した際:
- Invariant 4 が失敗:ゴーストと
absorbの戻り値しか使わないので、まずハンドラーの absorb 記録(またはabsorbの戻り値)を疑う。 - Invariant 1 のみ失敗し、Invariant 4 はパス:分解は整合しているので、コントラクトの
balanceの動き(または deposit / withdraw のゴースト)を疑う。 - 1 つのバグで両方失敗することもある:Step 7 ではハンドラーのゴースト更新を 1 つ消すだけで Invariant 1 と 4 の両方が失敗する。
これは見る場所を絞るためのもので、counterexample を読む代わりにはならない。
- Invariant 4 が失敗:ゴーストと
-
Step 6: Invariant を走らせる
cd examples/foundry-capstone
forge test --match-contract InsuranceFundInvariantTest -vvv
期待される出力:
Ran 4 tests for test/InsuranceFund.invariant.t.sol:InsuranceFundInvariantTest
[PASS] invariant_AbsorbDecomposition() (runs: 256, calls: 12800, reverts: 0)
[PASS] invariant_Conservation() (runs: 256, calls: 12800, reverts: 0)
[PASS] invariant_DepositAccounting() (runs: 256, calls: 12800, reverts: 0)
[PASS] invariant_WithdrawAccounting() (runs: 256, calls: 12800, reverts: 0)
Suite result: ok. 4 passed; 0 failed; 0 skipped; finished in ...
(Foundry 1.7.1。-vvv では各結果の後に selector ごとの calls / reverts / discards の表も出る。)
4 つの invariant、12,800 ランダム call 系列、すべて緑。 各 invariant は 12,800 ランダム call のそれぞれの後で check された。合計 51,200 個の個別 assertEq 評価だ。そしてすべてが成立した。
Heavy な proof には CI profile (2,000 runs × depth 100 = invariant あたり 200,000 calls) に bump する:
FOUNDRY_PROFILE=ci forge test --match-contract InsuranceFundInvariantTest -vvv
各 invariant に (runs: 2000, calls: 200000, reverts: 0) が表示され、検証に使ったマシンで約 13 秒だった。4 × 200,000 = 800,000 回の invariant check がすべて緑。
Step 7: 意図的な break デモ + Rust proptest との side-by-side
Invariant 1 を subtle なバグで壊す。wrappedAbsorb で ghostSumAbsorbed の更新を 忘れる:
function wrappedAbsorb(uint256 loss) public {
loss = bound(loss, 1, type(uint96).max);
ghostSumLossRequested += loss;
(uint256 absorbed, uint256 remaining) = fund.absorb(loss);
// ghostSumAbsorbed += absorbed; // ← 意図的にコメントアウト
ghostSumUnabsorbed += remaining;
}
再実行:
[FAIL: assertion failed: 79228162514264337593543950336 != 79228162514264337593543998142]
[Sequence] (original: 8, shrunk: 2)
sender=0x...171f addr=[test/InsuranceFundHandler.sol:InsuranceFundHandler]0x2e23... calldata=wrappedDeposit(uint256) args=[74161 [7.416e4]]
sender=0x...14C4 addr=[test/InsuranceFundHandler.sol:InsuranceFundHandler]0x2e23... calldata=wrappedAbsorb(uint256) args=[47806 [4.78e4]]
invariant_AbsorbDecomposition() (runs: 0, calls: 0, reverts: 0)
[FAIL: assertion failed: 79228162514264337593543976689 != 79228162514264337593544024495]
[Sequence] (original: 8, shrunk: 2)
(same two calls)
invariant_Conservation() (runs: 0, calls: 0, reverts: 0)
[PASS] invariant_DepositAccounting() (runs: 256, calls: 12800, reverts: 0)
[PASS] invariant_WithdrawAccounting() (runs: 256, calls: 12800, reverts: 0)
Suite result: FAILED. 2 passed; 2 failed; 0 skipped; ...
(Foundry 1.7.1 の実出力、address は短縮。fuzzer はランダム seed なので引数や数値は毎回異なる。absorbed が未使用になったという compiler warning も出る。)
Shrink された counterexample を読む:
wrappedDeposit(74161)— 範囲内の値はboundがそのまま返すので fund.balance = 74161、ghostSumDeposits = 74161wrappedAbsorb(47806)— fund が 47806 を absorb → fund.balance = 26355; ghostSumAbsorbed は 更新されない (バグ); ghostSumUnabsorbed = 0; ghostSumLossRequested = 47806
ここで invariant 1 は fund.balance() (26355) == ghostSumDeposits (74161) - ghostSumWithdrawn (0) - ghostSumAbsorbed (0、バグ) → FAIL、invariant 4 は ghostSumAbsorbed (0) + ghostSumUnabsorbed (0) == ghostSumLossRequested (47806) → FAIL。
Shrinker は元の 8-call の失敗系列をこの 2 call まで reduce した (assertion failed 行の値は元の系列のもので、そこにはずっと大きな量が含まれていた)。forge test を再実行すると保存された 2-call 系列が replay され、上の数値どおり invariant 1 は assertion failed: 26355 != 74161、invariant 4 は assertion failed: 0 != 47806 を表示する。Invariant 1 と 4 の両方がバグを catch した。absorb に関係しない 2 と 3 は pass のまま。
コメントアウトした行を restore する。再実行する。4 つすべて緑に戻る。
今度は Rust 側と比較する。openhl の commit 260883b (Stage 10b) で crates/liquidation/src/insurance.rs を開く。mod tests の最後に 4 つの proptest! property がある。自分の InsuranceFund.invariant.t.sol と並べる:
┌────────────────────────────────────────┬──────────────────────────────────────────┐
│ openhl insurance.rs (Rust, proptest!) │ Lesson 6 capstone (invariant tests) │
├────────────────────────────────────────┼──────────────────────────────────────────┤
│ withdraw_amount_plus_unfilled_ │ invariant_AbsorbDecomposition │
│ equals_shortfall │ (summed over a call sequence) │
│ withdraw_amount_matches_balance_delta │ invariant_Conservation (balance moves │
│ │ by exactly what went in and out) │
│ deposit_is_additive │ invariant_DepositAccounting (closest) │
│ balance_never_negative │ (guaranteed by uint256 + checked math) │
│ (no counterpart) │ invariant_WithdrawAccounting │
├────────────────────────────────────────┼──────────────────────────────────────────┤
│ ops: Vec<(bool, i64)> — each step is │ Handler methods: │
│ deposit or withdraw_shortfall │ wrappedDeposit / wrappedWithdraw / │
│ │ wrappedAbsorb │
└────────────────────────────────────────┴──────────────────────────────────────────┘
名前は違い、1 対 1 の組でもない: 2 つの property はそのまま引き継がれ、1 つは型の保証になり、Solidity 側は追加した bookkeeping の check を足している。中心にある保存則 — 入ったもの = まだあるもの + 出ていったもの — は同じだ。言語境界を越えて残るのは規律のこの部分だ。
よくある失敗パターン
StdUtils bound(uint256,uint256,uint256): Max is less than min.—bound(amount, min, max)でmin > maxになっている。通常bound(x, 1, 0)を渡したことを意味する。boundを呼ぶ前に short-circuit 条件を check する。- すべての invariant が pass するが
forge testがまだ失敗する — 同じファイルに invariant ではない test があって失敗している。--match-test invariantでスコープする。 failed to set up invariant testing environment: No contracts to fuzz.— 例えばtargetContract(address(handler))がhandlerのインスタンス化前に call され、address(0)を target にした。targetContractを呼ぶ前に必ず Handler をnewする。reverts: 12800— すべての Handler call が revert している。bound(...)の range が間違っているか、wrapper が invalid な入力を素通りさせているかのどちらかだ。boundを tight にするか、wrappedWithdrawのような early return を加える。- Invariant が
--match-contractで即座に失敗する — Invariant が間違っている。Contract ではない。Operation を手で呼ぶ単一のfunction test_X()を書き、invariant を信じる前に手で算術を検証する。
設計の振り返り
Capstone の設計に焼き込んだ load-bearing な決定が 3 つ。
-
核は翻訳し、追加にはラベルを付ける。 定理を運ぶ部分 —
withdraw_shortfall→absorb、amount + unfilled == shortfall→absorbed + remaining == loss— はそのまま翻訳する。EVM 版で加えたもの (total、owner、withdraw、no-op の代わりの revert) は追加として明記する。どこが翻訳でどこが新規かを明示することが、2 つの実装を正直に比較できる条件だ。言語横断の port は、違いが書き出されて初めて検証可能になる。 -
4 つではなく 5 つの ghost。 Handler は
ghostSumLossRequestedをghostSumAbsorbed + ghostSumUnabsorbedとは別に track する。これで invariant 4 が両者の等価性を証明できる。よりコンパクトな設計なら invariant に直接関連する 4 ghost だけを track するだろう。5 番目の ghost は invariant 4 を 意味ある assertion にするために存在する (tautology ではなく)。5 番目の ghost は invariant 4 の spec だ。 -
Handler 内部に
vm.assumeなし。 入力 bounding はすべてbound(x, min, max)で行う。すべてのランダム parameter が valid range に map される、filter out されるのではない。これで invariant テストの iteration count が productive に保たれ (rejection で潰れる iteration がない)、スケールでの test も fast になる。vm.assumeではなくbound。これが Handler パターンの規律だ。
答え合わせ
レッスン6の後、ディレクトリは exact にこの形になる:
examples/foundry-capstone/
├── foundry.toml ← invariant config + pragma pin
├── src/
│ └── InsuranceFund.sol ← 51 行、3 ops + 5 fields
├── test/
│ ├── InsuranceFundHandler.sol ← 57 行、3 wrappers + 5 ghosts
│ └── InsuranceFund.invariant.t.sol ← 58 行、4 invariants
└── lib/forge-std/ ← standard な submodule
forge test --match-contract InsuranceFundInvariantTest が 4 つの [PASS] 行を (runs: 256, calls: 12800, reverts: 0) で表示する。
FOUNDRY_PROFILE=ci forge test --match-contract InsuranceFundInvariantTest が同じことを invariant あたり runs: 2000, calls: 200000 で行う。
openhl の crates/liquidation/src/insurance.rs (commit 260883b) 末尾の 4 つの proptest! property と、Step 7 の対応表を使って比較する。
よくある質問
Q1: なぜ Rust に留まらず Solidity に port するのか?
違う deployment surface だ。Rust + openhl は実行環境をコントロールできる chain (自分の L1/L2) 向け。Solidity + invariant テストは EVM 向けで、固定された bytecode target にコンパイルしなければならない。Capstone が存在するのは、EVM chain 上の production-deployable な insurance fund (Aave の safety module、Compound の reserve など) が Solidity だからだ。そして同じ保存則規律が適用される。Port は規律が platform-agnostic であることを証明する。Deployment target が言語を決める。
Q2: 自分の port が 正しい と知るには? 自分の設計でしかないと感じるが?
Cross-check は 2 つだ。(a) 両側で同じルールを壊す (例: Solidity の remaining と Rust の unfilled を同じ間違いで計算する) と、対応する property が両方で失敗することを確認する。(b) マッピング表が比較対照すべき契約だ。表に意図的な追加・変更として載っていない semantics の違いは porting バグだ。機械的な対応は検証可能だ。「感じが正しい」は検証可能ではない。
Q3: invariant をもっと追加できる?
Yes、できるしすべきだ。ここの 4 つは出発点だ。Real な insurance fund はもっと加える。access-control invariant (owner だけが withdraw できる)、upper-bound invariant (total absorbed が total deposited - balance を決して超えない)、rate-limit invariant (Y ブロックあたり X% より多くは withdraw されない)。どれも同じ形に従う。observable を選び、ghost state に対する等価性を書き、invariant test に追加する。Invariant は compound する。Test ファイルは safety property と線形に成長する。
Q4: examples/foundry-capstone/ ディレクトリは何を ship するのか — commit されたコード? それともテンプレート?
Commit された動作するコードだ。ディレクトリはコースの答え合わせ。レッスン 0–レッスン5を完了する新しい読者は、自分の レッスン 6 作業をこの exact なソースに対して比較できる。Capstone は reference implementation だ。Walk-through に従って自分のバージョンを build し、答え合わせはそこに検証用として置かれている (既に快適なら飛ばすためにも)。Commit された reference implementation こそが、instructor review なしでコースが複数読者にスケールする仕組みだ。
Q5: なぜ examples/foundry-capstone/ がレッスン Web サイトの Next.js build の一部ではないのか?
独自の foundry.toml と lib/forge-std を持つ sub-project だからだ。Next.js build に含めるには、Vercel の deployment にそれを pull する (build time の無駄) か、forge-std を vendor する (disk + git churn の無駄) かのどちらかが必要になる。配置はこうだ。レッスンは Web にあり、executable な artifact は companion リポジトリの examples/foundry-capstone/ sub-project にある。読者はそれを走らせるために companion リポジトリを clone する。カリキュラム用は Web site、証明用は sub-project。
Q6: 同じ Handler パターンが、deploy された contract に対して invariant を証明できる (forking + impersonation)?
Yes、できる。それが レッスン 5 + レッスン 6 シンセシスだ。--fork-url <mainnet> を使い、targetContract を deploy された Aave reserve に向ける InvariantTest を書ける。Handler が vm.prank 経由で reserve の role-holder を impersonate し、real な method を呼ぶ。Invariant は、自分のローカル port に対してではなく、実際に deploy されたシステムに対して保存則を証明する。Capstone は contained な例だ。同じパターンが「real production contract に対して invariant を証明する」までスケールする。レッスン 5 forking 作業がセットアップしていたのはこれだ。
Q7: Fund がアップグレードされたとき (proxy パターン)、invariant testing はどうなる?
Invariant は public ABI と storage layout を保つアップグレードを survive する。アップグレードがそのどちらかを変えるなら、invariant は match するように更新されなければならない。パターンはこうだ。invariant test を contract source と一緒に store する。アップグレードのたびに新実装に対して full invariant suite を再走させる。CI 統合が、保存則を再証明せずにアップグレードが ship しないことを保証する。Invariant は contract の specification の一部だ。アップグレードはそれらを preserve するか、明示的に version しなければならない。
コース総括
これがこのコースの最終レッスンだ。6 レッスンを経て、「Foundry pragma とは何か」(レッスン1) から「Rust-to-Solidity port に対して 4 つの保存則 invariant を機械的に 60 分で証明した」まで歩いた。これが本コースの thesis だ。規律は言語を超えて転写する。下層の数学は、どのコンパイラが走るかを気にしないからだ。
次にどこへ行くか。
- Capstone をもっと多くの invariant で走らせる。
InsuranceFund.invariant.t.solに access-control、rate-limit、upper-bound invariant を加える。各々 ~3 行の Solidity だ。 - openhl からもう 1 つコンポーネントを port する。 openhl-liquidation から
LiquidationScanner(crates/liquidation/src/scanner.rs) か、compute.rsの pure な margin 計算を選ぶ。同じパターンだ。state + operation + invariant を特定し、Solidity を書き、invariant テストで証明する。 - 規律を自分の production code に適用する。 自分が書いた保存則形状の property (token balance、累積 fee、vesting schedule) を持つ contract は候補だ。Handler パターン + 1 行
assertEqinvariant が何にでもスケールする。 - openhl の liquidation crate(
crates/liquidation/)をもう一度読む。 1 つコンポーネントを port した今、パターンは違って読める。proptest!macro がinvariant_*のように見える。Rust ではあるが、骨格は同じだ。 - openhl ADL コースの capstone を読む — 本レッスンの Rust 側 sibling capstone だ。 あちらの 5 つの invariant proptest は、同じ保存則の規律を cascade 全体(scanner → insurance fund → ADL)に通す。ここが invariant テストを使うところで
proptest!(Rust) を使い、最後に Stage 10 quartet のレトロスペクティブで締める。2 つの capstone を並べて読むと、同じ規律が 2 言語で見える。
Capstone を走らせ終わったその瞬間、画面には 4 行の緑が並んでいる。書いたのは Solidity、走らせたのは invariant テスト、証明したのは Rust で先に証明した amount + unfilled == shortfall を中心とする保存則。コードは 2 つ、中心の定理は 1 つ。これがコース全体が指していた一点だ。
Foundry は道具だ。規律こそがプロダクトだ。
合格基準
- 4 invariants(Conservation / DepositAccounting / WithdrawAccounting / AbsorbDecomposition)を即答できる。
InsuranceFund.solのuint256state 4 つ +owner+ 3 関数 (deposit/withdraw/absorb) の API と、Rust 版 (balance: i64+deposit/withdraw_shortfall) との違いを即答できる。- Rust の saturating arithmetic と Solidity 0.8 の checked arithmetic の違いを即答できる。
InsuranceFundHandler+ ghost 変数 +InsuranceFundInvariantTestの 3 ピース構成を即答できる。[profile.ci.invariant] runs = 2000, depth = 100の意味(invariant あたり 200,000 call)を即答できる。- companion リポジトリの
examples/foundry-capstone/が答え合わせであることを即答できる。 - liquidation コースの
withdraw_shortfallレッスンの proptest(Rust)のamount + unfilled == shortfallが本 Capstone の invariant 4 にどう対応するかを即答できる。
まとめ(3行)
- Capstone = openhl-liquidation Stage 10b
InsuranceFundを Rust → Solidity port (withdraw_shortfall→absorb、EVM 側で total / owner /withdrawを追加)、4 保存則 invariant を invariant テストで検証 (default で invariant あたり 12,800 call、CI profile で 200,000)、規律の transfer の終点。 - Test harness 3 ピース =
InsuranceFund.sol+InsuranceFundHandler(5 つの ghost 変数) +InsuranceFundInvariantTest(targetContract+ 4invariant_*)、Rust の saturating add の代わりに Solidity 0.8 の checked arithmetic。 - 4 invariant pass、invariant 4 はliquidation コースの
withdraw_shortfallレッスンのamount + unfilled == shortfallの系列版、companion リポジトリのexamples/foundry-capstone/が答え合わせ、規律の transfer 完了。