{"eip":2926,"title":"Chunk-Based Code Merkleization","description":"Introduce code-chunking in an MPT context.","authors":["Sina Mahmoodi (@s1na)","Alex Beregszaszi (@axic)","Guillaume Ballet (@gballet)","Jochem Brouwer (@jochem-brouwer)","Ignacio Hagopian (@jsign)"],"status":"Draft","type":"Standards Track","category":"Core","created":"2020-08-25","requires":[161,170],"discussionsTo":"https://ethereum-magicians.org/t/eip-2926-chunk-based-code-merkleization/4555","repo":"EIPs","label":"EIP-2926","officialUrl":"https://eips.ethereum.org/EIPS/eip-2926","sourceUrl":"https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2926.md","url":"https://eips.huatuo.xyz/eip-2926/","tldr":{"en":"Splits contract bytecode into 31-byte chunks committed in a per-account trie, so stateless clients only need the chunks a transaction actually touches instead of whole contracts.","ja":"コントラクトのバイトコードを 31 バイトのチャンクに分割し、アカウントごとのトライにコミットすることで、ステートレスクライアントがコントラクト全体ではなくトランザクションが実際に触れるチャンクだけを必要とするようにする。","ko":"컨트랙트 바이트코드를 31바이트 청크로 나눠 계정별 트라이에 커밋함으로써, 스테이트리스 클라이언트가 컨트랙트 전체가 아니라 트랜잭션이 실제로 건드리는 청크만 필요로 하게 한다.","zh":"把合约字节码切分成 31 字节的块，并在每个账户的树中提交承诺，使无状态客户端只需要交易实际触及的那些块，而不是整个合约。"},"tags":["statelessness","state","bytecode","witness","core"],"explainers":{"en":{"lang":"en","tldr":"Splits contract bytecode into 31-byte chunks committed in a per-account trie, so stateless clients only need the chunks a transaction actually touches instead of whole contracts.","tags":["statelessness","state","bytecode","witness","core"],"related":[3102,6800,7864,4762,170],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-2926/","markdown":"## What problem does it solve?\n\nA stateless client verifies a block using a **witness**: the pieces of state the block touches, plus proofs that they belong to the state root. Today a contract's code is committed as one hash, so proving even one executed instruction means shipping the whole contract (up to 24 KB, see [EIP-170](/eip-170/)). The spec notes bytecode is the second-largest part of witnesses after proof hashes, and would become the largest once the trie itself gets more efficient.\n\nEIP-2926 **merkleizes code**: it breaks bytecode into fixed-size chunks and commits to them in a small trie, so a witness can include just the chunks that were executed.\n\n## How it works\n\n**Chunking.** Code is cut into 31-byte chunks. Each chunk is stored with a one-byte **first instruction offset (FIO)**: where the first real instruction starts. It is non-zero only when a `PUSHn` from the previous chunk spills its data across the boundary (and equals 31 if the whole chunk is push data). With FIO, a client holding only some chunks can still do safe `JUMPDEST` analysis.\n\n**Code trie.** For a non-empty contract, the account gains two fields:\n\n- `codeSize` = byte length of the code\n- `codeRoot` = root of a trie whose leaves are:\n  - key `BE(i, 4)` → value `BE(FIO_i, 1) || chunk_i`\n  - key `max(u256)` → version byte `0`\n\n`codeHash` is kept so `EXTCODEHASH` behaves the same. Accounts with no code omit both new fields.\n\n**Costs.** Code deposit cost rises from 200 to 500 gas per byte (aligned with [EIP-4762](/eip-4762/)), and the rationale sketches a warming cost for reading a not-yet-accessed chunk.\n\n**Transition.** After activation, new contracts use the new format immediately. Existing contracts are converted by a sweep: at the end of each block, clients convert a fixed number of accounts (`ITERATOR_STRIDE`, provisionally 50,000), finishing in roughly 10,000 blocks by the spec's estimate. Shared bytecode only needs chunking once.\n\n## Sample code\n\nChunking with first-instruction offsets (Python):\n\n```python\nCHUNK_SIZE = 31\n\ndef chunkify(code: bytes) -\u003e list[tuple[int, bytes]]:\n    chunks, pc = [], 0\n    for start in range(0, len(code), CHUNK_SIZE):\n        end = start + CHUNK_SIZE\n        fio = min(max(pc - start, 0), CHUNK_SIZE)   # where the first opcode begins\n        chunks.append((fio, code[start:end]))\n        # advance pc past every instruction that starts inside this chunk\n        while pc \u003c end and pc \u003c len(code):\n            op = code[pc]\n            pc += 1 + (op - 0x5F if 0x60 \u003c= op \u003c= 0x7F else 0)  # PUSH1..PUSH32\n    return chunks\n\ndef leaves(code: bytes):\n    for i, (fio, chunk) in enumerate(chunkify(code)):\n        yield i.to_bytes(4, \"big\"), bytes([fio]) + chunk\n```\n\n## Things to know\n\n- **Status: Draft.** Constants such as the chunk size, `ITERATOR_STRIDE` and the activation time are still open, and test vectors are TBD.\n- The code trie uses the same format as the account trie. If Ethereum moves to a new state tree ([EIP-6800](/eip-6800/) verkle, or [EIP-7864](/eip-7864/) binary), the code trie would have to be converted along with it.\n- Contracts see no behavioural change apart from gas costs, but the state layout change requires a hard fork.\n- For [EIP-7702](/eip-7702/) delegated accounts, the spec sets the code size to 23 and forwards `CODESIZE` / `CODECOPY` to the delegate.\n"},"ja":{"lang":"ja","tldr":"コントラクトのバイトコードを 31 バイトのチャンクに分割し、アカウントごとのトライにコミットすることで、ステートレスクライアントがコントラクト全体ではなくトランザクションが実際に触れるチャンクだけを必要とするようにする。","tags":["statelessness","state","bytecode","witness","core"],"related":[3102,6800,7864,4762,170],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-2926/","markdown":"## 何を解決するのか\n\nステートレスクライアントは**ウィットネス**を使ってブロックを検証します。ウィットネスとは、ブロックが触れるステートの断片と、それらがステートルートに属することの証明です。現在、コントラクトのコードは 1 つのハッシュとしてコミットされているため、実行された命令を 1 つ証明するだけでもコントラクト全体（最大 24 KB、[EIP-170](/eip-170/) 参照）を送る必要があります。仕様は、バイトコードがウィットネスの中でプルーフのハッシュに次いで 2 番目に大きな部分であり、トライ自体が効率化されれば最大になると述べています。\n\nEIP-2926 は**コードをマークル化**します。バイトコードを固定サイズのチャンクに分割して小さなトライにコミットするので、ウィットネスには実行されたチャンクだけを含められます。\n\n## 仕組み\n\n**チャンク化。** コードは 31 バイトのチャンクに切り分けられます。各チャンクは 1 バイトの**最初の命令オフセット（FIO）**とともに保存されます。これは本当の最初の命令が始まる位置です。前のチャンクの `PUSHn` のデータが境界をまたいではみ出している場合にのみ 0 以外になります（チャンク全体が push データなら 31 です）。FIO があるので、一部のチャンクしか持たないクライアントでも安全に `JUMPDEST` 解析ができます。\n\n**コードトライ。** 空でないコントラクトでは、アカウントに 2 つのフィールドが加わります。\n\n- `codeSize` = コードのバイト長\n- `codeRoot` = 次のようなリーフを持つトライのルート:\n  - キー `BE(i, 4)` → 値 `BE(FIO_i, 1) || chunk_i`\n  - キー `max(u256)` → バージョンバイト `0`\n\n`EXTCODEHASH` が同じ挙動を保てるよう、`codeHash` は残されます。コードのないアカウントは、新しい 2 つのフィールドを持ちません。\n\n**コスト。** コードデポジットのコストはバイトあたり 200 ガスから 500 ガスに上がります（[EIP-4762](/eip-4762/) に合わせたもの）。根拠の説明では、まだアクセスされていないチャンクを読むためのウォーミングコストも示されています。\n\n**移行。** 有効化後、新しいコントラクトはすぐに新形式を使います。既存のコントラクトはスイープによって変換されます。各ブロックの終わりに、クライアントが一定数のアカウント（`ITERATOR_STRIDE`、暫定で 50,000）を変換し、仕様の見積もりでは約 10,000 ブロックで完了します。共有されているバイトコードのチャンク化は 1 回で済みます。\n\n## サンプルコード\n\n最初の命令オフセット付きのチャンク化（Python）:\n\n```python\nCHUNK_SIZE = 31\n\ndef chunkify(code: bytes) -\u003e list[tuple[int, bytes]]:\n    chunks, pc = [], 0\n    for start in range(0, len(code), CHUNK_SIZE):\n        end = start + CHUNK_SIZE\n        fio = min(max(pc - start, 0), CHUNK_SIZE)   # where the first opcode begins\n        chunks.append((fio, code[start:end]))\n        # advance pc past every instruction that starts inside this chunk\n        while pc \u003c end and pc \u003c len(code):\n            op = code[pc]\n            pc += 1 + (op - 0x5F if 0x60 \u003c= op \u003c= 0x7F else 0)  # PUSH1..PUSH32\n    return chunks\n\ndef leaves(code: bytes):\n    for i, (fio, chunk) in enumerate(chunkify(code)):\n        yield i.to_bytes(4, \"big\"), bytes([fio]) + chunk\n```\n\n## 知っておくべきこと\n\n- **ステータス: Draft。** チャンクサイズ、`ITERATOR_STRIDE`、有効化時期などの定数はまだ未定で、テストベクターは TBD です。\n- コードトライはアカウントトライと同じ形式を使います。Ethereum が新しいステートツリー（[EIP-6800](/eip-6800/) の Verkle、または [EIP-7864](/eip-7864/) のバイナリ）に移行する場合、コードトライも一緒に変換する必要があります。\n- コントラクトから見た挙動の変化はガスコスト以外にありませんが、ステートレイアウトの変更にはハードフォークが必要です。\n- [EIP-7702](/eip-7702/) で委任されたアカウントについては、仕様はコードサイズを 23 に設定し、`CODESIZE` / `CODECOPY` を委任先へ転送します。\n"},"ko":{"lang":"ko","tldr":"컨트랙트 바이트코드를 31바이트 청크로 나눠 계정별 트라이에 커밋함으로써, 스테이트리스 클라이언트가 컨트랙트 전체가 아니라 트랜잭션이 실제로 건드리는 청크만 필요로 하게 한다.","tags":["statelessness","state","bytecode","witness","core"],"related":[3102,6800,7864,4762,170],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-2926/","markdown":"## 어떤 문제를 해결하나요?\n\n스테이트리스 클라이언트는 **witness**로 블록을 검증합니다. witness는 블록이 건드리는 상태 조각과, 그것들이 상태 루트에 속함을 보이는 증명입니다. 오늘날 컨트랙트 코드는 해시 하나로 커밋되어 있으므로, 실행된 명령어 하나를 증명하려 해도 컨트랙트 전체(최대 24 KB, [EIP-170](/eip-170/) 참고)를 보내야 합니다. 사양은 바이트코드가 witness에서 증명 해시 다음으로 큰 부분이며, 트라이 자체가 더 효율적이 되면 가장 큰 부분이 될 것이라고 언급합니다.\n\nEIP-2926은 **코드를 머클화**합니다. 바이트코드를 고정 크기 청크로 나누고 작은 트라이에 커밋하므로, witness에는 실행된 청크만 넣으면 됩니다.\n\n## 어떻게 동작하나요?\n\n**청크 분할.** 코드는 31바이트 청크로 잘립니다. 각 청크는 1바이트의 **첫 명령어 오프셋(FIO)**과 함께 저장됩니다. 첫 번째 실제 명령어가 시작되는 위치입니다. 이전 청크의 `PUSHn` 데이터가 경계를 넘어 흘러온 경우에만 0이 아니며(청크 전체가 push 데이터이면 31입니다), FIO 덕분에 일부 청크만 가진 클라이언트도 안전하게 `JUMPDEST` 분석을 할 수 있습니다.\n\n**코드 트라이.** 비어 있지 않은 컨트랙트의 계정에는 필드 두 개가 추가됩니다.\n\n- `codeSize` = 코드의 바이트 길이\n- `codeRoot` = 다음과 같은 리프를 가진 트라이의 루트:\n  - 키 `BE(i, 4)` → 값 `BE(FIO_i, 1) || chunk_i`\n  - 키 `max(u256)` → 버전 바이트 `0`\n\n`EXTCODEHASH`가 같게 동작하도록 `codeHash`는 유지됩니다. 코드가 없는 계정은 새 필드 두 개를 모두 생략합니다.\n\n**비용.** 코드 예치 비용은 바이트당 200 가스에서 500 가스로 오릅니다([EIP-4762](/eip-4762/)와 맞춤). 근거 설명에서는 아직 접근하지 않은 청크를 읽을 때의 워밍 비용도 스케치합니다.\n\n**전환.** 활성화 이후 새 컨트랙트는 즉시 새 형식을 사용합니다. 기존 컨트랙트는 스윕으로 변환됩니다. 각 블록이 끝날 때 클라이언트가 정해진 수의 계정(`ITERATOR_STRIDE`, 잠정 50,000)을 변환하며, 사양의 추정으로는 약 10,000블록 안에 끝납니다. 공유되는 바이트코드는 한 번만 청크로 나누면 됩니다.\n\n## 샘플 코드\n\n첫 명령어 오프셋을 포함한 청크 분할(Python):\n\n```python\nCHUNK_SIZE = 31\n\ndef chunkify(code: bytes) -\u003e list[tuple[int, bytes]]:\n    chunks, pc = [], 0\n    for start in range(0, len(code), CHUNK_SIZE):\n        end = start + CHUNK_SIZE\n        fio = min(max(pc - start, 0), CHUNK_SIZE)   # where the first opcode begins\n        chunks.append((fio, code[start:end]))\n        # advance pc past every instruction that starts inside this chunk\n        while pc \u003c end and pc \u003c len(code):\n            op = code[pc]\n            pc += 1 + (op - 0x5F if 0x60 \u003c= op \u003c= 0x7F else 0)  # PUSH1..PUSH32\n    return chunks\n\ndef leaves(code: bytes):\n    for i, (fio, chunk) in enumerate(chunkify(code)):\n        yield i.to_bytes(4, \"big\"), bytes([fio]) + chunk\n```\n\n## 알아둘 점\n\n- **상태: Draft.** 청크 크기, `ITERATOR_STRIDE`, 활성화 시점 같은 상수는 아직 정해지지 않았고 테스트 벡터는 TBD입니다.\n- 코드 트라이는 계정 트라이와 같은 형식을 씁니다. 이더리움이 새로운 상태 트리([EIP-6800](/eip-6800/)의 verkle 또는 [EIP-7864](/eip-7864/)의 이진 트리)로 옮겨 가면 코드 트라이도 함께 변환해야 합니다.\n- 컨트랙트가 보는 동작은 가스 비용을 제외하면 달라지지 않지만, 상태 레이아웃 변경에는 하드 포크가 필요합니다.\n- [EIP-7702](/eip-7702/)로 위임된 계정의 경우, 사양은 코드 크기를 23으로 설정하고 `CODESIZE` / `CODECOPY`를 위임 대상으로 전달합니다.\n"},"zh":{"lang":"zh","tldr":"把合约字节码切分成 31 字节的块，并在每个账户的树中提交承诺，使无状态客户端只需要交易实际触及的那些块，而不是整个合约。","tags":["statelessness","state","bytecode","witness","core"],"related":[3102,6800,7864,4762,170],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-2926/","markdown":"## 它解决什么问题？\n\n无状态客户端使用 **witness** 来验证区块：即区块触及的状态片段，加上证明它们属于状态根的证明。如今合约的代码以单个哈希提交，所以即使只为证明执行了一条指令，也必须发送整个合约（最大 24 KB，参见 [EIP-170](/eip-170/)）。规范指出，字节码是 witness 中仅次于证明哈希的第二大部分，一旦树本身变得更高效，它就会成为最大的部分。\n\nEIP-2926 对**代码做默克尔化**：它把字节码拆成固定大小的块，并在一棵小树中提交这些块，这样 witness 就只需包含被执行的那些块。\n\n## 它如何运作\n\n**分块。** 代码被切成 31 字节的块。每个块与一个单字节的**首条指令偏移量（FIO）**一起存储：即第一条真正的指令从哪里开始。只有当前一个块的 `PUSHn` 的数据跨过边界溢出到本块时，它才不为零（如果整个块都是 push 数据，则等于 31）。有了 FIO，只持有部分块的客户端仍然能安全地做 `JUMPDEST` 分析。\n\n**代码树。** 对于非空合约，账户会增加两个字段：\n\n- `codeSize` = 代码的字节长度\n- `codeRoot` = 一棵树的根，其叶子为：\n  - 键 `BE(i, 4)` → 值 `BE(FIO_i, 1) || chunk_i`\n  - 键 `max(u256)` → 版本字节 `0`\n\n保留 `codeHash`，使 `EXTCODEHASH` 的行为保持不变。没有代码的账户省略这两个新字段。\n\n**成本。** 代码存入成本从每字节 200 gas 提高到 500 gas（与 [EIP-4762](/eip-4762/) 对齐），设计理由部分还勾勒了读取尚未被访问的块时的预热成本。\n\n**过渡。** 激活后，新合约立即使用新格式。现有合约通过一次扫描转换：在每个区块末尾，客户端转换固定数量的账户（`ITERATOR_STRIDE`，暂定 50,000），按规范的估算大约 10,000 个区块完成。共享的字节码只需分块一次。\n\n## 示例代码\n\n带首条指令偏移量的分块（Python）：\n\n```python\nCHUNK_SIZE = 31\n\ndef chunkify(code: bytes) -\u003e list[tuple[int, bytes]]:\n    chunks, pc = [], 0\n    for start in range(0, len(code), CHUNK_SIZE):\n        end = start + CHUNK_SIZE\n        fio = min(max(pc - start, 0), CHUNK_SIZE)   # where the first opcode begins\n        chunks.append((fio, code[start:end]))\n        # advance pc past every instruction that starts inside this chunk\n        while pc \u003c end and pc \u003c len(code):\n            op = code[pc]\n            pc += 1 + (op - 0x5F if 0x60 \u003c= op \u003c= 0x7F else 0)  # PUSH1..PUSH32\n    return chunks\n\ndef leaves(code: bytes):\n    for i, (fio, chunk) in enumerate(chunkify(code)):\n        yield i.to_bytes(4, \"big\"), bytes([fio]) + chunk\n```\n\n## 需要注意\n\n- **状态：Draft。** 块大小、`ITERATOR_STRIDE` 和激活时间等常量仍未确定，测试向量待定（TBD）。\n- 代码树使用与账户树相同的格式。如果以太坊迁移到新的状态树（[EIP-6800](/eip-6800/) 的 verkle 树，或 [EIP-7864](/eip-7864/) 的二叉树），代码树也必须随之转换。\n- 除 gas 成本外，合约不会看到任何行为变化，但状态布局的变更需要一次硬分叉。\n- 对于 [EIP-7702](/eip-7702/) 委托的账户，规范把代码大小设为 23，并把 `CODESIZE` / `CODECOPY` 转发给被委托方。\n"}},"requiredBy":[8007]}
