You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Geth/Node.js等从以太坊节点获取区块数据并推送至API

如何用Geth获取以太坊区块数据 + 实现交易确认时自动推送API

我来一步步帮你解决这两个问题——先从基础的Geth获取区块数据说起,再搞定交易确认时自动推送的需求,完全对标你提到的比特币blocknotify逻辑。


1. 使用Geth获取以太坊区块数据

你可以通过两种方式用Geth调取区块数据:命令行直接执行,或者进入Geth交互式控制台操作。

方式一:命令行直接调用

如果你想快速获取某个区块的数据并保存到文件,可以直接在终端运行:

# 获取最新区块数据并输出到控制台
geth attach http://localhost:8545 --exec "eth.getBlock('latest')"

# 获取指定区块号的完整数据(比如区块18000000),并保存为格式化的JSON文件
geth attach http://localhost:8545 --exec "JSON.stringify(eth.getBlock(18000000), null, 2)" > block_18000000.json

# 也可以通过区块哈希获取
geth attach http://localhost:8545 --exec "eth.getBlock('0x123456...')"

参数说明:

  • http://localhost:8545 是你的Geth节点RPC地址(默认端口8545)
  • 'latest' 可以替换为区块号、区块哈希,或者'pending'(待打包区块)
  • JSON.stringify(..., null, 2) 是为了格式化输出JSON,方便阅读

方式二:Geth交互式控制台

如果需要多次操作或者调试,进入控制台更方便:

# 连接到本地Geth节点的控制台
geth attach http://localhost:8545

进入控制台后,执行以下命令获取数据:

// 获取最新区块
eth.getBlock('latest')

// 格式化输出带交易详情的区块数据(第二个参数true表示返回交易明细)
JSON.stringify(eth.getBlock('latest', true), null, 2)

2. 实现交易确认时自动获取区块并推送API

以太坊生态里没有和比特币blocknotify完全一样的原生参数,但有几种等价的实现方式,既能监听新区块,也能针对交易确认逻辑做定制。

方法一:用Geth的--posthook参数+Shell脚本(最接近比特币blocknotify)

Geth的--posthook参数可以在每个区块导入节点后自动执行指定脚本,你可以用它来获取区块数据并推送到API。

步骤1:启动Geth时配置posthook

启动全节点时添加--posthook参数(必须是全节点,轻节点无法获取完整区块数据):

geth --syncmode full --http --http.addr 0.0.0.0 --posthook "/path/to/your/block_handler.sh %d"

这里的%d会被Geth自动替换为当前导入的区块号。

步骤2:编写Shell脚本block_handler.sh

#!/bin/bash
# 获取Geth传入的区块号
BLOCK_NUM=$1

# 调用Geth获取区块的JSON数据(包含交易详情)
BLOCK_DATA=$(geth attach http://localhost:8545 --exec "JSON.stringify(eth.getBlock($BLOCK_NUM, true))")

# 推送区块数据到你的API
curl -X POST \
  -H "Content-Type: application/json" \
  -d "$BLOCK_DATA" \
  https://your-api-endpoint.com/receive-block

# 可选:记录日志
echo "[$(date)] Pushed block $BLOCK_NUM to API" >> /var/log/eth_block_push.log

给脚本添加执行权限:

chmod +x /path/to/your/block_handler.sh

注意:这个方法会在每个新区块导入时触发,如果你的需求是仅当特定交易确认后才推送,可以在脚本里加判断逻辑——比如先检查区块内是否包含目标交易哈希,或者后续通过API查询交易的确认数。

方法二:用Node.js+Web3.js定制监听逻辑(更灵活)

如果需要更精细的控制(比如等待交易达到6个确认再推送,或者只处理包含特定地址的交易),用Node.js结合Web3.js是最佳选择。

步骤1:安装依赖

npm install web3 node-fetch

步骤2:编写监听脚本block_monitor.js

const Web3 = require('web3');
const fetch = require('node-fetch');

// 连接到本地Geth节点的RPC接口
const web3 = new Web3('http://localhost:8545');

// 替换为你要监控的目标交易哈希(或者地址)
const TARGET_TX_HASH = '0xabcdef123456...';
const API_ENDPOINT = 'https://your-api-endpoint.com/receive-block';
const REQUIRED_CONFIRMATIONS = 6; // 要求的确认数

// 订阅新区块头部事件
const subscription = web3.eth.subscribe('newBlockHeaders', async (error, result) => {
  if (error) {
    console.error('订阅新区块出错:', error);
    return;
  }

  const currentBlockNumber = result.number;
  console.log(`收到新区块: ${currentBlockNumber}`);

  // 获取完整区块数据(包含交易详情)
  try {
    const block = await web3.eth.getBlock(currentBlockNumber, true);
    
    // 检查区块内是否包含目标交易
    const targetTx = block.transactions.find(tx => tx.hash === TARGET_TX_HASH);
    if (targetTx) {
      // 计算交易确认数
      const latestBlockNumber = await web3.eth.getBlockNumber();
      const confirmations = latestBlockNumber - currentBlockNumber + 1;

      if (confirmations >= REQUIRED_CONFIRMATIONS) {
        // 推送区块数据到API
        await fetch(API_ENDPOINT, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(block)
        });
        console.log(`目标交易已确认(${confirmations}次),已推送区块 ${currentBlockNumber} 到API`);
        // 可选:推送完成后取消订阅
        // subscription.unsubscribe();
      }
    }

    // 如果不需要过滤交易,直接推送所有区块数据
    // await fetch(API_ENDPOINT, {
    //   method: 'POST',
    //   headers: { 'Content-Type': 'application/json' },
    //   body: JSON.stringify(block)
    // });
  } catch (err) {
    console.error('处理区块出错:', err);
  }
});

