[Ethereum] Find out latest block hash in Ethereum using JSON-RPC

blockchainexplorersjson-rpcphp

I am developing an ethereum block explorer in PHP and have established an JSON-RPC communication with my server geth node successfully. Nevertheless, I am kind of stuck when trying to find out the last block in ethereum. I have read the great info at https://ethereum.gitbooks.io/frontier-guide/content/rpc.html but I don't find there any way to ask the ethereum node which one is the last block. Once I had the block hash I see there are endpoints to retrieve full information about the block, but I don't know how to find the latest block hash.

The API endpoint eth_blockNumber is supposed to return the latest block number, but how do I get the hash?

Any help? Thanks in advance!

Best Answer

request:

curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["latest", false],"id":1}' localhost:8545

response:

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "difficulty": "0x31962a3fc82b",
    "extraData": "0x4477617266506f6f6c",
    "gasLimit": "0x47c3d8",
    "gasUsed": "0x0",
    "hash": "0x78bfef68fccd4507f9f4804ba5c65eb2f928ea45b3383ade88aaa720f1209cba",
    "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
    "miner": "0x2a65aca4d5fc5b5c859090a6c34d164135398226",
    "nonce": "0xa5e8fb780cc2cd5e",
    "number": "0x1e655a",
    "parentHash": "0x8b535592eb3192017a527bbf8e3596da86b3abea51d6257898b2ced9d3a83826",
    "receiptRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
    "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
    "size": "0x20e",
    "stateRoot": "0xdc6ed0a382e50edfedb6bd296892690eb97eb3fc88fd55088d5ea753c48253dc",
    "timestamp": "0x579f4981",
    "totalDifficulty": "0x25cff06a0d96f4bee",
    "transactions": [

    ],
    "transactionsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
    "uncles": [

    ]
  }
}

(I've formatted the results for easier reading).

I've used "latest" to find the latest block. You could also use the result from your eth_blockNumber call.

Source: JSON-RPC - eth_getBlockByNumber.

Related Topic