2

如何使用 geth 或 nodejs 或任何其他语言从正在运行的以太坊节点获取块信息?例如,要从比特币获取块数据,有一个配置文件在确认交易时运行 blocknotify.sh 文件,并且在该 blocknotify.sh 文件中有以下命令:bitcoin-cli getblock "$@" >> "$@.json"获取块数据然后我可以发送帖子将该块数据请求到 api。所以我想做同样的事情,即从 ETH 节点获取块数据,并在确认交易时向 api 发送发布请求。我怎样才能做到这一点 ?

4

1 回答 1

5

在运行时geth console,您可以使用 web3 库来获取块信息:

> var blockNumber;

undefined
> var blockInfo;

undefined

> web3.eth.getBlockNumber(function(e, r) { blockNumber = r; });

undefined
> blockNumber;

2515149
> web3.eth.getBlock(blockNumber, function(e, r) { blockInfo = r; });

undefined
> blockInfo

{   difficulty: 1319089762,    extraData: "0xd58301070d8650617269747986312e32332e30826c69",    gasLimit: 4700036,  gasUsed: 0,    hash: "0xf9c495b5e5bcd3935aa4a6fd5a43009de29ca7d7be77d4b7cc4c68b8704bc422",  logsBloom: "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", miner: "0x94cd009bbba97f30a36845e2025edf7544d62439",    mixHash: "0xb8794a6d1b777f8c6fdf509f04896642f67dab82dc872ae9cbe9bcbf85172972",  nonce: "0x264c013815697c2f",    number: 2515149,    parentHash: "0x0d2b4185aec34d8963b4c0b8fa7abb8604e1452bcb7f7f7d7a75a3d1cfd85f92",  receiptsRoot: "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",  sha3Uncles: "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",  size: 537,    stateRoot: "0xc3810c2e763669a6e0219c78990c92b91c634d23810f4bd67144c4d76b9cfe6e",  timestamp: 1516811780,    totalDifficulty: 7642933628775356,    transactions: [],    transactionsRoot: "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",  uncles: []  }

web3 文档可以在这里找到:v0.2x.x , v1.0

编辑 - 交易信息检索示例:

> web3.eth.getTransaction('0xaebaf7e8207c417f6bb7920f3820e5220738d6825b6f577e3c3d0736d3c95b49', function(e, r) { if (e) console.log(e); else res = r; });

undefined
> res

{   blockHash: "0x0000000000000000000000000000000000000000000000000000000000000000",  blockNumber: null,   from: "0x0a78c28257b40d5076ea180bc6a9e4c597c5ea98",   gas: 90000,   gasPrice: 40000000000,   hash: "0xaebaf7e8207c417f6bb7920f3820e5220738d6825b6f577e3c3d0736d3c95b49",  input: "0x",   nonce: 32,   r: "0x902f7a7b7c3e4ebcab47014f9c3b81858cdc4b90ef36d9630adaf30b47ec370f",  s: "0x6f09e7d66dc2146afa108322f433c12b629eadd149e1e113669b6bd2e0cd467e",  to: "0xb8ac544e818d01a9533c9556d572d8366b91d6c1",   transactionIndex: 0,   v: "0x2a",   value: 200000 }
于 2018-01-30T18:38:17.460 回答