#!/usr/bin/env python3
"""Call a Divi regtest node over JSON-RPC with only the standard library.
Usage: python3 regtest_rpc.py [datadir]   (default ~/divi-regtest)
Reads rpcuser/rpcpassword from the node's divi.conf, so no secret is on the command line."""
import base64, json, os, sys, urllib.error, urllib.request

DATADIR = os.path.expanduser(sys.argv[1] if len(sys.argv) > 1 else "~/divi-regtest")
conf = {}
with open(os.path.join(DATADIR, "divi.conf")) as f:
    for line in f:
        if "=" in line and not line.startswith("#"):
            k, v = line.strip().split("=", 1)
            conf[k] = v
URL = f"http://127.0.0.1:{conf.get('rpcport', '51475')}/"
AUTH = base64.b64encode(f"{conf['rpcuser']}:{conf['rpcpassword']}".encode()).decode()

def rpc(method, *params):
    body = json.dumps({"jsonrpc": "1.0", "id": "py", "method": method, "params": list(params)}).encode()
    req = urllib.request.Request(URL, body, {"Authorization": "Basic " + AUTH, "Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req) as r:
            reply = json.load(r)
    except urllib.error.HTTPError as e:     # divid answers errors with HTTP 404/500 and a JSON body
        if e.code == 401:
            raise RuntimeError("401: wrong rpcuser or rpcpassword") from None
        reply = json.load(e)
    if reply.get("error"):
        raise RuntimeError(reply["error"])
    return reply["result"]

print("height before:", rpc("getblockcount"))
addr = rpc("getnewaddress")
txid = rpc("sendtoaddress", addr, 12.5)
print("sent 12.5 to", addr, "txid", txid)
print("confirmations before block:", rpc("gettransaction", txid)["confirmations"])
rpc("setgenerate", 1)                       # C++ divid only: make one block
print("confirmations after block: ", rpc("gettransaction", txid)["confirmations"])
print("height after: ", rpc("getblockcount"))

try:
    rpc("sendtoaddress", "notanaddress", 1)
except RuntimeError as e:
    print("bad address refused:", e)
