---
eip: 234
label: EIP-234
title: Add `blockHash` to JSON-RPC filter options.
status: Final
type: Standards Track
category: Interface
created: 2017-03-24
requires: 1474
official: https://eips.ethereum.org/EIPS/eip-234
source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-234.md
canonical: https://eips.huatuo.xyz/zh/eip-234/
lang: zh
tldr: 为 eth_getLogs 和 eth_newFilter 增加 blockHash 选项，使应用可以获取某个确切区块的日志，并在链重组时保持正确。
tags: [json-rpc, logs, reorg, interface]
---

# EIP-234: Add `blockHash` to JSON-RPC filter options.

> Add an option to JSON-RPC filter options (used by ethnewFilter and ethgetLogs) that allows specifying the block hash that should be included in the results. This option would be an alternative to fromBlock/toBlock options.

**TL;DR:** 为 eth_getLogs 和 eth_newFilter 增加 blockHash 选项，使应用可以获取某个确切区块的日志，并在链重组时保持正确。

## 它解决什么问题？

钱包、交易所和仪表盘等索引事件的应用，既需要知道日志何时出现，也需要知道重组何时把它们移除。仅靠日志订阅是脆弱的。如果在重组期间 WebSocket 断开或节点重启，你就永远收不到关于日志被移除的通知。

一种稳健的做法是自己跟踪区块，并逐个区块获取日志。但在 EIP-234 之前，`eth_getLogs` 只接受区块**编号**。如果在"我看到了哈希为 0xabc 的区块 #100"和"给我 #100 的日志"之间发生了重组，你可能会在不知情的情况下得到另一个区块 #100 的日志。如果结果为空，你甚至无法判断它来自哪个区块。

## 它如何运作

`eth_getLogs` 和 `eth_newFilter` 的过滤器对象新增一个可选的 `blockHash` 字段：

- 无论该区块是否仍在规范链上，节点都会返回**恰好在该区块内**匹配过滤器的日志。
- 如果节点不认识该哈希，它会返回**错误**，而不是空列表。规范的测试用例使用错误码 `-32000` 和消息 `"Block not found."`。
- `blockHash` 与 `fromBlock` / `toBlock` 互斥。
- `address` 和 `topics` 的过滤照常工作。

现在，空结果真正意味着"这个区块没有匹配的日志"，而错误则意味着"回滚并重新同步"。

## 示例代码

原始 JSON-RPC：

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "eth_getLogs",
  "params": [{
    "blockHash": "0x<32-byte block hash>",
    "address": "0x<contract address>",
    "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]
  }]
}
```

上面的 topic 是 `keccak256("Transfer(address,address,uint256)")`。

使用 ethers v6，为你已经见过的区块获取日志：

```ts
import { JsonRpcProvider, id } from "ethers";

const provider = new JsonRpcProvider(process.env.RPC_URL);

provider.on("block", async (n: number) => {
  const block = await provider.getBlock(n);
  try {
    const logs = await provider.getLogs({
      blockHash: block!.hash!,                     // pin to this exact block
      topics: [id("Transfer(address,address,uint256)")],
    });
    console.log(n, block!.hash, logs.length);
  } catch {
    // block vanished in a reorg: roll back local state and resync
  }
});
```

## 需要注意

- 这个 EIP 的状态是 **Final**，并得到主要客户端的支持。规范把 Geth 列为参考实现。
- 它依赖于 JSON-RPC 规范 EIP [EIP-1474](/eip-1474/)，后者的状态是 Stagnant。规范的 RPC 定义现在位于 `ethereum/execution-apis` 仓库。
- [EIP-1898](/eip-1898/) 把同样的思路应用到 `eth_call` 和 `eth_getBalance` 等状态查询上，让你可以将它们固定到某个区块哈希。
- 可以结合区块的 `logsBloom`，对不可能包含你所关注事件的区块跳过 `eth_getLogs` 调用。


---

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