---
eip: 7823
label: EIP-7823
title: Set upper bounds for MODEXP
status: Final
type: Standards Track
category: Core
created: 2024-11-11
requires: 198
official: https://eips.ethereum.org/EIPS/eip-7823
source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-7823.md
canonical: https://eips.huatuo.xyz/zh/eip-7823/
lang: zh
tldr: 把 MODEXP 预编译的每个长度字段限制在 1024 字节（8192 位）以内，消除曾多次引发共识 bug 的无界输入空间。
tags: [precompile, modexp, cryptography, evm, core, fusaka]
---

# EIP-7823: Set upper bounds for MODEXP

> Each input field is restricted to a maximum of 8192 bits

**TL;DR:** 把 MODEXP 预编译的每个长度字段限制在 1024 字节（8192 位）以内，消除曾多次引发共识 bug 的无界输入空间。

## 它解决什么问题？

位于地址 `0x05` 的 MODEXP 预编译由 [EIP-198](/eip-198/) 引入，用来对任意大的数计算 `base ** exponent % modulus`。问题就在于"任意大"：每个操作数的长度都在输入中声明，而且没有上限，所以客户端团队必须处理并测试一个实际上无限的输入空间。MODEXP 一直是大量共识 bug 的来源，其中许多是由刻意构造的、古怪且长得不切实际的输入触发的。由于大小没有上限，它的 gas 定价也很复杂。

实际使用的范围要小得多。规范中的一项链上分析覆盖了从 Byzantium（2018 年 4 月）到 2025 年 1 月的区块，发现没有任何一次成功调用使用过超过 513 字节的输入；几乎都是 32、128 或 256 字节。

## 它如何运作

EIP-198 的输入格式保持不变：

```
<length_of_BASE> <length_of_EXPONENT> <length_of_MODULUS> <BASE> <EXPONENT> <MODULUS>
```

新规则是：三个长度都必须 **≤ 1024 字节（8192 位）**。如果任何一个长度超过这个值，预编译就会失败，返回错误，并耗尽提供给它的全部 gas。

为什么是 8192 位？因为它仍然涵盖所有实际用途：

- 密钥最长 8192 位的 RSA 签名验证（常见的是 1024/2048/4096）。
- 椭圆曲线运算，通常最多需要 384 位。

输入有界之后，将来用普通 EVM 代码（例如使用 EVMMAX 风格的指令）取代该预编译，并为常见大小提供快速路径，也会更加现实。

## 示例代码

在 Solidity 中调用 MODEXP，并加入与新限制一致的检查：

```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

library ModExp {
    uint256 constant MAX_LEN = 1024; // EIP-7823 limit, in bytes

    function modexp(bytes memory b, bytes memory e, bytes memory m)
        internal view returns (bytes memory result)
    {
        require(b.length <= MAX_LEN && e.length <= MAX_LEN && m.length <= MAX_LEN, "too long");
        bytes memory input = abi.encodePacked(
            uint256(b.length), uint256(e.length), uint256(m.length), b, e, m
        );
        result = new bytes(m.length);
        bool ok;
        assembly {
            ok := staticcall(gas(), 0x05, add(input, 32), mload(input),
                             add(result, 32), mload(m))
        }
        require(ok, "modexp failed");
    }
}
```

## 需要注意

- **状态：Final**，已包含在 Fusaka 升级（[EIP-7607](/eip-7607/)）中。
- 从技术上说不向后兼容，但规范的分析没有发现过去有任何交易的行为会因此不同。
- 该限制针对的是声明的长度，而不仅是实际提供的字节，所以即使数据很短，过长的长度头也会失败。
- 本 EIP 没有改变定价公式；MODEXP 的重新定价另行处理（早先的重新定价见 [EIP-2565](/eip-2565/)）。


---

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