{"eip":7823,"title":"Set upper bounds for MODEXP","description":"Each input field is restricted to a maximum of 8192 bits","authors":["Alex Beregszaszi (@axic)","Radoslaw Zagorowicz (@rodiazet)"],"status":"Final","type":"Standards Track","category":"Core","created":"2024-11-11","requires":[198],"discussionsTo":"https://ethereum-magicians.org/t/eip-7823-set-upper-bounds-for-modexp/21798","repo":"EIPs","label":"EIP-7823","officialUrl":"https://eips.ethereum.org/EIPS/eip-7823","sourceUrl":"https://github.com/ethereum/EIPs/blob/master/EIPS/eip-7823.md","url":"https://eips.huatuo.xyz/eip-7823/","tldr":{"en":"Caps each length field of the MODEXP precompile at 1024 bytes (8192 bits), removing an unbounded input space that had caused repeated consensus bugs.","ja":"MODEXP プリコンパイルの各長さフィールドを 1024 バイト（8192 ビット）に制限し、繰り返しコンセンサスバグの原因となってきた無制限の入力空間を取り除く。","ko":"MODEXP 프리컴파일의 각 길이 필드를 1024바이트(8192비트)로 제한해, 반복적인 합의 버그의 원인이던 무제한 입력 공간을 없앤다.","zh":"把 MODEXP 预编译的每个长度字段限制在 1024 字节（8192 位）以内，消除曾多次引发共识 bug 的无界输入空间。"},"tags":["precompile","modexp","cryptography","evm","core","fusaka"],"explainers":{"en":{"lang":"en","tldr":"Caps each length field of the MODEXP precompile at 1024 bytes (8192 bits), removing an unbounded input space that had caused repeated consensus bugs.","tags":["precompile","modexp","cryptography","evm","core","fusaka"],"related":[198,7607,2565],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-7823/","markdown":"## What problem does it solve?\n\nThe MODEXP precompile at address `0x05`, added by [EIP-198](/eip-198/), computes `base ** exponent % modulus` on arbitrarily large numbers. \"Arbitrarily large\" is the problem: each operand's length is declared in the input and was unbounded, so client teams had to handle and test an effectively infinite input space. MODEXP has been the source of numerous consensus bugs, many triggered by deliberately strange, impractically long inputs. Its gas pricing is also complex because of the unbounded sizes.\n\nReal-world use is far smaller. An on-chain analysis in the spec, covering blocks from Byzantium (April 2018) to January 2025, found that no successful call ever used an input longer than 513 bytes; almost all used 32, 128 or 256 bytes.\n\n## How it works\n\nThe input format from EIP-198 is unchanged:\n\n```\n\u003clength_of_BASE\u003e \u003clength_of_EXPONENT\u003e \u003clength_of_MODULUS\u003e \u003cBASE\u003e \u003cEXPONENT\u003e \u003cMODULUS\u003e\n```\n\nThe new rule: each of the three lengths must be **≤ 1024 bytes (8192 bits)**. If any length exceeds that, the precompile fails, returns an error and consumes all gas supplied to it.\n\nWhy 8192 bits? It still covers every practical use:\n\n- RSA signature verification with keys up to 8192 bits (1024/2048/4096 are common).\n- Elliptic-curve arithmetic, which typically needs at most 384 bits.\n\nA bounded input also makes it more realistic to replace the precompile later with ordinary EVM code (for example using EVMMAX-style instructions), with fast paths for common sizes.\n\n## Sample code\n\nCalling MODEXP from Solidity, with a guard that mirrors the new limit:\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nlibrary ModExp {\n    uint256 constant MAX_LEN = 1024; // EIP-7823 limit, in bytes\n\n    function modexp(bytes memory b, bytes memory e, bytes memory m)\n        internal view returns (bytes memory result)\n    {\n        require(b.length \u003c= MAX_LEN \u0026\u0026 e.length \u003c= MAX_LEN \u0026\u0026 m.length \u003c= MAX_LEN, \"too long\");\n        bytes memory input = abi.encodePacked(\n            uint256(b.length), uint256(e.length), uint256(m.length), b, e, m\n        );\n        result = new bytes(m.length);\n        bool ok;\n        assembly {\n            ok := staticcall(gas(), 0x05, add(input, 32), mload(input),\n                             add(result, 32), mload(m))\n        }\n        require(ok, \"modexp failed\");\n    }\n}\n```\n\n## Things to know\n\n- **Status: Final**, included in the Fusaka upgrade ([EIP-7607](/eip-7607/)).\n- Technically backwards incompatible, but the spec's analysis found no past transaction that would have behaved differently.\n- The limit applies to the declared lengths, not just the actual bytes supplied, so an over-long length header fails even if the data is short.\n- The pricing formula is not changed by this EIP; MODEXP repricing is handled separately (see [EIP-2565](/eip-2565/) for the earlier repricing).\n"},"ja":{"lang":"ja","tldr":"MODEXP プリコンパイルの各長さフィールドを 1024 バイト（8192 ビット）に制限し、繰り返しコンセンサスバグの原因となってきた無制限の入力空間を取り除く。","tags":["precompile","modexp","cryptography","evm","core","fusaka"],"related":[198,7607,2565],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-7823/","markdown":"## 何を解決するのか\n\n[EIP-198](/eip-198/) で追加された、アドレス `0x05` の MODEXP プリコンパイルは、任意に大きな数に対して `base ** exponent % modulus` を計算します。問題は「任意に大きい」ことです。各オペランドの長さは入力の中で宣言され、上限がなかったため、クライアントチームは事実上無限の入力空間を扱い、テストしなければなりませんでした。MODEXP は数多くのコンセンサスバグの原因となっており、その多くは意図的に奇妙で非現実的に長い入力によって引き起こされました。無制限のサイズのため、ガス価格の設定も複雑です。\n\n実際の利用ははるかに小さい範囲に収まります。仕様に載っているオンチェーン分析（Byzantium（2018 年 4 月）から 2025 年 1 月までのブロックが対象）では、513 バイトを超える入力を使った成功呼び出しは一度もなく、ほとんどが 32、128、256 バイトを使っていました。\n\n## 仕組み\n\nEIP-198 の入力形式は変わりません。\n\n```\n\u003clength_of_BASE\u003e \u003clength_of_EXPONENT\u003e \u003clength_of_MODULUS\u003e \u003cBASE\u003e \u003cEXPONENT\u003e \u003cMODULUS\u003e\n```\n\n新しいルールは、3 つの長さがそれぞれ **1024 バイト（8192 ビット）以下**でなければならない、というものです。いずれかの長さがそれを超えると、プリコンパイルは失敗してエラーを返し、渡されたガスをすべて消費します。\n\nなぜ 8192 ビットなのか。現実的な用途をすべてカバーできるからです。\n\n- 8192 ビットまでの鍵による RSA 署名検証（1024/2048/4096 が一般的）。\n- 楕円曲線演算。通常は最大でも 384 ビットで足ります。\n\n入力に上限があれば、将来このプリコンパイルを、一般的なサイズ向けの高速パスを備えた通常の EVM コード（たとえば EVMMAX 系の命令を使うもの）に置き換えることも、より現実的になります。\n\n## サンプルコード\n\n新しい上限と同じ検査を入れて、Solidity から MODEXP を呼び出す例:\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nlibrary ModExp {\n    uint256 constant MAX_LEN = 1024; // EIP-7823 limit, in bytes\n\n    function modexp(bytes memory b, bytes memory e, bytes memory m)\n        internal view returns (bytes memory result)\n    {\n        require(b.length \u003c= MAX_LEN \u0026\u0026 e.length \u003c= MAX_LEN \u0026\u0026 m.length \u003c= MAX_LEN, \"too long\");\n        bytes memory input = abi.encodePacked(\n            uint256(b.length), uint256(e.length), uint256(m.length), b, e, m\n        );\n        result = new bytes(m.length);\n        bool ok;\n        assembly {\n            ok := staticcall(gas(), 0x05, add(input, 32), mload(input),\n                             add(result, 32), mload(m))\n        }\n        require(ok, \"modexp failed\");\n    }\n}\n```\n\n## 知っておくべきこと\n\n- **ステータス: Final**。Fusaka アップグレード（[EIP-7607](/eip-7607/)）に含まれています。\n- 技術的には後方互換性がありませんが、仕様の分析では、過去のトランザクションで動作が変わるものは見つかりませんでした。\n- 上限は、実際に渡されたバイト数ではなく宣言された長さに適用されるため、データが短くても、長すぎる長さのヘッダーは失敗します。\n- この EIP は価格式を変更しません。MODEXP の価格再設定は別に扱われます（以前の再設定は [EIP-2565](/eip-2565/) を参照）。\n"},"ko":{"lang":"ko","tldr":"MODEXP 프리컴파일의 각 길이 필드를 1024바이트(8192비트)로 제한해, 반복적인 합의 버그의 원인이던 무제한 입력 공간을 없앤다.","tags":["precompile","modexp","cryptography","evm","core","fusaka"],"related":[198,7607,2565],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-7823/","markdown":"## 어떤 문제를 해결하나요?\n\n[EIP-198](/eip-198/)이 추가한 주소 `0x05`의 MODEXP 프리컴파일은 임의로 큰 수에 대해 `base ** exponent % modulus`를 계산합니다. 문제는 \"임의로 크다\"는 점입니다. 각 피연산자의 길이는 입력에서 선언되었고 상한이 없었기 때문에, 클라이언트 팀은 사실상 무한한 입력 공간을 처리하고 테스트해야 했습니다. MODEXP는 수많은 합의 버그의 원인이었고, 그 중 다수는 일부러 이상하고 비현실적으로 긴 입력으로 유발되었습니다. 크기에 상한이 없어서 가스 가격 책정도 복잡합니다.\n\n실제 사용은 훨씬 작은 범위입니다. 명세에 실린 온체인 분석(Byzantium(2018년 4월)부터 2025년 1월까지의 블록 대상)에 따르면, 513바이트보다 긴 입력을 사용한 성공 호출은 한 번도 없었고 거의 대부분 32, 128, 256바이트를 사용했습니다.\n\n## 어떻게 동작하나요?\n\nEIP-198의 입력 형식은 바뀌지 않습니다.\n\n```\n\u003clength_of_BASE\u003e \u003clength_of_EXPONENT\u003e \u003clength_of_MODULUS\u003e \u003cBASE\u003e \u003cEXPONENT\u003e \u003cMODULUS\u003e\n```\n\n새 규칙은 세 길이가 각각 **1024바이트(8192비트) 이하**여야 한다는 것입니다. 어느 하나라도 이를 넘으면 프리컴파일은 실패하고 오류를 반환하며 전달된 가스를 모두 소모합니다.\n\n왜 8192비트일까요? 현실적인 용도를 모두 포괄하기 때문입니다.\n\n- 최대 8192비트 키를 사용하는 RSA 서명 검증(1024/2048/4096이 흔함).\n- 보통 최대 384비트면 되는 타원 곡선 연산.\n\n입력에 상한이 있으면, 나중에 이 프리컴파일을 일반적인 크기에 대한 빠른 경로를 갖춘 일반 EVM 코드(예: EVMMAX 방식 명령어 사용)로 대체하는 것도 더 현실적이 됩니다.\n\n## 샘플 코드\n\n새 한도와 같은 검사를 넣어 Solidity에서 MODEXP 호출하기:\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nlibrary ModExp {\n    uint256 constant MAX_LEN = 1024; // EIP-7823 limit, in bytes\n\n    function modexp(bytes memory b, bytes memory e, bytes memory m)\n        internal view returns (bytes memory result)\n    {\n        require(b.length \u003c= MAX_LEN \u0026\u0026 e.length \u003c= MAX_LEN \u0026\u0026 m.length \u003c= MAX_LEN, \"too long\");\n        bytes memory input = abi.encodePacked(\n            uint256(b.length), uint256(e.length), uint256(m.length), b, e, m\n        );\n        result = new bytes(m.length);\n        bool ok;\n        assembly {\n            ok := staticcall(gas(), 0x05, add(input, 32), mload(input),\n                             add(result, 32), mload(m))\n        }\n        require(ok, \"modexp failed\");\n    }\n}\n```\n\n## 알아둘 점\n\n- **상태: Final**, Fusaka 업그레이드([EIP-7607](/eip-7607/))에 포함되었습니다.\n- 기술적으로는 하위 호환되지 않지만, 명세의 분석에서는 과거 트랜잭션 중 동작이 달라질 것이 발견되지 않았습니다.\n- 한도는 실제로 제공된 바이트가 아니라 선언된 길이에 적용되므로, 데이터가 짧아도 지나치게 긴 길이 헤더는 실패합니다.\n- 이 EIP는 가격 공식을 바꾸지 않습니다. MODEXP 가격 재조정은 별도로 다룹니다(이전 재조정은 [EIP-2565](/eip-2565/) 참고).\n"},"zh":{"lang":"zh","tldr":"把 MODEXP 预编译的每个长度字段限制在 1024 字节（8192 位）以内，消除曾多次引发共识 bug 的无界输入空间。","tags":["precompile","modexp","cryptography","evm","core","fusaka"],"related":[198,7607,2565],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-7823/","markdown":"## 它解决什么问题？\n\n位于地址 `0x05` 的 MODEXP 预编译由 [EIP-198](/eip-198/) 引入，用来对任意大的数计算 `base ** exponent % modulus`。问题就在于\"任意大\"：每个操作数的长度都在输入中声明，而且没有上限，所以客户端团队必须处理并测试一个实际上无限的输入空间。MODEXP 一直是大量共识 bug 的来源，其中许多是由刻意构造的、古怪且长得不切实际的输入触发的。由于大小没有上限，它的 gas 定价也很复杂。\n\n实际使用的范围要小得多。规范中的一项链上分析覆盖了从 Byzantium（2018 年 4 月）到 2025 年 1 月的区块，发现没有任何一次成功调用使用过超过 513 字节的输入；几乎都是 32、128 或 256 字节。\n\n## 它如何运作\n\nEIP-198 的输入格式保持不变：\n\n```\n\u003clength_of_BASE\u003e \u003clength_of_EXPONENT\u003e \u003clength_of_MODULUS\u003e \u003cBASE\u003e \u003cEXPONENT\u003e \u003cMODULUS\u003e\n```\n\n新规则是：三个长度都必须 **≤ 1024 字节（8192 位）**。如果任何一个长度超过这个值，预编译就会失败，返回错误，并耗尽提供给它的全部 gas。\n\n为什么是 8192 位？因为它仍然涵盖所有实际用途：\n\n- 密钥最长 8192 位的 RSA 签名验证（常见的是 1024/2048/4096）。\n- 椭圆曲线运算，通常最多需要 384 位。\n\n输入有界之后，将来用普通 EVM 代码（例如使用 EVMMAX 风格的指令）取代该预编译，并为常见大小提供快速路径，也会更加现实。\n\n## 示例代码\n\n在 Solidity 中调用 MODEXP，并加入与新限制一致的检查：\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nlibrary ModExp {\n    uint256 constant MAX_LEN = 1024; // EIP-7823 limit, in bytes\n\n    function modexp(bytes memory b, bytes memory e, bytes memory m)\n        internal view returns (bytes memory result)\n    {\n        require(b.length \u003c= MAX_LEN \u0026\u0026 e.length \u003c= MAX_LEN \u0026\u0026 m.length \u003c= MAX_LEN, \"too long\");\n        bytes memory input = abi.encodePacked(\n            uint256(b.length), uint256(e.length), uint256(m.length), b, e, m\n        );\n        result = new bytes(m.length);\n        bool ok;\n        assembly {\n            ok := staticcall(gas(), 0x05, add(input, 32), mload(input),\n                             add(result, 32), mload(m))\n        }\n        require(ok, \"modexp failed\");\n    }\n}\n```\n\n## 需要注意\n\n- **状态：Final**，已包含在 Fusaka 升级（[EIP-7607](/eip-7607/)）中。\n- 从技术上说不向后兼容，但规范的分析没有发现过去有任何交易的行为会因此不同。\n- 该限制针对的是声明的长度，而不仅是实际提供的字节，所以即使数据很短，过长的长度头也会失败。\n- 本 EIP 没有改变定价公式；MODEXP 的重新定价另行处理（早先的重新定价见 [EIP-2565](/eip-2565/)）。\n"}},"requiredBy":[7607,8200]}
