-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path07_node_rpc.py
More file actions
33 lines (27 loc) · 1.34 KB
/
Copy path07_node_rpc.py
File metadata and controls
33 lines (27 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# SPDX-License-Identifier: MIT
"""07 - Talk to your own node over JSON-RPC.
Set RPC_URL / RPC_USER / RPC_PASS in the environment (or config.py). For a local node
the safest auth is the auto-generated .cookie file: use its `user:pass` contents.
Keep RPC private and never expose it (see testnethub.com/rpc-safety).
RPC_USER=... RPC_PASS=... python 07_node_rpc.py
"""
import requests
from config import RPC_URL, RPC_USER, RPC_PASS
def rpc(method, params=None):
payload = {"jsonrpc": "1.0", "id": "ex", "method": method, "params": params or []}
try:
r = requests.post(RPC_URL, json=payload, auth=(RPC_USER, RPC_PASS), timeout=15)
except requests.exceptions.RequestException:
raise SystemExit(f"could not reach your node at {RPC_URL}. is it running with RPC "
"enabled? see testnethub.com/run-node")
if r.status_code == 401:
raise SystemExit("the node rejected the login: set RPC_USER / RPC_PASS (see testnethub.com/rpc-safety)")
body = r.json()
if body.get("error"):
raise SystemExit(f"the node rejected the call: {body['error']['message']}")
return body["result"]
info = rpc("getblockchaininfo")
print(f"chain : {info['chain']}")
print(f"blocks : {info['blocks']:,}")
print(f"progress : {info['verificationprogress'] * 100:.2f}%")
print(f"new addr : {rpc('getnewaddress')}")