{"eip":2565,"title":"ModExp Gas Cost","description":"Defines the gas cost of the ModExp (0x00..05) precompile.","authors":["Kelly Olson (@ineffectualproperty)","Sean Gulley (@sean-sn)","Simon Peffers (@simonatsn)","Justin Drake (@justindrake)","Dankrad Feist (@dankrad)"],"status":"Final","type":"Standards Track","category":"Core","created":"2020-03-20","requires":[198],"discussionsTo":"https://ethereum-magicians.org/t/big-integer-modular-exponentiation-eip-198-gas-cost/4150","repo":"EIPs","label":"EIP-2565","officialUrl":"https://eips.ethereum.org/EIPS/eip-2565","sourceUrl":"https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2565.md","url":"https://eips.huatuo.xyz/eip-2565/","tldr":{"en":"Replaced the gas formula for the ModExp precompile (0x05) with a simpler, benchmark-based one that made big-number modular exponentiation much cheaper, with a 200 gas floor.","ja":"ModExp プリコンパイル（0x05）のガス計算式を、より単純でベンチマークに基づくものに置き換え、巨大整数のべき乗剰余を大幅に安くした。下限は 200 ガス。","ko":"ModExp 프리컴파일(0x05)의 가스 공식을 더 단순하고 벤치마크에 기반한 공식으로 교체해 큰 수의 모듈러 거듭제곱을 훨씬 저렴하게 만들었다. 최소값은 200 gas.","zh":"用更简单、基于基准测试的公式取代了 ModExp 预编译（0x05）的 gas 公式，使大整数模幂运算便宜了许多，并设有 200 gas 的下限。"},"tags":["precompile","gas","cryptography","core","berlin"],"explainers":{"en":{"lang":"en","tldr":"Replaced the gas formula for the ModExp precompile (0x05) with a simpler, benchmark-based one that made big-number modular exponentiation much cheaper, with a 200 gas floor.","tags":["precompile","gas","cryptography","core","berlin"],"related":[198,7883,7823,2666],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-2565/","markdown":"## What problem does it solve?\n\n[EIP-198](/eip-198/) added the ModExp precompile at address `0x05`, which computes `base^exp mod modulus` on arbitrary-size integers. It is the building block for RSA signature checks, VDFs, accumulators and some SNARK verifiers.\n\nBenchmarks showed ModExp was overpriced compared with other precompiles, and that the EIP-198 complexity formula (modelled on Karatsuba multiplication) did not track real execution time well. ERC-2565 changed the pricing so these operations became practical on-chain. It went live in the Berlin upgrade.\n\n## How it works\n\nThe interface and arithmetic are unchanged; only gas changes. Cost is \"how hard is one multiplication\" times \"how many steps the exponentiation takes\", divided by 3:\n\n1. **Multiplication complexity**: take the larger of the base and modulus lengths in bytes, convert to 8-byte words (rounding up), and square it.\n2. **Iteration count**: roughly the bit length of the exponent minus one. For exponents longer than 32 bytes, add 8 per extra byte beyond 32, plus the bit length of the low 256 bits. Minimum 1.\n3. **Gas** = `max(200, floor(complexity * iterations / 3))`.\n\nSo the old divisor (`GQUADDIVISOR`, 20 in EIP-198) became 3, and a 200 gas minimum stops tiny inputs from being underpriced.\n\n```python\ndef gas(base_len, mod_len, exp_len, exponent):\n    words = math.ceil(max(base_len, mod_len) / 8)\n    complexity = words ** 2\n    if exp_len \u003c= 32 and exponent == 0:\n        iters = 0\n    elif exp_len \u003c= 32:\n        iters = exponent.bit_length() - 1\n    else:\n        iters = 8 * (exp_len - 32) + ((exponent \u0026 (2**256 - 1)).bit_length() - 1)\n    return max(200, complexity * max(iters, 1) // 3)\n```\n\nFrom the spec's test table: `modexp_nagydani_1_pow0x10001` dropped from 3276 to 341 gas, and `modexp_nagydani_5_pow0x10001` from 285900 to 87381.\n\n## Sample code\n\nCalling the precompile from Solidity. Input is three 32-byte lengths followed by base, exponent and modulus:\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nlibrary ModExp {\n    function modexp(bytes memory base, bytes memory exp, bytes memory mod)\n        internal view returns (bytes memory result)\n    {\n        bytes memory input = abi.encodePacked(\n            uint256(base.length), uint256(exp.length), uint256(mod.length),\n            base, exp, mod\n        );\n        bool ok;\n        (ok, result) = address(0x05).staticcall(input);\n        require(ok, \"modexp failed\");\n        // result has the same length as `mod`\n    }\n}\n```\n\n## Things to know\n\n- Status is **Final** and active since Berlin.\n- The spec flagged the main risk as making ModExp too cheap and opening a DoS vector. Later work revisited this: [EIP-7883](/eip-7883/) raises ModExp costs again and [EIP-7823](/eip-7823/) caps input sizes. Check which pricing applies on your target fork before hard-coding gas.\n- Input lengths, not values, drive most of the cost, so pass minimal-length byte strings.\n- [EIP-2666](/eip-2666/), a broader precompile repricing proposal, assumed this change was in place.\n"},"ja":{"lang":"ja","tldr":"ModExp プリコンパイル（0x05）のガス計算式を、より単純でベンチマークに基づくものに置き換え、巨大整数のべき乗剰余を大幅に安くした。下限は 200 ガス。","tags":["precompile","gas","cryptography","core","berlin"],"related":[198,7883,7823,2666],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-2565/","markdown":"## 何を解決するのか\n\n[EIP-198](/eip-198/) はアドレス `0x05` に ModExp プリコンパイルを追加しました。任意サイズの整数に対して `base^exp mod modulus` を計算します。RSA 署名の検証、VDF、アキュムレーター、一部の SNARK 検証器の部品になります。\n\nベンチマークの結果、ModExp は他のプリコンパイルに比べて割高であり、EIP-198 の複雑度の式（Karatsuba 乗算をモデルにしたもの）は実際の実行時間をうまく反映していないことが分かりました。ERC-2565 は価格設定を変更し、これらの演算がオンチェーンで実用的になりました。Berlin アップグレードで稼働を開始しました。\n\n## 仕組み\n\nインターフェースと算術は変わらず、ガスだけが変わります。コストは「1 回の乗算がどれだけ重いか」×「べき乗が何ステップかかるか」を 3 で割ったものです。\n\n1. **乗算の複雑度**: base と modulus の長さ（バイト）の大きい方を取り、8 バイトのワード数に変換（切り上げ）して、2 乗します。\n2. **反復回数**: おおよそ指数のビット長から 1 を引いた値。指数が 32 バイトを超える場合は、32 を超える 1 バイトごとに 8 を加え、さらに下位 256 ビットのビット長を加えます。最小値は 1。\n3. **ガス** = `max(200, floor(complexity * iterations / 3))`。\n\nつまり、以前の除数（EIP-198 では `GQUADDIVISOR` が 20）は 3 になり、200 ガスの最小値により小さな入力が安すぎる価格になるのを防いでいます。\n\n```python\ndef gas(base_len, mod_len, exp_len, exponent):\n    words = math.ceil(max(base_len, mod_len) / 8)\n    complexity = words ** 2\n    if exp_len \u003c= 32 and exponent == 0:\n        iters = 0\n    elif exp_len \u003c= 32:\n        iters = exponent.bit_length() - 1\n    else:\n        iters = 8 * (exp_len - 32) + ((exponent \u0026 (2**256 - 1)).bit_length() - 1)\n    return max(200, complexity * max(iters, 1) // 3)\n```\n\n仕様のテスト表より: `modexp_nagydani_1_pow0x10001` は 3276 から 341 ガスに、`modexp_nagydani_5_pow0x10001` は 285900 から 87381 に下がりました。\n\n## サンプルコード\n\nSolidity からプリコンパイルを呼び出します。入力は 32 バイトの長さ 3 つに続けて base、exponent、modulus を並べたものです。\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nlibrary ModExp {\n    function modexp(bytes memory base, bytes memory exp, bytes memory mod)\n        internal view returns (bytes memory result)\n    {\n        bytes memory input = abi.encodePacked(\n            uint256(base.length), uint256(exp.length), uint256(mod.length),\n            base, exp, mod\n        );\n        bool ok;\n        (ok, result) = address(0x05).staticcall(input);\n        require(ok, \"modexp failed\");\n        // result has the same length as `mod`\n    }\n}\n```\n\n## 知っておくべきこと\n\n- ステータスは **Final** で、Berlin 以降有効です。\n- 仕様は主なリスクとして、ModExp が安くなりすぎて DoS の経路が開くことを挙げていました。その後の作業でこの点が再検討されています。[EIP-7883](/eip-7883/) は ModExp のコストを再び引き上げ、[EIP-7823](/eip-7823/) は入力サイズに上限を設けます。ガスをハードコードする前に、対象のフォークでどの価格設定が適用されるか確認してください。\n- コストの大半を決めるのは値ではなく入力の長さなので、最小の長さのバイト列を渡してください。\n- より広範なプリコンパイルの価格見直し提案である [EIP-2666](/eip-2666/) は、この変更が適用済みであることを前提にしていました。\n"},"ko":{"lang":"ko","tldr":"ModExp 프리컴파일(0x05)의 가스 공식을 더 단순하고 벤치마크에 기반한 공식으로 교체해 큰 수의 모듈러 거듭제곱을 훨씬 저렴하게 만들었다. 최소값은 200 gas.","tags":["precompile","gas","cryptography","core","berlin"],"related":[198,7883,7823,2666],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-2565/","markdown":"## 어떤 문제를 해결하나요?\n\n[EIP-198](/eip-198/)은 주소 `0x05`에 ModExp 프리컴파일을 추가했습니다. 임의 크기의 정수에 대해 `base^exp mod modulus`를 계산합니다. RSA 서명 검증, VDF, 어큐뮬레이터, 일부 SNARK 검증기의 구성 요소입니다.\n\n벤치마크 결과 ModExp는 다른 프리컴파일에 비해 가격이 높게 책정되어 있었고, EIP-198의 복잡도 공식(Karatsuba 곱셈을 모델로 한 것)은 실제 실행 시간을 잘 반영하지 못했습니다. ERC-2565는 가격 책정을 바꿔 이런 연산이 온체인에서 실용적이 되도록 했습니다. Berlin 업그레이드에서 적용되었습니다.\n\n## 어떻게 동작하나요?\n\n인터페이스와 산술은 그대로이고 가스만 바뀝니다. 비용은 \"곱셈 한 번이 얼마나 어려운가\"에 \"거듭제곱이 몇 단계 걸리는가\"를 곱해 3으로 나눈 값입니다.\n\n1. **곱셈 복잡도**: base와 modulus의 바이트 길이 중 큰 쪽을 8바이트 워드로 변환(올림)하고 제곱합니다.\n2. **반복 횟수**: 대략 지수의 비트 길이에서 1을 뺀 값. 지수가 32바이트보다 길면 32바이트를 넘는 바이트마다 8을 더하고, 하위 256비트의 비트 길이를 더합니다. 최솟값은 1.\n3. **가스** = `max(200, floor(complexity * iterations / 3))`.\n\n즉 예전 나눗수(EIP-198에서 `GQUADDIVISOR`는 20)가 3이 되었고, 최소 200 gas가 아주 작은 입력의 가격이 너무 낮게 매겨지는 것을 막습니다.\n\n```python\ndef gas(base_len, mod_len, exp_len, exponent):\n    words = math.ceil(max(base_len, mod_len) / 8)\n    complexity = words ** 2\n    if exp_len \u003c= 32 and exponent == 0:\n        iters = 0\n    elif exp_len \u003c= 32:\n        iters = exponent.bit_length() - 1\n    else:\n        iters = 8 * (exp_len - 32) + ((exponent \u0026 (2**256 - 1)).bit_length() - 1)\n    return max(200, complexity * max(iters, 1) // 3)\n```\n\n스펙의 테스트 표에서: `modexp_nagydani_1_pow0x10001`은 3276에서 341 gas로, `modexp_nagydani_5_pow0x10001`은 285900에서 87381로 내려갔습니다.\n\n## 샘플 코드\n\nSolidity에서 프리컴파일 호출하기. 입력은 32바이트 길이 세 개 뒤에 base, exponent, modulus가 이어집니다.\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nlibrary ModExp {\n    function modexp(bytes memory base, bytes memory exp, bytes memory mod)\n        internal view returns (bytes memory result)\n    {\n        bytes memory input = abi.encodePacked(\n            uint256(base.length), uint256(exp.length), uint256(mod.length),\n            base, exp, mod\n        );\n        bool ok;\n        (ok, result) = address(0x05).staticcall(input);\n        require(ok, \"modexp failed\");\n        // result has the same length as `mod`\n    }\n}\n```\n\n## 알아둘 점\n\n- 상태는 **Final**이며 Berlin부터 활성화되어 있습니다.\n- 스펙은 주된 위험으로 ModExp가 너무 저렴해져 DoS 경로가 열리는 것을 꼽았습니다. 이후 작업에서 이 부분을 다시 검토했습니다. [EIP-7883](/eip-7883/)은 ModExp 비용을 다시 올리고 [EIP-7823](/eip-7823/)은 입력 크기에 상한을 둡니다. 가스를 하드코딩하기 전에 대상 포크에 어떤 가격 책정이 적용되는지 확인하세요.\n- 비용의 대부분은 값이 아니라 입력 길이가 결정하므로, 가능한 한 짧은 길이의 바이트열을 전달하세요.\n- 더 폭넓은 프리컴파일 가격 재조정 제안인 [EIP-2666](/eip-2666/)은 이 변경이 적용되어 있다고 가정했습니다.\n"},"zh":{"lang":"zh","tldr":"用更简单、基于基准测试的公式取代了 ModExp 预编译（0x05）的 gas 公式，使大整数模幂运算便宜了许多，并设有 200 gas 的下限。","tags":["precompile","gas","cryptography","core","berlin"],"related":[198,7883,7823,2666],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-2565/","markdown":"## 它解决什么问题？\n\n[EIP-198](/eip-198/) 在地址 `0x05` 添加了 ModExp 预编译，用于对任意大小的整数计算 `base^exp mod modulus`。它是 RSA 签名验证、VDF、累加器以及部分 SNARK 验证器的基础构件。\n\n基准测试表明，与其他预编译相比，ModExp 定价过高，而且 EIP-198 的复杂度公式（以 Karatsuba 乘法为模型）并不能很好地反映实际执行时间。ERC-2565 修改了定价，使这些运算在链上变得可行。它随 Berlin 升级上线。\n\n## 它如何运作\n\n接口和算术保持不变，只有 gas 变化。成本是\"一次乘法有多难\"乘以\"幂运算需要多少步\"，再除以 3：\n\n1. **乘法复杂度**：取 base 和 modulus 字节长度中较大者，转换为 8 字节的字（向上取整），然后平方。\n2. **迭代次数**：大致为指数的位长减一。对于超过 32 字节的指数，32 字节之后每多一个字节加 8，再加上低 256 位的位长。最小为 1。\n3. **Gas** = `max(200, floor(complexity * iterations / 3))`。\n\n因此，旧的除数（EIP-198 中 `GQUADDIVISOR` 为 20）变成了 3，200 gas 的下限则避免极小输入被定价过低。\n\n```python\ndef gas(base_len, mod_len, exp_len, exponent):\n    words = math.ceil(max(base_len, mod_len) / 8)\n    complexity = words ** 2\n    if exp_len \u003c= 32 and exponent == 0:\n        iters = 0\n    elif exp_len \u003c= 32:\n        iters = exponent.bit_length() - 1\n    else:\n        iters = 8 * (exp_len - 32) + ((exponent \u0026 (2**256 - 1)).bit_length() - 1)\n    return max(200, complexity * max(iters, 1) // 3)\n```\n\n来自规范测试表：`modexp_nagydani_1_pow0x10001` 从 3276 降到 341 gas，`modexp_nagydani_5_pow0x10001` 从 285900 降到 87381。\n\n## 示例代码\n\n在 Solidity 中调用该预编译。输入是三个 32 字节的长度，后面依次是 base、exponent 和 modulus：\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nlibrary ModExp {\n    function modexp(bytes memory base, bytes memory exp, bytes memory mod)\n        internal view returns (bytes memory result)\n    {\n        bytes memory input = abi.encodePacked(\n            uint256(base.length), uint256(exp.length), uint256(mod.length),\n            base, exp, mod\n        );\n        bool ok;\n        (ok, result) = address(0x05).staticcall(input);\n        require(ok, \"modexp failed\");\n        // result has the same length as `mod`\n    }\n}\n```\n\n## 需要注意\n\n- 状态为 **Final**，自 Berlin 起生效。\n- 规范将主要风险指为 ModExp 变得过于便宜，从而打开 DoS 攻击面。后续工作重新审视了这一点：[EIP-7883](/eip-7883/) 再次提高 ModExp 成本，[EIP-7823](/eip-7823/) 对输入大小设置上限。在硬编码 gas 之前，请确认目标分叉适用哪种定价。\n- 成本主要由输入的长度而非数值决定，因此请传入最短长度的字节串。\n- [EIP-2666](/eip-2666/) 是一项更广泛的预编译重新定价提案，它假定本变更已经生效。\n"}},"requiredBy":[2666,7883]}
