EIP-2565 · Final(最终) · Core(核心) · 2020-03-20
EIP-2565: ModExp Gas Cost
用更简单、基于基准测试的公式取代了 ModExp 预编译(0x05)的 gas 公式,使大整数模幂运算便宜了许多,并设有 200 gas 的下限。
它解决什么问题?
EIP-198 在地址 0x05 添加了 ModExp 预编译,用于对任意大小的整数计算 base^exp mod modulus。它是 RSA 签名验证、VDF、累加器以及部分 SNARK 验证器的基础构件。
基准测试表明,与其他预编译相比,ModExp 定价过高,而且 EIP-198 的复杂度公式(以 Karatsuba 乘法为模型)并不能很好地反映实际执行时间。ERC-2565 修改了定价,使这些运算在链上变得可行。它随 Berlin 升级上线。
它如何运作
接口和算术保持不变,只有 gas 变化。成本是"一次乘法有多难"乘以"幂运算需要多少步",再除以 3:
- 乘法复杂度:取 base 和 modulus 字节长度中较大者,转换为 8 字节的字(向上取整),然后平方。
- 迭代次数:大致为指数的位长减一。对于超过 32 字节的指数,32 字节之后每多一个字节加 8,再加上低 256 位的位长。最小为 1。
- Gas =
max(200, floor(complexity * iterations / 3))。
因此,旧的除数(EIP-198 中 GQUADDIVISOR 为 20)变成了 3,200 gas 的下限则避免极小输入被定价过低。
def gas(base_len, mod_len, exp_len, exponent):
words = math.ceil(max(base_len, mod_len) / 8)
complexity = words ** 2
if exp_len <= 32 and exponent == 0:
iters = 0
elif exp_len <= 32:
iters = exponent.bit_length() - 1
else:
iters = 8 * (exp_len - 32) + ((exponent & (2**256 - 1)).bit_length() - 1)
return max(200, complexity * max(iters, 1) // 3)
来自规范测试表:modexp_nagydani_1_pow0x10001 从 3276 降到 341 gas,modexp_nagydani_5_pow0x10001 从 285900 降到 87381。
示例代码
在 Solidity 中调用该预编译。输入是三个 32 字节的长度,后面依次是 base、exponent 和 modulus:
// 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
);
bool ok;
(ok, result) = address(0x05).staticcall(input);
require(ok, "modexp failed");
// result has the same length as `mod`
}
}