{"eip":7883,"title":"ModExp Gas Cost Increase","description":"Increases cost of ModExp precompile","authors":["Marcin Sobczak (@marcindsobczak)","Marek Moraczyński (@MarekM25)","Marcos Maceo (@stdevMac)"],"status":"Final","type":"Standards Track","category":"Core","created":"2025-02-11","requires":[2565],"discussionsTo":"https://ethereum-magicians.org/t/eip-7883-modexp-gas-cost-increase/22841","repo":"EIPs","label":"EIP-7883","officialUrl":"https://eips.ethereum.org/EIPS/eip-7883","sourceUrl":"https://github.com/ethereum/EIPs/blob/master/EIPS/eip-7883.md","url":"https://eips.huatuo.xyz/eip-7883/","tldr":{"en":"Raises the gas price of the ModExp precompile (minimum 200 to 500, general cost roughly tripled, large inputs priced more steeply) so its worst cases no longer block a higher block gas limit.","ja":"ModExp プリコンパイルの gas 価格を引き上げる（最小値を 200 から 500 へ、一般コストをおよそ 3 倍に、大きな入力はより急な価格に）。これにより、最悪のケースが、より高いブロック gas 上限の妨げにならなくなる。","ko":"ModExp 프리컴파일의 가스 가격을 올린다(최솟값 200에서 500으로, 일반 비용은 대략 3배로, 큰 입력은 더 가파르게). 그래서 최악의 경우가 더 높은 블록 가스 한도를 막지 않게 한다.","zh":"提高 ModExp 预编译的 gas 价格（最低值从 200 升至 500，一般成本约为原来的三倍，大输入的定价更陡），使其最坏情况不再阻碍提高区块 gas 上限。"},"tags":["gas","precompile","modexp","repricing","core"],"explainers":{"en":{"lang":"en","tldr":"Raises the gas price of the ModExp precompile (minimum 200 to 500, general cost roughly tripled, large inputs priced more steeply) so its worst cases no longer block a higher block gas limit.","tags":["gas","precompile","modexp","repricing","core"],"related":[198,2565,7823,7825],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-7883/","markdown":"## What problem does it solve?\n\nThe `ModExp` precompile at address `0x05` computes `base^exp mod modulus` on arbitrarily large integers ([EIP-198](/eip-198/)). Its gas formula was last tuned by [EIP-2565](/eip-2565/). Benchmarks across execution clients later showed that some inputs were significantly underpriced: a block filled with such calls could take far longer to execute than its gas suggests.\n\nThat matters because the block gas limit can only be raised safely if *every* operation's worst case fits in the time budget. EIP-7883 reprices `ModExp` so it stops being one of the bottlenecks to scaling the gas limit.\n\n## How it works\n\nThe interface and arithmetic are unchanged; only the gas formula moves. Three adjustments to the EIP-2565 formula:\n\n1. **Higher floor and no division by 3.** `max(200, complexity * iterations / 3)` becomes `max(500, complexity * iterations)`. The minimum goes from 200 to 500 gas and the general cost triples.\n2. **Large exponents cost more.** For exponents longer than 32 bytes, each extra byte adds 16 iterations instead of 8.\n3. **Minimum operand size and steeper scaling.** Multiplication complexity is at least 16 (as if operands were 32 bytes), and above 32 bytes it is `2 * words²` instead of `words²` (where `words = ceil(max(base_len, mod_len) / 8)`).\n\n```python\ndef multiplication_complexity(base_len, mod_len):\n    max_len = max(base_len, mod_len)\n    words = math.ceil(max_len / 8)\n    return 16 if max_len \u003c= 32 else 2 * words**2\n\ndef iteration_count(exp_len, exp):\n    if exp_len \u003c= 32 and exp == 0: n = 0\n    elif exp_len \u003c= 32:            n = exp.bit_length() - 1\n    else: n = 16 * (exp_len - 32) + ((exp \u0026 (2**256 - 1)).bit_length() - 1)\n    return max(n, 1)\n\ndef gas(base_len, mod_len, exp_len, exp):\n    return max(500, multiplication_complexity(base_len, mod_len) * iteration_count(exp_len, exp))\n```\n\nAccording to the spec's analysis, about 99.7 % of historical calls see either the 200 to 500 floor bump or a tripling. Some edge-case test vectors rise by 20x or more.\n\n## Sample code\n\nCalling the precompile from Solidity; budget gas generously, since hard-coded gas stipends written for the old pricing may now be too low:\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nlibrary ModExp {\n    /// Returns base^exp % mod for 32-byte operands.\n    function modexp(uint256 base, uint256 exp, uint256 mod) internal view returns (uint256 r) {\n        bytes memory input = abi.encodePacked(\n            uint256(32), uint256(32), uint256(32), // lengths of base, exp, mod\n            base, exp, mod\n        );\n        (bool ok, bytes memory out) = address(0x05).staticcall(input);\n        require(ok, \"modexp failed\");\n        r = abi.decode(out, (uint256));\n    }\n}\n```\n\n## Things to know\n\n- Status: **Final**. It is a backwards-incompatible gas change: contracts that call `0x05` with a fixed gas amount tuned to EIP-2565 prices may now run out of gas.\n- Typical RSA verification and big-number cryptography contracts are the main users affected; re-measure gas for your inputs instead of assuming old numbers.\n- It is often discussed together with [EIP-7823](/eip-7823/), which caps `ModExp` input sizes, and [EIP-7825](/eip-7825/), which caps per-transaction gas; together they bound worst-case work.\n- The spec notes the remaining risk is overpricing some cases, which it considers less harmful than underpricing.\n"},"ja":{"lang":"ja","tldr":"ModExp プリコンパイルの gas 価格を引き上げる（最小値を 200 から 500 へ、一般コストをおよそ 3 倍に、大きな入力はより急な価格に）。これにより、最悪のケースが、より高いブロック gas 上限の妨げにならなくなる。","tags":["gas","precompile","modexp","repricing","core"],"related":[198,2565,7823,7825],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-7883/","markdown":"## 何を解決するのか\n\nアドレス `0x05` の `ModExp` プリコンパイルは、任意の大きさの整数に対して `base^exp mod modulus` を計算します（[EIP-198](/eip-198/)）。その gas の式は、[EIP-2565](/eip-2565/) で最後に調整されました。その後、実行クライアントを横断したベンチマークにより、一部の入力が大幅に過小評価されていたことがわかりました。そうした呼び出しで満たされたブロックは、gas から想定されるよりはるかに長い実行時間がかかる可能性があります。\n\nこれが重要なのは、ブロック gas 上限は、*すべての*操作の最悪ケースが時間予算に収まる場合にのみ、安全に引き上げられるからです。EIP-7883 は `ModExp` の価格を見直し、gas 上限をスケールさせる際のボトルネックの 1 つでなくなるようにします。\n\n## 仕組み\n\nインターフェースと計算は変わりません。変わるのは gas の式だけです。EIP-2565 の式に 3 つの調整が加わります。\n\n1. **下限の引き上げと 3 での除算の廃止。** `max(200, complexity * iterations / 3)` は `max(500, complexity * iterations)` になります。最小値は 200 gas から 500 gas になり、一般コストは 3 倍になります。\n2. **大きな指数はコストが高くなる。** 32 バイトより長い指数では、追加の 1 バイトごとに 8 回ではなく 16 回のイテレーションが加わります。\n3. **オペランドの最小サイズと、より急なスケーリング。** 乗算の複雑度は少なくとも 16（オペランドが 32 バイトであるかのように）で、32 バイトを超えると `words²` ではなく `2 * words²` になります（`words = ceil(max(base_len, mod_len) / 8)`）。\n\n```python\ndef multiplication_complexity(base_len, mod_len):\n    max_len = max(base_len, mod_len)\n    words = math.ceil(max_len / 8)\n    return 16 if max_len \u003c= 32 else 2 * words**2\n\ndef iteration_count(exp_len, exp):\n    if exp_len \u003c= 32 and exp == 0: n = 0\n    elif exp_len \u003c= 32:            n = exp.bit_length() - 1\n    else: n = 16 * (exp_len - 32) + ((exp \u0026 (2**256 - 1)).bit_length() - 1)\n    return max(n, 1)\n\ndef gas(base_len, mod_len, exp_len, exp):\n    return max(500, multiplication_complexity(base_len, mod_len) * iteration_count(exp_len, exp))\n```\n\n仕様の分析によると、過去の呼び出しの約 99.7 % は、200 から 500 への下限の引き上げか、3 倍化のどちらかを受けます。一部のエッジケースのテストベクターは 20 倍以上に上がります。\n\n## サンプルコード\n\nSolidity からプリコンパイルを呼び出す例です。古い価格設定向けに書かれたハードコードの gas 手当は、今では低すぎる可能性があるため、gas は余裕を持って見積もってください。\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nlibrary ModExp {\n    /// Returns base^exp % mod for 32-byte operands.\n    function modexp(uint256 base, uint256 exp, uint256 mod) internal view returns (uint256 r) {\n        bytes memory input = abi.encodePacked(\n            uint256(32), uint256(32), uint256(32), // lengths of base, exp, mod\n            base, exp, mod\n        );\n        (bool ok, bytes memory out) = address(0x05).staticcall(input);\n        require(ok, \"modexp failed\");\n        r = abi.decode(out, (uint256));\n    }\n}\n```\n\n## 知っておくべきこと\n\n- ステータス: **Final**。これは後方互換性のない gas の変更です。EIP-2565 の価格に合わせて調整された固定の gas 量で `0x05` を呼び出すコントラクトは、gas が足りなくなる可能性があります。\n- 影響を受ける主な利用者は、典型的な RSA 検証や多倍長整数の暗号を扱うコントラクトです。古い数値を前提にせず、自分の入力で gas を測り直してください。\n- `ModExp` の入力サイズに上限を設ける [EIP-7823](/eip-7823/) や、トランザクションごとの gas に上限を設ける [EIP-7825](/eip-7825/) とあわせて議論されることが多く、これらを組み合わせることで最悪ケースの作業量に上限がかかります。\n- 仕様は、残るリスクは一部のケースでの過大評価であり、過小評価より害は小さいと考えている、と述べています。\n"},"ko":{"lang":"ko","tldr":"ModExp 프리컴파일의 가스 가격을 올린다(최솟값 200에서 500으로, 일반 비용은 대략 3배로, 큰 입력은 더 가파르게). 그래서 최악의 경우가 더 높은 블록 가스 한도를 막지 않게 한다.","tags":["gas","precompile","modexp","repricing","core"],"related":[198,2565,7823,7825],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-7883/","markdown":"## 어떤 문제를 해결하나요?\n\n주소 `0x05`의 `ModExp` 프리컴파일은 임의로 큰 정수에 대해 `base^exp mod modulus`를 계산합니다([EIP-198](/eip-198/)). 가스 공식은 [EIP-2565](/eip-2565/)에서 마지막으로 조정되었습니다. 이후 실행 클라이언트 전반의 벤치마크에서 일부 입력이 크게 저평가되어 있다는 사실이 드러났습니다. 그런 호출로 채운 블록은 가스가 시사하는 것보다 훨씬 오래 실행될 수 있습니다.\n\n이것이 중요한 이유는, 블록 가스 한도는 *모든* 연산의 최악의 경우가 시간 예산 안에 들어올 때만 안전하게 올릴 수 있기 때문입니다. EIP-7883은 `ModExp`의 가격을 다시 책정해 가스 한도 확장의 병목 중 하나가 되지 않도록 합니다.\n\n## 어떻게 동작하나요?\n\n인터페이스와 연산은 그대로이고 가스 공식만 바뀝니다. EIP-2565 공식에 세 가지 조정이 가해집니다.\n\n1. **더 높은 하한과 3으로 나누기 폐지.** `max(200, complexity * iterations / 3)`이 `max(500, complexity * iterations)`가 됩니다. 최솟값은 200 가스에서 500 가스로 오르고 일반 비용은 3배가 됩니다.\n2. **큰 지수는 비용이 더 듭니다.** 32바이트보다 긴 지수의 경우, 바이트가 하나 늘 때마다 반복이 8회가 아니라 16회 추가됩니다.\n3. **최소 피연산자 크기와 더 가파른 증가.** 곱셈 복잡도는 최소 16(피연산자가 32바이트인 것처럼)이고, 32바이트를 넘으면 `words²`가 아니라 `2 * words²`입니다(`words = ceil(max(base_len, mod_len) / 8)`).\n\n```python\ndef multiplication_complexity(base_len, mod_len):\n    max_len = max(base_len, mod_len)\n    words = math.ceil(max_len / 8)\n    return 16 if max_len \u003c= 32 else 2 * words**2\n\ndef iteration_count(exp_len, exp):\n    if exp_len \u003c= 32 and exp == 0: n = 0\n    elif exp_len \u003c= 32:            n = exp.bit_length() - 1\n    else: n = 16 * (exp_len - 32) + ((exp \u0026 (2**256 - 1)).bit_length() - 1)\n    return max(n, 1)\n\ndef gas(base_len, mod_len, exp_len, exp):\n    return max(500, multiplication_complexity(base_len, mod_len) * iteration_count(exp_len, exp))\n```\n\n스펙의 분석에 따르면 과거 호출의 약 99.7 %는 200에서 500으로의 하한 상향이나 3배 증가 중 하나를 겪습니다. 일부 엣지 케이스의 테스트 벡터는 20배 이상 오릅니다.\n\n## 샘플 코드\n\nSolidity에서 프리컴파일을 호출하는 예입니다. 예전 가격에 맞춰 하드코딩한 가스 지원금은 이제 너무 낮을 수 있으므로 가스를 넉넉히 잡으세요.\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nlibrary ModExp {\n    /// Returns base^exp % mod for 32-byte operands.\n    function modexp(uint256 base, uint256 exp, uint256 mod) internal view returns (uint256 r) {\n        bytes memory input = abi.encodePacked(\n            uint256(32), uint256(32), uint256(32), // lengths of base, exp, mod\n            base, exp, mod\n        );\n        (bool ok, bytes memory out) = address(0x05).staticcall(input);\n        require(ok, \"modexp failed\");\n        r = abi.decode(out, (uint256));\n    }\n}\n```\n\n## 알아둘 점\n\n- 상태: **Final**. 하위 호환이 되지 않는 가스 변경입니다. EIP-2565 가격에 맞춰 조정한 고정 가스 양으로 `0x05`를 호출하는 컨트랙트는 이제 가스가 부족할 수 있습니다.\n- 영향을 받는 주된 사용처는 전형적인 RSA 검증과 큰 수 암호 컨트랙트입니다. 예전 수치를 가정하지 말고 자신의 입력에 대해 가스를 다시 측정하세요.\n- `ModExp` 입력 크기를 제한하는 [EIP-7823](/eip-7823/), 트랜잭션당 가스를 제한하는 [EIP-7825](/eip-7825/)와 함께 논의되는 경우가 많으며, 이 셋이 합쳐져 최악의 경우의 작업량에 상한을 둡니다.\n- 스펙은 남은 위험이 일부 경우를 과대평가하는 것이며, 이는 저평가보다 덜 해롭다고 본다고 밝힙니다.\n"},"zh":{"lang":"zh","tldr":"提高 ModExp 预编译的 gas 价格（最低值从 200 升至 500，一般成本约为原来的三倍，大输入的定价更陡），使其最坏情况不再阻碍提高区块 gas 上限。","tags":["gas","precompile","modexp","repricing","core"],"related":[198,2565,7823,7825],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-7883/","markdown":"## 它解决什么问题？\n\n位于地址 `0x05` 的 `ModExp` 预编译对任意大整数计算 `base^exp mod modulus`（[EIP-198](/eip-198/)）。它的 gas 公式最后一次调整是在 [EIP-2565](/eip-2565/)。后来，跨执行客户端的基准测试显示，一些输入被明显低估了：塞满此类调用的区块，执行时间可能远远超出其 gas 所暗示的水平。\n\n这一点很重要，因为只有当*每个*操作的最坏情况都能落在时间预算之内时，区块 gas 上限才能被安全地提高。EIP-7883 重新定价 `ModExp`，使它不再是扩展 gas 上限的瓶颈之一。\n\n## 它如何运作\n\n接口和算术保持不变，变化的只有 gas 公式。对 EIP-2565 公式做了三处调整：\n\n1. **更高的下限，且不再除以 3。** `max(200, complexity * iterations / 3)` 变为 `max(500, complexity * iterations)`。最低值从 200 gas 升至 500 gas，一般成本变为三倍。\n2. **大指数成本更高。** 对于长度超过 32 字节的指数，每多一个字节增加 16 次迭代，而不是 8 次。\n3. **最小操作数大小与更陡的增长。** 乘法复杂度至少为 16（相当于操作数为 32 字节），超过 32 字节后为 `2 * words²`，而不是 `words²`（其中 `words = ceil(max(base_len, mod_len) / 8)`）。\n\n```python\ndef multiplication_complexity(base_len, mod_len):\n    max_len = max(base_len, mod_len)\n    words = math.ceil(max_len / 8)\n    return 16 if max_len \u003c= 32 else 2 * words**2\n\ndef iteration_count(exp_len, exp):\n    if exp_len \u003c= 32 and exp == 0: n = 0\n    elif exp_len \u003c= 32:            n = exp.bit_length() - 1\n    else: n = 16 * (exp_len - 32) + ((exp \u0026 (2**256 - 1)).bit_length() - 1)\n    return max(n, 1)\n\ndef gas(base_len, mod_len, exp_len, exp):\n    return max(500, multiplication_complexity(base_len, mod_len) * iteration_count(exp_len, exp))\n```\n\n根据规范的分析，大约 99.7 % 的历史调用要么遇到从 200 提到 500 的下限提升，要么遇到三倍增长。一些边缘情况的测试向量会上升 20 倍或更多。\n\n## 示例代码\n\n从 Solidity 调用该预编译；请预留充足的 gas，因为针对旧定价写死的 gas 额度现在可能太低：\n\n```solidity\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nlibrary ModExp {\n    /// Returns base^exp % mod for 32-byte operands.\n    function modexp(uint256 base, uint256 exp, uint256 mod) internal view returns (uint256 r) {\n        bytes memory input = abi.encodePacked(\n            uint256(32), uint256(32), uint256(32), // lengths of base, exp, mod\n            base, exp, mod\n        );\n        (bool ok, bytes memory out) = address(0x05).staticcall(input);\n        require(ok, \"modexp failed\");\n        r = abi.decode(out, (uint256));\n    }\n}\n```\n\n## 需要注意\n\n- 状态：**Final**。这是一次向后不兼容的 gas 变更：以固定 gas 数量调用 `0x05`（该数量是针对 EIP-2565 价格调好的）的合约，现在可能会耗尽 gas。\n- 典型的 RSA 验证和大数密码学合约是受影响的主要使用者；请针对你的输入重新测量 gas，而不要沿用旧数字。\n- 它常与限制 `ModExp` 输入大小的 [EIP-7823](/eip-7823/) 以及限制单笔交易 gas 的 [EIP-7825](/eip-7825/) 一起讨论；三者合起来可约束最坏情况的工作量。\n- 规范指出，剩下的风险是对某些情况定价过高，它认为这比定价过低的危害更小。\n"}},"requiredBy":[7607,8200]}