console.log('区块监控脚本已启动,等待新区块...');

步骤3:运行脚本

node block_monitor.js

这个脚本会一直后台运行,实时监听新区块,一旦满足条件就自动推送数据。

方法三:用Python+Web3.py实现

如果你更熟悉Python,用Web3.py也能实现同样的逻辑:

步骤1:安装依赖

pip install web3 requests

步骤2:编写脚本block_monitor.py

from web3 import Web3
import requests
import time

# 连接本地Geth节点
w3 = Web3(Web3.HTTPProvider('http://localhost:8545'))

# 配置参数
TARGET_TX_HASH = '0xabcdef123456...'
API_ENDPOINT = 'https://your-api-endpoint.com/receive-block'
REQUIRED_CONFIRMATIONS = 6

def handle_new_block(block_header):
    try:
        block_number = block_header['number']
        print(f"收到新区块: {block_number}")

        # 获取带交易详情的完整区块
        block = w3.eth.get_block(block_number, full_transactions=True)
        
        # 转换为可序列化的字典(Web3.py的Block对象有不可直接序列化的属性)
        block_dict = dict(block)
        block_dict['transactions'] = [dict(tx) for tx in block_dict['transactions']]

        # 检查目标交易是否在区块内
        target_tx = next((tx for tx in block_dict['transactions'] if tx['hash'] == TARGET_TX_HASH), None)
        if target_tx:
            # 计算确认数
            latest_block = w3.eth.block_number
            confirmations = latest_block - block_number + 1

            if confirmations >= REQUIRED_CONFIRMATIONS:
                # 推送API
                response = requests.post(
                    API_ENDPOINT,
                    json=block_dict,
                    headers={'Content-Type': 'application/json'}
                )
                response.raise_for_status()
                print(f"目标交易已确认({confirmations}次),推送区块 {block_number} 成功")

        # 直接推送所有区块的话,取消下面的注释
        # response = requests.post(API_ENDPOINT, json=block_dict, headers={'Content-Type': 'application/json'})
        # response.raise_for_status()
        # print(f"推送区块 {block_number} 成功")

    except Exception as e:
        print(f"处理区块出错: {str(e)}")

# 订阅新区块事件
subscription = w3.eth.subscribe('new_block_headers', handle_new_block)

print("区块监控脚本已启动...")
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    subscription.unsubscribe()
    print("监控脚本已停止")

一些关键注意事项

  • 必须用全节点:轻节点(--syncmode light)无法获取完整的区块交易数据,所以一定要配置--syncmode full启动Geth。
  • RPC权限:确保Geth节点开启了RPC接口(启动时加--http参数),并且允许本地脚本访问(默认--http.addr 127.0.0.1,如果脚本在其他机器运行,改成0.0.0.0并配置--http.corsdomain)。
  • 错误处理:实际部署时,建议给脚本添加重连逻辑、失败重试机制,避免因节点临时断开导致数据丢失。

内容的提问来源于stack exchange,提问作者Farhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:37:03