EIP-198 · Final(最终) · Core(核心) · 2017-01-30
EIP-198: Big integer modular exponentiation
在地址 0x05 新增 MODEXP 预编译,可对任意大的整数计算 (base^exp) mod m,使合约能够验证 RSA 签名及其他基于数论的密码学。
它解决什么问题?
许多密码学方案(包括 RSA 签名验证)需要对远大于 256 位的数进行模幂运算。EVM 原生的 EXP 和 MULMOD 只能处理 256 位的字。在 Solidity 中做 2048 位或 4096 位的运算既慢又消耗大量 gas。
EIP-198 增加了一个预编译合约,原生执行大整数模幂运算,其 gas 价格基于计算的实际难度。
它如何运作
该预编译位于地址 0x05。其输入是三个 32 字节的长度字段,后面跟着三个数:
<len(BASE)> <len(EXP)> <len(MOD)> <BASE> <EXP> <MOD>
- 每个长度都是大端序的 32 字节整数,表示后面那个值的字节长度。
- 缺失的输入视为在右侧用零填充,多余的字节会被忽略。
- 输出为
BASE**EXP % MOD,并填充到与MOD相同的字节长度。
最初的 gas 公式结合了两部分。第一部分是基于 max(len(BASE), len(MOD)) 的 mult_complexity 项,用来近似 Karatsuba 乘法。第二部分是"调整后的指数长度"(大致是指数的位长度)除以 GQUADDIVISOR = 20。将成本与指数位数挂钩,可以让 3 和 65537 这类常见的 RSA 指数保持低成本。
规范指出,也可以借助该预编译来做乘法,方法是 a*b = ((a+b)^2 - (a-b)^2) / 4。
示例代码
从 Solidity 调用 MODEXP:
// 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));