---
eip: 155
label: EIP-155
title: Simple replay attack protection
status: Final
type: Standards Track
category: Core
created: 2016-10-14
official: https://eips.ethereum.org/EIPS/eip-155
source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
canonical: https://eips.huatuo.xyz/zh/eip-155/
lang: zh
tldr: 将链 ID 混入每笔交易签名，使为某个以太坊网络签名的交易无法在另一个网络上重放。
tags: [transactions, signatures, chainid, security, core]
---

# EIP-155: Simple replay attack protection

**TL;DR:** 将链 ID 混入每笔交易签名，使为某个以太坊网络签名的交易无法在另一个网络上重放。

## 它解决什么问题？

2016 年 DAO 分叉之后，以太坊和以太坊经典共享相同的历史、地址和交易格式。为一条链签名的交易在另一条链上同样有效，因此任何人都可以把它复制过去并“重放”。在一条链上发送了 ETH 的用户，可能会损失对应的 ETC，反过来也一样。

EIP-155 通过把链 ID 纳入被签名的内容，使签名只对特定链有效。它随 Spurious Dragon 硬分叉（[EIP-607](/eip-607/)）在区块 2,675,000 上线。主网的链 ID 是 `1`。

## 它如何运作

在 EIP-155 之前，传统交易对六个经 RLP 编码的字段进行签名：

```
(nonce, gasprice, startgas, to, value, data)
```

有了 EIP-155，签名者改为对九个字段求哈希：

```
(nonce, gasprice, startgas, to, value, data, chainid, 0, 0)
```

恢复值 `v` 也随之编码了链 ID：

```
v = {0,1} + CHAIN_ID * 2 + 35      # protected
v = {0,1} + 27                     # old, unprotected
```

其中 `{0,1}` 是曲线上点的 y 值的奇偶性。在主网上，受保护签名的 `v` 为 `37` 或 `38`。

当节点看到 `v = CHAIN_ID * 2 + 35` 或 `+ 36` 时，会重建九字段哈希来恢复发送者。为链 1 生成的签名在链 61 上无法恢复出正确的发送者，因此无法重放。旧的 `v = 27/28` 签名在旧规则下依然有效。该方案在协议层面是可选启用的。

## 示例代码

规范中的完整示例：nonce 9、gas 价格 20 gwei、gas 21000，在链 1 上向 `0x3535…3535` 发送 1 ETH。签名载荷以 `018080`（链 ID 1，后跟两个空字段）结尾，得到的签名 `v = 37`。

使用 ethers v6 对传统交易签名。链 ID 会自动写入签名：

```ts
import { Wallet, Transaction, parseUnits, parseEther } from "ethers";

const wallet = new Wallet(process.env.PRIVATE_KEY!);

const signed = await wallet.signTransaction({
  type: 0,                     // legacy transaction
  chainId: 1,                  // EIP-155 chain id
  nonce: 9,
  gasPrice: parseUnits("20", "gwei"),
  gasLimit: 21000,
  to: "0x3535353535353535353535353535353535353535",
  value: parseEther("1"),
});

const tx = Transaction.from(signed);
console.log(tx.chainId, tx.signature!.networkV); // 1n, 37n or 38n
```

## 需要注意

- 类型化交易（[EIP-2718](/eip-2718/) 及之后，包括 EIP-1559 的 type-2）把 `chainId` 作为显式字段，并使用取值为 0 或 1 的普通 `yParity`。`v = chainId * 2 + 35` 这一做法只适用于传统交易。
- 未受保护的（155 之前的）交易在链上依然有效。许多节点配置默认拒绝通过 RPC 接收它们。
- 合约可以用 `CHAINID` opcode（[EIP-1344](/eip-1344/)）读取当前链 ID，钱包可以用 `eth_chainId`（[EIP-695](/eip-695/)）查询。链下签名通过 [EIP-712](/eip-712/) 域使用同一个 ID。
- 链 ID 并非由本 EIP 分配。每个网络自行选择唯一的链 ID，并记录在社区维护的 `ethereum-lists/chains` 注册表中。
- 该 EIP 状态为 Final。


---

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