{"eip":5450,"title":"EOF - Stack Validation","description":"Deploy-time validation of stack usage for EOF functions.","authors":["Andrei Maiboroda (@gumb0)","Paweł Bylica (@chfast)","Alex Beregszaszi (@axic)","Danno Ferrin (@shemnon)"],"status":"Stagnant","type":"Standards Track","category":"Core","created":"2022-08-12","requires":[3540,3670,4200,4750],"discussionsTo":"https://ethereum-magicians.org/t/eip-5450-eof-stack-validation/10410","repo":"EIPs","label":"EIP-5450","officialUrl":"https://eips.ethereum.org/EIPS/eip-5450","sourceUrl":"https://github.com/ethereum/EIPs/blob/master/EIPS/eip-5450.md","url":"https://eips.huatuo.xyz/eip-5450/","tldr":{"en":"Part of EOF: a deploy-time, single-pass check that proves an EOF function can never underflow the stack and can only overflow at CALLF/JUMPF, so the EVM can skip most per-instruction stack checks.","ja":"EOF の一部: デプロイ時に 1 パスで行う検査で、EOF の関数がスタックアンダーフローを起こさず、CALLF/JUMPF でしかオーバーフローしないことを証明する。これにより EVM は命令ごとのスタックチェックの大半を省略できる。","ko":"EOF의 일부: 배포 시점에 한 번의 패스로 수행하는 검사로, EOF 함수가 스택 언더플로를 일으킬 수 없고 CALLF/JUMPF에서만 오버플로가 가능함을 증명한다. 그래서 EVM은 명령어별 스택 검사 대부분을 생략할 수 있다.","zh":"EOF 的一部分：在部署时进行的单次遍历检查，证明 EOF 函数绝不会发生栈下溢，且只可能在 CALLF/JUMPF 处上溢，因此 EVM 可以跳过大部分逐指令的栈检查。"},"tags":["eof","evm","validation","stack","core"],"explainers":{"en":{"lang":"en","tldr":"Part of EOF: a deploy-time, single-pass check that proves an EOF function can never underflow the stack and can only overflow at CALLF/JUMPF, so the EVM can skip most per-instruction stack checks.","tags":["eof","evm","validation","stack","core"],"related":[3540,3670,4200,4750,7692],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-5450/","markdown":"## What problem does it solve?\n\nToday's EVM checks for stack underflow and overflow on **every instruction** it executes. That costs time, and it means bad bytecode is only caught when it runs.\n\nThe EVM Object Format (EOF, [EIP-3540](/eip-3540/)) validates code when it is deployed instead. EIP-5450 adds stack validation to that process. Every EOF code section is analyzed once, before deployment, and rejected unless the analysis proves stack errors are impossible. After that:\n\n- run-time **underflow** checks can be removed entirely,\n- **overflow** is checked only at `CALLF`/`JUMPF`, once for the whole called function,\n- every path ends in a terminating instruction, and unreachable code (sometimes used to hide data in code) is rejected,\n- AOT/JIT compilation of EVM code becomes easier.\n\n## How it works\n\nThe rules build on [EIP-3670](/eip-3670/) (opcode validation), [EIP-4200](/eip-4200/) (static relative jumps `RJUMP`/`RJUMPI`/`RJUMPV`) and [EIP-4750](/eip-4750/) (functions with a type section declaring `inputs`, `outputs` and `max_stack_increase`).\n\nEach code section is scanned **once, in order**. For each instruction the validator keeps a range `[stack_height_min, stack_height_max]` of possible stack heights:\n\n1. The first instruction starts at `inputs`. An instruction that has no recorded range was never reached by fall-through or a forward jump, so it is unreachable and the code is rejected. Compilers must order basic blocks so that no block is reached *only* by a backward jump.\n2. The lower bound must cover what the instruction pops. `RETF` needs exactly `outputs` items, and `CALLF` needs at least the callee's `inputs`.\n3. For `CALLF`/`JUMPF`, the upper bound plus the callee's `max_stack_increase` must not exceed 1024.\n4. Successors reached by **forward jumps** widen the target's range. A **backward jump** must reach its target at exactly the recorded height, so loops cannot grow or shrink the stack without limit.\n5. At the end, the highest height seen minus `inputs` must equal the declared `max_stack_increase`.\n\nThe pass is linear in code size. Other terminating instructions (`STOP`, `RETURN`, `REVERT`, …) may leave extra items on the stack. That allows the common compiler pattern of several `assert`s jumping into one shared revert block from different stack heights.\n\n## Sample code\n\nA simplified version of the validator loop:\n\n```python\ndef validate_stack(code, types, sec):\n    lo = {0: types[sec].inputs}; hi = {0: types[sec].inputs}\n    for pc, ins in instructions(code):\n        if pc not in lo: raise Invalid(\"unreachable\")\n        need, out = stack_effect(ins, types)          # pops, pushes (CALLF uses callee type)\n        if lo[pc] \u003c need: raise Invalid(\"underflow\")\n        if ins.op in (\"CALLF\", \"JUMPF\") and hi[pc] \u003e 1024 - types[ins.target].max_stack_increase:\n            raise Invalid(\"overflow\")\n        nlo, nhi = lo[pc] - need + out, hi[pc] - need + out\n        for succ in successors(pc, ins):\n            if succ \u003c pc:                              # backward jump\n                if (lo[succ], hi[succ]) != (nlo, nhi): raise Invalid(\"loop height mismatch\")\n            else:\n                lo[succ] = min(lo.get(succ, nlo), nlo); hi[succ] = max(hi.get(succ, nhi), nhi)\n    if max(hi.values()) - types[sec].inputs != types[sec].max_stack_increase:\n        raise Invalid(\"max_stack_increase mismatch\")\n```\n\n## Things to know\n\n- **Status: Stagnant**, together with the rest of EOF ([EIP-7692](/eip-7692/) is the EOFv1 meta EIP). EOF was considered for several network upgrades but has not shipped on mainnet.\n- The rules apply only to EOF-formatted contracts. Legacy bytecode is unaffected.\n- An earlier, stricter design required one exact stack height per instruction. Compiler teams objected, so the current version uses min/max ranges for forward jumps.\n- `JUMPF` and `RETURNCODE` are defined in separate EOF EIPs.\n"},"ja":{"lang":"ja","tldr":"EOF の一部: デプロイ時に 1 パスで行う検査で、EOF の関数がスタックアンダーフローを起こさず、CALLF/JUMPF でしかオーバーフローしないことを証明する。これにより EVM は命令ごとのスタックチェックの大半を省略できる。","tags":["eof","evm","validation","stack","core"],"related":[3540,3670,4200,4750,7692],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-5450/","markdown":"## 何を解決するのか\n\n今日の EVM は、実行する**すべての命令**でスタックのアンダーフローとオーバーフローをチェックします。これには時間がかかり、不正なバイトコードも実行されたときにしか検出されません。\n\nEVM Object Format（EOF、[EIP-3540](/eip-3540/)）は代わりに、デプロイ時にコードを検証します。EIP-5450 はそのプロセスにスタック検証を加えます。すべての EOF コードセクションはデプロイ前に一度解析され、スタックエラーが起こり得ないことが証明されなければ拒否されます。その結果、次のようになります。\n\n- 実行時の**アンダーフロー**チェックを完全に削除できる、\n- **オーバーフロー**は `CALLF`/`JUMPF` でのみ、呼び出される関数全体に対して 1 回だけチェックされる、\n- すべてのパスが終了命令で終わり、到達不能なコード（コード内にデータを隠すために使われることがある）は拒否される、\n- EVM コードの AOT/JIT コンパイルが容易になる。\n\n## 仕組み\n\nルールは、[EIP-3670](/eip-3670/)（opcode の検証）、[EIP-4200](/eip-4200/)（静的な相対ジャンプ `RJUMP`/`RJUMPI`/`RJUMPV`）、[EIP-4750](/eip-4750/)（`inputs`、`outputs`、`max_stack_increase` を宣言する型セクションを持つ関数）の上に成り立っています。\n\n各コードセクションは**順番に 1 回だけ**走査されます。命令ごとに、バリデーターは取り得るスタック高さの範囲 `[stack_height_min, stack_height_max]` を保持します。\n\n1. 最初の命令は `inputs` から始まります。範囲が記録されていない命令は、フォールスルーや前方ジャンプでは一度も到達されていないため、到達不能とみなされ、コードは拒否されます。コンパイラは、後方ジャンプ*だけ*で到達されるブロックがないように、基本ブロックを並べなければなりません。\n2. 下限は、その命令がポップする数を満たしていなければなりません。`RETF` はちょうど `outputs` 個の要素を必要とし、`CALLF` は少なくとも呼び出し先の `inputs` 個を必要とします。\n3. `CALLF`/`JUMPF` については、上限に呼び出し先の `max_stack_increase` を加えた値が 1024 を超えてはなりません。\n4. **前方ジャンプ**で到達する後続命令は、ターゲットの範囲を広げます。**後方ジャンプ**は、記録された高さちょうどでターゲットに到達しなければならないため、ループがスタックを際限なく増減させることはできません。\n5. 最後に、観測された最大の高さから `inputs` を引いた値が、宣言された `max_stack_increase` と等しくなければなりません。\n\nこのパスはコードサイズに対して線形です。その他の終了命令（`STOP`、`RETURN`、`REVERT` など）は、スタックに余分な要素を残してもかまいません。これにより、複数の `assert` が異なるスタック高さから 1 つの共通の revert ブロックへジャンプするという、コンパイラのよくあるパターンが可能になります。\n\n## サンプルコード\n\nバリデーターのループの簡略版:\n\n```python\ndef validate_stack(code, types, sec):\n    lo = {0: types[sec].inputs}; hi = {0: types[sec].inputs}\n    for pc, ins in instructions(code):\n        if pc not in lo: raise Invalid(\"unreachable\")\n        need, out = stack_effect(ins, types)          # pops, pushes (CALLF uses callee type)\n        if lo[pc] \u003c need: raise Invalid(\"underflow\")\n        if ins.op in (\"CALLF\", \"JUMPF\") and hi[pc] \u003e 1024 - types[ins.target].max_stack_increase:\n            raise Invalid(\"overflow\")\n        nlo, nhi = lo[pc] - need + out, hi[pc] - need + out\n        for succ in successors(pc, ins):\n            if succ \u003c pc:                              # backward jump\n                if (lo[succ], hi[succ]) != (nlo, nhi): raise Invalid(\"loop height mismatch\")\n            else:\n                lo[succ] = min(lo.get(succ, nlo), nlo); hi[succ] = max(hi.get(succ, nhi), nhi)\n    if max(hi.values()) - types[sec].inputs != types[sec].max_stack_increase:\n        raise Invalid(\"max_stack_increase mismatch\")\n```\n\n## 知っておくべきこと\n\n- **ステータス: Stagnant**。EOF の他の部分と同様です（[EIP-7692](/eip-7692/) は EOFv1 のメタ EIP）。EOF は複数のネットワークアップグレードで検討されましたが、メインネットには出荷されていません。\n- ルールは EOF 形式のコントラクトにのみ適用されます。レガシーのバイトコードには影響しません。\n- 以前の、より厳格な設計では、命令ごとにスタック高さを 1 つに厳密に固定する必要がありました。コンパイラチームが反対したため、現在のバージョンでは前方ジャンプに min/max の範囲を使います。\n- `JUMPF` と `RETURNCODE` は、別の EOF の EIP で定義されています。\n"},"ko":{"lang":"ko","tldr":"EOF의 일부: 배포 시점에 한 번의 패스로 수행하는 검사로, EOF 함수가 스택 언더플로를 일으킬 수 없고 CALLF/JUMPF에서만 오버플로가 가능함을 증명한다. 그래서 EVM은 명령어별 스택 검사 대부분을 생략할 수 있다.","tags":["eof","evm","validation","stack","core"],"related":[3540,3670,4200,4750,7692],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-5450/","markdown":"## 어떤 문제를 해결하나요?\n\n오늘날의 EVM은 실행하는 **모든 명령어**에서 스택 언더플로와 오버플로를 검사합니다. 이는 시간이 들고, 잘못된 바이트코드도 실행될 때에야 발견된다는 뜻입니다.\n\nEVM Object Format(EOF, [EIP-3540](/eip-3540/))은 대신 배포 시점에 코드를 검증합니다. EIP-5450은 이 과정에 스택 검증을 추가합니다. 모든 EOF 코드 섹션은 배포 전에 한 번 분석되며, 분석이 스택 오류가 불가능함을 증명하지 못하면 거부됩니다. 그 결과는 다음과 같습니다.\n\n- 런타임 **언더플로** 검사를 완전히 제거할 수 있고,\n- **오버플로**는 `CALLF`/`JUMPF`에서만, 호출되는 함수 전체에 대해 한 번 검사하며,\n- 모든 경로가 종료 명령어로 끝나고, 도달할 수 없는 코드(코드 안에 데이터를 숨기는 데 쓰이기도 함)는 거부되며,\n- EVM 코드의 AOT/JIT 컴파일이 쉬워집니다.\n\n## 어떻게 동작하나요?\n\n규칙은 [EIP-3670](/eip-3670/)(opcode 검증), [EIP-4200](/eip-4200/)(정적 상대 점프 `RJUMP`/`RJUMPI`/`RJUMPV`), [EIP-4750](/eip-4750/)(`inputs`, `outputs`, `max_stack_increase`를 선언하는 타입 섹션이 있는 함수)을 기반으로 합니다.\n\n각 코드 섹션은 **순서대로 한 번만** 스캔됩니다. 명령어마다 검증기는 가능한 스택 높이의 범위 `[stack_height_min, stack_height_max]`를 유지합니다.\n\n1. 첫 번째 명령어는 `inputs`에서 시작합니다. 기록된 범위가 없는 명령어는 폴스루나 전방 점프로 한 번도 도달되지 않았으므로 도달 불가능하며, 코드는 거부됩니다. 컴파일러는 후방 점프로*만* 도달되는 블록이 없도록 기본 블록을 배치해야 합니다.\n2. 하한은 그 명령어가 팝하는 수를 충족해야 합니다. `RETF`는 정확히 `outputs`개의 항목이 필요하고, `CALLF`는 최소한 피호출자의 `inputs`개가 필요합니다.\n3. `CALLF`/`JUMPF`의 경우, 상한에 피호출자의 `max_stack_increase`를 더한 값이 1024를 넘어서는 안 됩니다.\n4. **전방 점프**로 도달하는 후속 명령어는 대상의 범위를 넓힙니다. **후방 점프**는 기록된 높이에서 정확히 대상에 도달해야 하므로, 루프가 스택을 무한정 늘리거나 줄일 수 없습니다.\n5. 마지막으로, 관찰된 최대 높이에서 `inputs`를 뺀 값이 선언된 `max_stack_increase`와 같아야 합니다.\n\n이 패스는 코드 크기에 선형입니다. 다른 종료 명령어(`STOP`, `RETURN`, `REVERT` 등)는 스택에 여분의 항목을 남겨도 됩니다. 이는 여러 `assert`가 서로 다른 스택 높이에서 하나의 공유 revert 블록으로 점프하는, 컴파일러의 흔한 패턴을 가능하게 합니다.\n\n## 샘플 코드\n\n검증기 루프의 단순화된 버전:\n\n```python\ndef validate_stack(code, types, sec):\n    lo = {0: types[sec].inputs}; hi = {0: types[sec].inputs}\n    for pc, ins in instructions(code):\n        if pc not in lo: raise Invalid(\"unreachable\")\n        need, out = stack_effect(ins, types)          # pops, pushes (CALLF uses callee type)\n        if lo[pc] \u003c need: raise Invalid(\"underflow\")\n        if ins.op in (\"CALLF\", \"JUMPF\") and hi[pc] \u003e 1024 - types[ins.target].max_stack_increase:\n            raise Invalid(\"overflow\")\n        nlo, nhi = lo[pc] - need + out, hi[pc] - need + out\n        for succ in successors(pc, ins):\n            if succ \u003c pc:                              # backward jump\n                if (lo[succ], hi[succ]) != (nlo, nhi): raise Invalid(\"loop height mismatch\")\n            else:\n                lo[succ] = min(lo.get(succ, nlo), nlo); hi[succ] = max(hi.get(succ, nhi), nhi)\n    if max(hi.values()) - types[sec].inputs != types[sec].max_stack_increase:\n        raise Invalid(\"max_stack_increase mismatch\")\n```\n\n## 알아둘 점\n\n- **상태: Stagnant**. EOF의 나머지 부분과 같습니다([EIP-7692](/eip-7692/)는 EOFv1 메타 EIP). EOF는 여러 네트워크 업그레이드에서 검토되었지만 메인넷에는 출시되지 않았습니다.\n- 규칙은 EOF 형식의 컨트랙트에만 적용됩니다. 레거시 바이트코드는 영향을 받지 않습니다.\n- 이전의 더 엄격한 설계는 명령어마다 정확히 하나의 스택 높이를 요구했습니다. 컴파일러 팀이 반대했기 때문에 현재 버전은 전방 점프에 min/max 범위를 사용합니다.\n- `JUMPF`와 `RETURNCODE`는 별도의 EOF EIP에서 정의됩니다.\n"},"zh":{"lang":"zh","tldr":"EOF 的一部分：在部署时进行的单次遍历检查，证明 EOF 函数绝不会发生栈下溢，且只可能在 CALLF/JUMPF 处上溢，因此 EVM 可以跳过大部分逐指令的栈检查。","tags":["eof","evm","validation","stack","core"],"related":[3540,3670,4200,4750,7692],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-5450/","markdown":"## 它解决什么问题？\n\n今天的 EVM 在执行**每一条指令**时都会检查栈下溢和上溢。这会耗费时间，而且有问题的字节码只有在运行时才会被发现。\n\nEVM 对象格式（EOF，[EIP-3540](/eip-3540/)）转而在部署时验证代码。EIP-5450 为这个过程加入了栈验证。每个 EOF 代码段在部署前都会被分析一次，除非分析证明栈错误不可能发生，否则会被拒绝。之后：\n\n- 运行时的**下溢**检查可以完全移除，\n- **上溢**只在 `CALLF`/`JUMPF` 处检查，对整个被调用函数只检查一次，\n- 每条路径都以终止指令结束，不可达代码（有时被用来在代码中藏匿数据）会被拒绝，\n- EVM 代码的 AOT/JIT 编译变得更容易。\n\n## 它如何运作\n\n这些规则建立在 [EIP-3670](/eip-3670/)（opcode 验证）、[EIP-4200](/eip-4200/)（静态相对跳转 `RJUMP`/`RJUMPI`/`RJUMPV`）和 [EIP-4750](/eip-4750/)（带有声明 `inputs`、`outputs` 和 `max_stack_increase` 的类型段的函数）之上。\n\n每个代码段按顺序**只扫描一次**。对每条指令，验证器维护一个可能的栈高度范围 `[stack_height_min, stack_height_max]`：\n\n1. 第一条指令从 `inputs` 开始。没有记录范围的指令从未被顺序执行或前向跳转到达，因此不可达，代码会被拒绝。编译器必须安排基本块的顺序，使得没有任何块*仅*通过后向跳转到达。\n2. 下界必须满足该指令要弹出的数量。`RETF` 需要恰好 `outputs` 个元素，`CALLF` 至少需要被调用者的 `inputs` 个。\n3. 对于 `CALLF`/`JUMPF`，上界加上被调用者的 `max_stack_increase` 不得超过 1024。\n4. 通过**前向跳转**到达的后继会扩大目标的范围。**后向跳转**必须以恰好记录的高度到达目标，因此循环不能无限制地增加或减少栈。\n5. 最后，所见的最大高度减去 `inputs`，必须等于声明的 `max_stack_increase`。\n\n这一遍扫描与代码大小成线性关系。其他终止指令（`STOP`、`RETURN`、`REVERT` 等）可以在栈上留下多余元素。这允许编译器常见的模式：多个 `assert` 从不同的栈高度跳转到同一个共享的 revert 块。\n\n## 示例代码\n\n验证器循环的简化版本：\n\n```python\ndef validate_stack(code, types, sec):\n    lo = {0: types[sec].inputs}; hi = {0: types[sec].inputs}\n    for pc, ins in instructions(code):\n        if pc not in lo: raise Invalid(\"unreachable\")\n        need, out = stack_effect(ins, types)          # pops, pushes (CALLF uses callee type)\n        if lo[pc] \u003c need: raise Invalid(\"underflow\")\n        if ins.op in (\"CALLF\", \"JUMPF\") and hi[pc] \u003e 1024 - types[ins.target].max_stack_increase:\n            raise Invalid(\"overflow\")\n        nlo, nhi = lo[pc] - need + out, hi[pc] - need + out\n        for succ in successors(pc, ins):\n            if succ \u003c pc:                              # backward jump\n                if (lo[succ], hi[succ]) != (nlo, nhi): raise Invalid(\"loop height mismatch\")\n            else:\n                lo[succ] = min(lo.get(succ, nlo), nlo); hi[succ] = max(hi.get(succ, nhi), nhi)\n    if max(hi.values()) - types[sec].inputs != types[sec].max_stack_increase:\n        raise Invalid(\"max_stack_increase mismatch\")\n```\n\n## 需要注意\n\n- **状态：Stagnant**，与 EOF 的其余部分一样（[EIP-7692](/eip-7692/) 是 EOFv1 的元 EIP）。EOF 曾被考虑纳入多次网络升级，但尚未在主网上线。\n- 这些规则只适用于 EOF 格式的合约。传统字节码不受影响。\n- 早期更严格的设计要求每条指令对应一个确切的栈高度。编译器团队表示反对，因此当前版本对前向跳转使用 min/max 范围。\n- `JUMPF` 和 `RETURNCODE` 在单独的 EOF EIP 中定义。\n"}},"requiredBy":[663,4750,6206,7692]}
