Files
plm-lottery/plm_engine/regtest.py
T

117 lines
4.7 KiB
Python
Raw Normal View History

"""A handle on a local regtest node, for tests and the dev scripts (ADR-58, roadmap B3). Never used by the site.
The node is the one of `plm-regtest` (palladiumcore in `-regtest`, with plm-fulcrum in front of it). Nothing here
starts it: bring it up with `docker compose up -d` in that folder. Where to find it is configuration, all optional:
* `PLM_REGTEST_RPC_URL` (default `http://127.0.0.1:18332`), with `PLM_REGTEST_RPC_USER` / `PLM_REGTEST_RPC_PASSWORD`,
or else the `rpcuser`/`rpcpassword` of `PLM_REGTEST_CONF` (default `../plm-regtest/node/palladium.conf`);
* `PLM_REGTEST_ELECTRUM` as `host:port` of the plain-TCP Fulcrum port (default `127.0.0.1:50001`).
"""
import base64
import json
import os
import socket
import urllib.error
import urllib.request
from dataclasses import dataclass
from pathlib import Path
DEFAULT_RPC_URL = "http://127.0.0.1:18332"
DEFAULT_ELECTRUM = "127.0.0.1:50001"
DEFAULT_CONF = Path(__file__).resolve().parents[2] / "plm-regtest" / "node" / "palladium.conf"
COINBASE_MATURITY = 100
class RegtestError(Exception):
pass
def _conf_credentials(path: Path) -> tuple[str, str] | None:
try:
lines = path.read_text().splitlines()
except OSError:
return None
values = dict(line.split("=", 1) for line in lines if "=" in line and not line.lstrip().startswith("#"))
if "rpcuser" in values and "rpcpassword" in values:
return values["rpcuser"].strip(), values["rpcpassword"].strip()
return None
@dataclass
class RegtestNode:
url: str
user: str
password: str
@classmethod
def from_environment(cls) -> "RegtestNode":
url = os.environ.get("PLM_REGTEST_RPC_URL", DEFAULT_RPC_URL)
user, password = os.environ.get("PLM_REGTEST_RPC_USER"), os.environ.get("PLM_REGTEST_RPC_PASSWORD")
if not (user and password):
found = _conf_credentials(Path(os.environ.get("PLM_REGTEST_CONF", DEFAULT_CONF)))
if found is None:
raise RegtestError("no RPC credentials: set PLM_REGTEST_RPC_USER and PLM_REGTEST_RPC_PASSWORD")
user, password = found
return cls(url, user, password)
def rpc(self, method: str, *params):
body = json.dumps({"jsonrpc": "1.0", "id": "plm", "method": method, "params": list(params)}).encode()
token = base64.b64encode(f"{self.user}:{self.password}".encode()).decode()
request = urllib.request.Request(self.url, body, {"Content-Type": "text/plain", "Authorization": f"Basic {token}"})
try:
with urllib.request.urlopen(request, timeout=30) as reply:
payload = json.load(reply)
except urllib.error.HTTPError as error: # bitcoind answers 500 with a JSON error body
payload = json.load(error)
except (urllib.error.URLError, OSError) as error:
raise RegtestError(f"the regtest node is not reachable at {self.url}: {error}") from error
if payload.get("error"):
raise RegtestError(f"{method}: {payload['error']}")
return payload["result"]
# -- what a test needs -------------------------------------------------------------------
def info(self) -> dict:
info = self.rpc("getblockchaininfo")
if info["chain"] != "regtest":
raise RegtestError(f"this node is on {info['chain']!r}, not regtest: refusing to touch it")
return info
def height(self) -> int:
return self.info()["blocks"]
def mine(self, blocks: int = 1, address: str | None = None) -> list[str]:
"""Mine `blocks` blocks (to `address`, or to a fresh address of the node's wallet) and return their hashes."""
self.info()
return self.rpc("generatetoaddress", blocks, address or self.rpc("getnewaddress"))
def balance(self) -> float:
return float(self.rpc("getbalance"))
def ensure_funds(self, plm: float) -> None:
"""Make sure the node's wallet can spend `plm`, mining past the coinbase maturity if it cannot."""
self.info()
while self.balance() < plm:
self.mine(COINBASE_MATURITY + 1)
def fund(self, address: str, plm: float, confirm: bool = True) -> str:
"""Send `plm` to `address` from the node's wallet; with `confirm`, mine one block on top. Returns the txid."""
self.ensure_funds(plm + 1)
txid = self.rpc("sendtoaddress", address, plm)
if confirm:
self.mine(1)
return txid
def electrum_address() -> tuple[str, int]:
host, _, port = os.environ.get("PLM_REGTEST_ELECTRUM", DEFAULT_ELECTRUM).rpartition(":")
return host, int(port)
def electrum_reachable(timeout: float = 2.0) -> bool:
try:
with socket.create_connection(electrum_address(), timeout=timeout):
return True
except OSError:
return False