{"eip":198,"title":"Big integer modular exponentiation","authors":["Vitalik Buterin (@vbuterin)"],"status":"Final","type":"Standards Track","category":"Core","created":"2017-01-30","repo":"EIPs","label":"EIP-198","officialUrl":"https://eips.ethereum.org/EIPS/eip-198","sourceUrl":"https://github.com/ethereum/EIPs/blob/master/EIPS/eip-198.md","url":"https://eips.huatuo.xyz/eip-198/","tldr":{"en":"Added the MODEXP precompile at address 0x05, which computes (base^exp) mod m for arbitrarily large integers so contracts can verify RSA signatures and other number-theory cryptography.","ja":"アドレス 0x05 に MODEXP プリコンパイルを追加。任意の大きさの整数で (base^exp) mod m を計算し、コントラクトが RSA 署名やその他の数論ベースの暗号を検証できるようにする。","ko":"주소 0x05에 MODEXP 프리컴파일을 추가해 임의로 큰 정수에 대해 (base^exp) mod m을 계산하고, 컨트랙트가 RSA 서명과 기타 수론 기반 암호를 검증할 수 있게 했다.","zh":"在地址 0x05 新增 MODEXP 预编译，可对任意大的整数计算 (base^exp) mod m，使合约能够验证 RSA 签名及其他基于数论的密码学。"},"tags":["precompile","cryptography","modexp","rsa","byzantium"],"explainers":{"en":{"lang":"en","tldr":"Added the MODEXP precompile at address 0x05, which computes (base^exp) mod m for arbitrarily large integers so contracts can verify RSA signatures and other number-theory cryptography.","tags":["precompile","cryptography","modexp","rsa","byzantium"],"related":[609,2565,7883,7823,196],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/eip-198/","markdown":"## What problem does it solve?\n\nMany cryptographic schemes, including RSA signature verification, need modular exponentiation on numbers much larger than 256 bits. The EVM's native `EXP` and `MULMOD` only work on 256-bit words. Doing 2048-bit or 4096-bit arithmetic in Solidity is slow and costs a lot of gas.\n\nEIP-198 adds a precompiled contract that does big-integer modular exponentiation natively, at a gas price based on how hard the computation really is.\n\n## How it works\n\nThe precompile lives at address `0x05`. Its input is three 32-byte length fields followed by the three numbers:\n\n```\n\u003clen(BASE)\u003e \u003clen(EXP)\u003e \u003clen(MOD)\u003e \u003cBASE\u003e \u003cEXP\u003e \u003cMOD\u003e\n```\n\n- Each length is a big-endian 32-byte integer giving the byte length of the next value.\n- Missing input is treated as zero-padded on the right, and extra bytes are ignored.\n- The output is `BASE**EXP % MOD`, padded to the same byte length as `MOD`.\n\nThe original gas formula combined two things. The first was a `mult_complexity` term based on `max(len(BASE), len(MOD))`, meant to approximate Karatsuba multiplication. The second was an \"adjusted exponent length\", roughly the bit length of the exponent, divided by `GQUADDIVISOR = 20`. Tying the cost to exponent bits keeps common RSA exponents such as 3 and 65537 cheap.\n\nThe spec notes that multiplication can also go through this precompile, using `a*b = ((a+b)^2 - (a-b)^2) / 4`.\n\n## Sample code\n\nCalling MODEXP from Solidity:\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        result = new bytes(mod.length);\n        bool ok;\n        assembly {\n            ok := staticcall(gas(), 0x05, add(input, 32), mload(input),\n                             add(result, 32), mload(mod))\n        }\n        require(ok, \"modexp failed\");\n    }\n}\n\n// Example: 3^65535 mod 2^255\n// ModExp.modexp(hex\"03\", hex\"ffff\", abi.encodePacked(uint256(1) \u003c\u003c 255));\n```\n\n## Things to know\n\n- This proposal is Final. It went live in the Byzantium upgrade ([EIP-609](/eip-609/)) in 2017.\n- The gas formula in this EIP is **no longer current**. [EIP-2565](/eip-2565/) repriced MODEXP in the Berlin upgrade, and [EIP-7883](/eip-7883/) raised the price again. [EIP-7823](/eip-7823/) caps each input length at 1,024 bytes. Use current client behavior, not this EIP's formula, to estimate gas.\n- A zero length for `BASE` means no bytes are read for it. The next bytes are read as the exponent. Encode lengths carefully.\n- The output is always as long as the modulus, with leading zeros, so compare results as fixed-length byte strings.\n"},"ja":{"lang":"ja","tldr":"アドレス 0x05 に MODEXP プリコンパイルを追加。任意の大きさの整数で (base^exp) mod m を計算し、コントラクトが RSA 署名やその他の数論ベースの暗号を検証できるようにする。","tags":["precompile","cryptography","modexp","rsa","byzantium"],"related":[609,2565,7883,7823,196],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ja/eip-198/","markdown":"## 何を解決するのか\n\nRSA 署名検証を含む多くの暗号方式は、256 ビットよりはるかに大きな数に対するべき乗剰余を必要とします。EVM ネイティブの `EXP` と `MULMOD` は 256 ビットのワードしか扱えません。2048 ビットや 4096 ビットの演算を Solidity で行うと遅く、ガスも大量に消費します。\n\nEIP-198 は、巨大整数のべき乗剰余をネイティブに実行するプリコンパイル済みコントラクトを追加し、計算の実際の難しさに応じたガス価格を設定します。\n\n## 仕組み\n\nプリコンパイルはアドレス `0x05` にあります。入力は 3 つの 32 バイト長フィールドと、それに続く 3 つの数です。\n\n```\n\u003clen(BASE)\u003e \u003clen(EXP)\u003e \u003clen(MOD)\u003e \u003cBASE\u003e \u003cEXP\u003e \u003cMOD\u003e\n```\n\n- 各長さは、次の値のバイト長を表すビッグエンディアンの 32 バイト整数です。\n- 不足している入力は右側がゼロパディングされたものとして扱われ、余分なバイトは無視されます。\n- 出力は `BASE**EXP % MOD` で、`MOD` と同じバイト長にパディングされます。\n\n当初のガス計算式は 2 つの要素を組み合わせたものでした。1 つ目は `max(len(BASE), len(MOD))` に基づく `mult_complexity` 項で、Karatsuba 乗算の近似を意図したものです。2 つ目は「調整済み指数長」（おおよそ指数のビット長）を `GQUADDIVISOR = 20` で割ったものです。コストを指数のビット数に結び付けることで、3 や 65537 といった一般的な RSA の指数は安価に保たれます。\n\n仕様には、`a*b = ((a+b)^2 - (a-b)^2) / 4` を使えば、このプリコンパイル経由で乗算もできると書かれています。\n\n## サンプルコード\n\nSolidity から MODEXP を呼び出す:\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        result = new bytes(mod.length);\n        bool ok;\n        assembly {\n            ok := staticcall(gas(), 0x05, add(input, 32), mload(input),\n                             add(result, 32), mload(mod))\n        }\n        require(ok, \"modexp failed\");\n    }\n}\n\n// Example: 3^65535 mod 2^255\n// ModExp.modexp(hex\"03\", hex\"ffff\", abi.encodePacked(uint256(1) \u003c\u003c 255));\n```\n\n## 知っておくべきこと\n\n- この提案は Final です。2017 年の Byzantium アップグレード（[EIP-609](/eip-609/)）で本番稼働しました。\n- この EIP のガス計算式は**もう現行のものではありません**。[EIP-2565](/eip-2565/) が Berlin アップグレードで MODEXP の価格を見直し、[EIP-7883](/eip-7883/) が再び引き上げました。[EIP-7823](/eip-7823/) は各入力の長さを 1,024 バイトに制限します。ガスを見積もるときは、この EIP の計算式ではなく現行クライアントの挙動を使ってください。\n- `BASE` の長さがゼロの場合、`BASE` のためのバイトは読み取られません。次のバイトが指数として読み取られます。長さのエンコードには注意してください。\n- 出力は常に法と同じ長さで、先頭にゼロが付くため、結果は固定長のバイト列として比較してください。\n"},"ko":{"lang":"ko","tldr":"주소 0x05에 MODEXP 프리컴파일을 추가해 임의로 큰 정수에 대해 (base^exp) mod m을 계산하고, 컨트랙트가 RSA 서명과 기타 수론 기반 암호를 검증할 수 있게 했다.","tags":["precompile","cryptography","modexp","rsa","byzantium"],"related":[609,2565,7883,7823,196],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/ko/eip-198/","markdown":"## 어떤 문제를 해결하나요?\n\nRSA 서명 검증을 포함한 많은 암호 방식은 256비트보다 훨씬 큰 수에 대한 모듈러 거듭제곱이 필요합니다. EVM의 기본 `EXP`와 `MULMOD`는 256비트 워드에서만 동작합니다. Solidity로 2048비트나 4096비트 연산을 하면 느리고 가스도 많이 듭니다.\n\nEIP-198은 큰 정수의 모듈러 거듭제곱을 네이티브로 수행하는 프리컴파일 컨트랙트를 추가하고, 실제 계산의 난이도에 따라 가스 가격을 매깁니다.\n\n## 어떻게 동작하나요?\n\n프리컴파일은 주소 `0x05`에 있습니다. 입력은 32바이트 길이 필드 세 개와 그 뒤에 오는 세 개의 수입니다.\n\n```\n\u003clen(BASE)\u003e \u003clen(EXP)\u003e \u003clen(MOD)\u003e \u003cBASE\u003e \u003cEXP\u003e \u003cMOD\u003e\n```\n\n- 각 길이는 다음 값의 바이트 길이를 나타내는 빅 엔디언 32바이트 정수입니다.\n- 부족한 입력은 오른쪽이 0으로 채워진 것으로 취급하며, 남는 바이트는 무시합니다.\n- 출력은 `BASE**EXP % MOD`이며 `MOD`와 같은 바이트 길이로 패딩됩니다.\n\n최초의 가스 공식은 두 가지를 결합한 것이었습니다. 첫째는 `max(len(BASE), len(MOD))`에 기반한 `mult_complexity` 항으로, Karatsuba 곱셈을 근사하려는 것이었습니다. 둘째는 \"조정된 지수 길이\"(대략 지수의 비트 길이)를 `GQUADDIVISOR = 20`으로 나눈 값입니다. 비용을 지수의 비트 수에 연동하면 3이나 65537 같은 일반적인 RSA 지수가 저렴하게 유지됩니다.\n\n명세에 따르면 `a*b = ((a+b)^2 - (a-b)^2) / 4`를 이용해 이 프리컴파일로 곱셈도 할 수 있습니다.\n\n## 샘플 코드\n\nSolidity에서 MODEXP 호출하기:\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        result = new bytes(mod.length);\n        bool ok;\n        assembly {\n            ok := staticcall(gas(), 0x05, add(input, 32), mload(input),\n                             add(result, 32), mload(mod))\n        }\n        require(ok, \"modexp failed\");\n    }\n}\n\n// Example: 3^65535 mod 2^255\n// ModExp.modexp(hex\"03\", hex\"ffff\", abi.encodePacked(uint256(1) \u003c\u003c 255));\n```\n\n## 알아둘 점\n\n- 이 제안은 Final입니다. 2017년 Byzantium 업그레이드([EIP-609](/eip-609/))에서 시작되었습니다.\n- 이 EIP의 가스 공식은 **더 이상 현재 기준이 아닙니다**. [EIP-2565](/eip-2565/)가 Berlin 업그레이드에서 MODEXP 가격을 재조정했고, [EIP-7883](/eip-7883/)이 다시 인상했습니다. [EIP-7823](/eip-7823/)은 각 입력의 길이를 1,024바이트로 제한합니다. 가스를 추정할 때는 이 EIP의 공식이 아니라 현재 클라이언트의 동작을 기준으로 하세요.\n- `BASE`의 길이가 0이면 그에 대해 아무 바이트도 읽지 않습니다. 다음 바이트가 지수로 읽힙니다. 길이를 인코딩할 때 주의하세요.\n- 출력은 항상 모듈러스와 같은 길이이며 앞에 0이 붙으므로, 결과는 고정 길이 바이트 문자열로 비교하세요.\n"},"zh":{"lang":"zh","tldr":"在地址 0x05 新增 MODEXP 预编译，可对任意大的整数计算 (base^exp) mod m，使合约能够验证 RSA 签名及其他基于数论的密码学。","tags":["precompile","cryptography","modexp","rsa","byzantium"],"related":[609,2565,7883,7823,196],"updated":"2026-10-19","url":"https://eips.huatuo.xyz/zh/eip-198/","markdown":"## 它解决什么问题？\n\n许多密码学方案（包括 RSA 签名验证）需要对远大于 256 位的数进行模幂运算。EVM 原生的 `EXP` 和 `MULMOD` 只能处理 256 位的字。在 Solidity 中做 2048 位或 4096 位的运算既慢又消耗大量 gas。\n\nEIP-198 增加了一个预编译合约，原生执行大整数模幂运算，其 gas 价格基于计算的实际难度。\n\n## 它如何运作\n\n该预编译位于地址 `0x05`。其输入是三个 32 字节的长度字段，后面跟着三个数：\n\n```\n\u003clen(BASE)\u003e \u003clen(EXP)\u003e \u003clen(MOD)\u003e \u003cBASE\u003e \u003cEXP\u003e \u003cMOD\u003e\n```\n\n- 每个长度都是大端序的 32 字节整数，表示后面那个值的字节长度。\n- 缺失的输入视为在右侧用零填充，多余的字节会被忽略。\n- 输出为 `BASE**EXP % MOD`，并填充到与 `MOD` 相同的字节长度。\n\n最初的 gas 公式结合了两部分。第一部分是基于 `max(len(BASE), len(MOD))` 的 `mult_complexity` 项，用来近似 Karatsuba 乘法。第二部分是\"调整后的指数长度\"（大致是指数的位长度）除以 `GQUADDIVISOR = 20`。将成本与指数位数挂钩，可以让 3 和 65537 这类常见的 RSA 指数保持低成本。\n\n规范指出，也可以借助该预编译来做乘法，方法是 `a*b = ((a+b)^2 - (a-b)^2) / 4`。\n\n## 示例代码\n\n从 Solidity 调用 MODEXP：\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        result = new bytes(mod.length);\n        bool ok;\n        assembly {\n            ok := staticcall(gas(), 0x05, add(input, 32), mload(input),\n                             add(result, 32), mload(mod))\n        }\n        require(ok, \"modexp failed\");\n    }\n}\n\n// Example: 3^65535 mod 2^255\n// ModExp.modexp(hex\"03\", hex\"ffff\", abi.encodePacked(uint256(1) \u003c\u003c 255));\n```\n\n## 需要注意\n\n- 该提案状态为 Final。它在 2017 年的 Byzantium 升级（[EIP-609](/eip-609/)）中上线。\n- 本 EIP 中的 gas 公式**已不是当前版本**。[EIP-2565](/eip-2565/) 在 Berlin 升级中重新定价了 MODEXP，[EIP-7883](/eip-7883/) 再次提高了价格。[EIP-7823](/eip-7823/) 将每个输入的长度上限设为 1,024 字节。估算 gas 时请以当前客户端行为为准，而不是本 EIP 的公式。\n- `BASE` 的长度为零表示不为它读取任何字节，接下来的字节会被当作指数读取。请谨慎编码长度。\n- 输出的长度始终与模数相同，并带有前导零，因此请将结果作为定长字节串进行比较。\n"}},"requiredBy":[609,2565,3068,7823]}
