EIP-198 · Final · Core · 2017-01-30
EIP-198: Big integer modular exponentiation
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.
What problem does it solve?
Many 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.
EIP-198 adds a precompiled contract that does big-integer modular exponentiation natively, at a gas price based on how hard the computation really is.
How it works
The precompile lives at address 0x05. Its input is three 32-byte length fields followed by the three numbers:
<len(BASE)> <len(EXP)> <len(MOD)> <BASE> <EXP> <MOD>
- Each length is a big-endian 32-byte integer giving the byte length of the next value.
- Missing input is treated as zero-padded on the right, and extra bytes are ignored.
- The output is
BASE**EXP % MOD, padded to the same byte length asMOD.
The 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.
The spec notes that multiplication can also go through this precompile, using a*b = ((a+b)^2 - (a-b)^2) / 4.
Sample code
Calling MODEXP from Solidity:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
library ModExp {
function modexp(bytes memory base, bytes memory exp, bytes memory mod)
internal view returns (bytes memory result)
{
bytes memory input = abi.encodePacked(
uint256(base.length), uint256(exp.length), uint256(mod.length),
base, exp, mod
);
result = new bytes(mod.length);
bool ok;
assembly {
ok := staticcall(gas(), 0x05, add(input, 32), mload(input),
add(result, 32), mload(mod))
}
require(ok, "modexp failed");
}
}
// Example: 3^65535 mod 2^255
// ModExp.modexp(hex"03", hex"ffff", abi.encodePacked(uint256(1) << 255));
Things to know
- This proposal is Final. It went live in the Byzantium upgrade (EIP-609) in 2017.
- The gas formula in this EIP is no longer current. EIP-2565 repriced MODEXP in the Berlin upgrade, and EIP-7883 raised the price again. EIP-7823 caps each input length at 1,024 bytes. Use current client behavior, not this EIP's formula, to estimate gas.
- A zero length for
BASEmeans no bytes are read for it. The next bytes are read as the exponent. Encode lengths carefully. - The output is always as long as the modulus, with leading zeros, so compare results as fixed-length byte strings.