---
eip: 2565
label: EIP-2565
title: ModExp Gas Cost
status: Final
type: Standards Track
category: Core
created: 2020-03-20
requires: 198
official: https://eips.ethereum.org/EIPS/eip-2565
source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2565.md
canonical: https://eips.huatuo.xyz/zh/eip-2565/
lang: zh
tldr: 用更简单、基于基准测试的公式取代了 ModExp 预编译（0x05）的 gas 公式，使大整数模幂运算便宜了许多，并设有 200 gas 的下限。
tags: [precompile, gas, cryptography, core, berlin]
---

# EIP-2565: ModExp Gas Cost

> Defines the gas cost of the ModExp (0x00..05) precompile.

**TL;DR:** 用更简单、基于基准测试的公式取代了 ModExp 预编译（0x05）的 gas 公式，使大整数模幂运算便宜了许多，并设有 200 gas 的下限。

## 它解决什么问题？

[EIP-198](/eip-198/) 在地址 `0x05` 添加了 ModExp 预编译，用于对任意大小的整数计算 `base^exp mod modulus`。它是 RSA 签名验证、VDF、累加器以及部分 SNARK 验证器的基础构件。

基准测试表明，与其他预编译相比，ModExp 定价过高，而且 EIP-198 的复杂度公式（以 Karatsuba 乘法为模型）并不能很好地反映实际执行时间。ERC-2565 修改了定价，使这些运算在链上变得可行。它随 Berlin 升级上线。

## 它如何运作

接口和算术保持不变，只有 gas 变化。成本是"一次乘法有多难"乘以"幂运算需要多少步"，再除以 3：

1. **乘法复杂度**：取 base 和 modulus 字节长度中较大者，转换为 8 字节的字（向上取整），然后平方。
2. **迭代次数**：大致为指数的位长减一。对于超过 32 字节的指数，32 字节之后每多一个字节加 8，再加上低 256 位的位长。最小为 1。
3. **Gas** = `max(200, floor(complexity * iterations / 3))`。

因此，旧的除数（EIP-198 中 `GQUADDIVISOR` 为 20）变成了 3，200 gas 的下限则避免极小输入被定价过低。

```python
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：

```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
        );
        bool ok;
        (ok, result) = address(0x05).staticcall(input);
        require(ok, "modexp failed");
        // result has the same length as `mod`
    }
}
```

## 需要注意

- 状态为 **Final**，自 Berlin 起生效。
- 规范将主要风险指为 ModExp 变得过于便宜，从而打开 DoS 攻击面。后续工作重新审视了这一点：[EIP-7883](/eip-7883/) 再次提高 ModExp 成本，[EIP-7823](/eip-7823/) 对输入大小设置上限。在硬编码 gas 之前，请确认目标分叉适用哪种定价。
- 成本主要由输入的长度而非数值决定，因此请传入最短长度的字节串。
- [EIP-2666](/eip-2666/) 是一项更广泛的预编译重新定价提案，它假定本变更已经生效。


---

This is an unofficial plain-language summary. Read the full specification: https://eips.ethereum.org/EIPS/eip-2565
