2

I am trying to request a block hash for a specific block using the Polkadot JSON-RPC but no matter how I construct the request (with Python), it always returns the latest block and not the one I want. How can I solve that?

import requests

import json

def get_block_hash(block_number):

  url = "https://dot.getblock.io/mainnet/"

  payload = json.dumps({

    "jsonrpc": "2.0",

    "method": "chain_getBlockHash",

    "id": 1

  })

  headers = {
    'x-api-key': 'enter-api-key',
    'blockNumber': block_number,
    'Content-Type': 'application/json'
  }

  response = requests.request("POST", url, headers=headers, data=payload)

  print(response.text)

  return response

3 Answers 3

5

The JSON-RPC 2.0 parameters doesn't go in the header, they are part of the body. Here is a correctly-formatted body for a getBlockHash query -

{
  "id":1,
  "jsonrpc":"2.0",
  "method":"chain_getBlockHash",
  "params":[123456]
}

The params above contain the blocknumber, 123456 in this case.

1
import json
# pip3 install websocket-client
import websocket

uri = 'wss://rpc.polkadot.io'
ws = websocket.create_connection(uri)

for block_number in range(11627380, 0, -1):
    print(block_number)

    data = f'{{\
        "jsonrpc": "2.0",\
        "id": 1,\
        "method": "chain_getBlockHash",\
        "params": [{block_number}]\
    }}'

    ws.send(data)

    block_hash = json.loads(ws.recv())['result']

    print(block_hash)
11627380
0x6d4d9db750b8b25c3a8b924c7a9987f4dfebc4f64d981d27f5ebfbcc36dc2acc
11627379
0x83f433b3cb100e41f4028849e1299632d8d3a9eb92c0429de68cd3345c22544f
11627378
0x98feb884664c370090bbabf8d43f6cf1d580cf99bed392b3b45173456e93e237
11627377
0x01810c5483943974e1c00fed4f49bf0ac057d131f2842566289b0f417d6e8bfd
11627376
0xd1ccb8a533a37db43947aa6bf3c854eded35558309d0e888356819bac6a6fcab
11627375
0xa9ded33c03d0f7ba435ed7ddc528fb3a4bbb1486ac7fdad41f3adb9c68cc656c
11627374
0x41d2512fcdd9fec34e97a5d931dbdff3144cd900fd5ef94b9f070b5abcd947a6
0

You can also have a look at https://github.com/polkascan/py-substrate-interface if you want more complex interaction with the RPC

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.