---
eip: 1344
label: EIP-1344
title: ChainID opcode
status: Final
type: Standards Track
category: Core
created: 2018-08-22
requires: 155
official: https://eips.ethereum.org/EIPS/eip-1344
source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1344.md
canonical: https://eips.huatuo.xyz/zh/eip-1344/
lang: zh
tldr: 新增 CHAINID 操作码（0x46），让合约可以在运行时读取当前链 ID，把签名绑定到某一条链，从而防止跨链重放。
tags: [opcode, evm, chain-id, signatures, istanbul]
---

# EIP-1344: ChainID opcode

> This EIP adds an opcode that returns the current chain's EIP-155 unique identifier.

**TL;DR:** 新增 CHAINID 操作码（0x46），让合约可以在运行时读取当前链 ID，把签名绑定到某一条链，从而防止跨链重放。

## 它解决什么问题？

[EIP-155](/eip-155/) 把链 ID 放进交易签名，使为某个网络签署的交易无法在另一个网络上重放。自己验证签名的智能合约（元交易、permit、多签、使用 [EIP-712](/eip-712/) 的 L2 方案）没有这样的保护：它们只能在部署时把链 ID 硬编码进去。

硬编码的值在链分叉、其中一方更改 ID 时就会失效，而且也是容易出现人为错误的地方。如果同一个合约和签名者存在于两条链上，为其中一条链生成的签名就可能在另一条链上被重放。

EIP-1344 让合约可以向 EVM 询问它正在哪条链上运行。它随 Istanbul 升级上线。

## 它如何运作

- 新操作码 `CHAINID`，编码为 `0x46`。它没有栈输入，把链 ID 作为 256 位的值压栈。
- 成本：`G_base`（2 gas），与其他简单的环境类操作码同档。
- 该值来自客户端的链配置，即它在交易中接受的 EIP-155 链 ID。即使当前交易是在不带链 ID 的情况下签名的，也会返回该值。

在 Solidity 中，它以 `block.chainid`（0.8.0 及更高版本）暴露，在内联汇编中则是 `chainid()`。

## 示例代码

在运行时计算 EIP-712 域分隔符，并在链 ID 发生变化时重新计算（OpenZeppelin 的 `EIP712` 使用的模式）：

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

contract Domain {
    bytes32 private constant TYPE_HASH = keccak256(
        "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
    );
    bytes32 private immutable _cachedSeparator;
    uint256 private immutable _cachedChainId;

    constructor() {
        _cachedChainId = block.chainid;              // CHAINID opcode
        _cachedSeparator = _build();
    }

    function domainSeparator() public view returns (bytes32) {
        // After a contentious fork the chain ID may differ: rebuild instead of trusting the cache.
        return block.chainid == _cachedChainId ? _cachedSeparator : _build();
    }

    function _build() private view returns (bytes32) {
        return keccak256(abi.encode(
            TYPE_HASH, keccak256("MyApp"), keccak256("1"), block.chainid, address(this)
        ));
    }
}
```

在链下读取同一个值（ethers v6）：

```ts
const { chainId } = await provider.getNetwork(); // bigint, e.g. 1n on mainnet
```

## 需要注意

- 该操作码返回节点所配置的任何链 ID；它不是从交易中推导出来的。
- 规范明确警告，在有争议的分裂之后，链 ID 可能会改变。长期有效的已签名消息在设计时应确保这种变化不会悄悄使它们失效或被重放；永久缓存 ID 正是这个 EIP 想要避免的 bug。
- 由于该值是 256 位的，工具和 RLP 编码在遇到极大的 ID 时可能出问题。[EIP-2294](/eip-2294/) 提议了一个明确的上限。
- 像 [ERC-1271](/eip-1271/) 这样基于合约的签名检查，依赖于把链 ID 包含在被签名的数据中来获得重放保护。


---

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