File size: 11,652 Bytes
707fc65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
"""Private, local integration seam for Qwencoin, not an end-to-end package.

Chain shapes and graph interface follow staccDOTsol/qwencoin rails/tools.py
at 9768bfe9f72b7a227fcefba5186da83bec319ecf. See its private-peer fixture
tests/check_qwork_node.py for the native submitblock acceptance sequence.
"""
from __future__ import annotations

import base64
from dataclasses import dataclass
import http.client
import ipaddress
import json
import re
from typing import Any, Protocol

_HEX = re.compile(r"[A-Fa-f0-9]+")
_MAX_REPLY = 8 * 1024 * 1024
_MAX_BLOCK = 4 * 1024 * 1024


class NodeError(RuntimeError):
    """Malformed, disallowed, unavailable, or rejected node operation."""


class LocalGraph(Protocol):
    """An upstream rails.tools.Node owned by this process, not an RPC proxy."""

    def t_graph_feed(self, count: int = 6) -> list[dict[str, Any]]: ...
    def t_graph_who(self, identity: str) -> dict[str, Any]: ...


@dataclass(frozen=True)
class SyncStatus:
    chain: str
    height: int
    headers: int
    tip: str
    peers: int
    initial_block_download: bool
    chainwork: str | None = None

    @property
    def caught_up(self) -> bool:
        """Local progress signal only, not proof another peer agrees."""
        return self.peers > 0 and self.height == self.headers and not self.initial_block_download


def _hex(value: Any, *, length: int) -> str:
    if not isinstance(value, str) or len(value) != length or not _HEX.fullmatch(value):
        raise NodeError("Invalid hexadecimal field")
    return value.lower()


def _nat(value: Any) -> int:
    if type(value) is not int or value < 0:
        raise NodeError("Expected a non-negative integer from node")
    return value


def _loopback_peer(addr: Any) -> bool:
    if not isinstance(addr, str):
        return False
    host, sep, port = addr.rpartition(":")
    if not sep or not port.isascii() or not port.isdigit() or len(port) > 5 or not 1 <= int(port) <= 65535:
        return False
    try:
        return ipaddress.ip_address(host.strip("[]")).is_loopback
    except ValueError:
        return False


class QwencoinNode:
    """Accepts trusted local configuration only; do not pass it to the model.

    Bind the corresponding daemon's RPC to loopback, use cookie auth, and
    disable seed discovery and external connectivity for any submit test.
    This adapter checks chain and observed peers, but cannot verify daemon flags.
    """

    def __init__(self, port: int, cookie: str, *, graph: LocalGraph | None = None,
                 timeout: float = 5.0, allow_regtest_submit: bool = False, allow_mainnet_prepare: bool = False):
        if type(port) is not int or not 1 <= port <= 65535:
            raise ValueError("Invalid port")
        if not isinstance(cookie, str) or len(cookie) > 1024 or not cookie.startswith("__cookie__:") or not cookie[11:] or not cookie.isascii() or any(c.isspace() for c in cookie):
            raise ValueError("Invalid local RPC cookie")
        if type(timeout) not in (float, int) or not 0 < timeout <= 30:
            raise ValueError("Invalid timeout")
        if type(allow_regtest_submit) is not bool:
            raise ValueError("Expected a boolean submit flag")
        self._port = port
        self._authorization = "Basic " + base64.b64encode(cookie.encode("ascii")).decode("ascii")
        self._timeout = timeout
        if type(allow_mainnet_prepare) is not bool or (allow_mainnet_prepare and allow_regtest_submit):
            raise ValueError("Expected separate read-only prepare capability")
        self._allow_mainnet_prepare=allow_mainnet_prepare
        self._graph = graph
        self._allow_regtest_submit = allow_regtest_submit

    def _rpc(self, method: str, params: list[Any]) -> Any:
        if method not in {"getblockchaininfo", "getconnectioncount", "getblockhash", "getbestblockhash", "getblock",
                          "getrawtransaction", "getpeerinfo", "getblocktemplate", "submitblock", "validateaddress"}:
            raise NodeError("RPC operation not allowlisted")
        if method=="submitblock" and not self._allow_regtest_submit:
            raise NodeError("Submission disabled")
        if method=="getblocktemplate" and not (self._allow_regtest_submit or self._allow_mainnet_prepare):
            raise NodeError("Template capability disabled")
        if method=="validateaddress" and not self._allow_mainnet_prepare:
            raise NodeError("Prepare address capability disabled")
        body = json.dumps({"jsonrpc": "1.0", "id": "inkling-local", "method": method, "params": params},
                          allow_nan=False, separators=(",", ":")).encode()
        conn = http.client.HTTPConnection("127.0.0.1", self._port, timeout=self._timeout)
        try:
            conn.request("POST", "/", body, {"Content-Type": "application/json",
                                             "Authorization": self._authorization})
            res = conn.getresponse()
            if res.status not in {200, 404, 500}:
                raise NodeError(f"Local RPC returned HTTP {res.status}; not followed")
            raw = res.read(_MAX_REPLY + 1)
            if len(raw) > _MAX_REPLY:
                raise NodeError("Local RPC response exceeded size limit")
            parsed = json.loads(raw)
        except (OSError, http.client.HTTPException, UnicodeError, ValueError) as exc:
            raise NodeError("Local RPC connection or response failed") from exc
        finally:
            conn.close()
        if not isinstance(parsed, dict) or parsed.get("id") != "inkling-local":
            raise NodeError("Malformed or mismatched RPC response")
        if parsed.get("error") is not None:
            err = parsed["error"]
            code = err.get("code") if isinstance(err, dict) else None
            raise NodeError(f"{method} failed (RPC {code if type(code) is int else 'unknown'})")
        if res.status != 200 or "result" not in parsed:
            raise NodeError("Unexpected RPC status or missing result")
        return parsed["result"]

    def sync_status(self) -> SyncStatus:
        b = self._rpc("getblockchaininfo", [])
        if not isinstance(b, dict) or not isinstance(b.get("chain"), str) or type(b.get("initialblockdownload")) is not bool:
            raise NodeError("Unexpected blockchain info")
        return SyncStatus(b["chain"], _nat(b.get("blocks")), _nat(b.get("headers")),
                          _hex(b.get("bestblockhash"), length=64),
                          _nat(self._rpc("getconnectioncount", [])), b["initialblockdownload"],
                          None if "chainwork" not in b else _hex(b["chainwork"],length=64))

    def mainnet_prepare_reader(self, *, peer):
        if not self._allow_mainnet_prepare:
            raise NodeError("Prepare-only capability disabled")
        routes={"info":("getblockchaininfo",[]),"genesis":("getblockhash",[0]),
                "peers":("getconnectioncount",[]),
                "template":("getblocktemplate",[{"rules":["segwit"]}])}

        def read(op):
            if op not in routes:
                raise NodeError("Expected allowlisted prepare read")
            if op in {"peers","template"}:
                peers=self._rpc("getpeerinfo",[])
                if (type(peers) is not list or not peers or not all(
                    type(row) is dict and row.get("addr")==peer and row.get("inbound") is False for row in peers)):
                    raise NodeError("Require only exact approved native outbound RunPod peer")
            method,params=routes[op]
            return self._rpc(method,params)
        return read

    def prepare_public_payout(self,address,expected_script):
        if not self._allow_mainnet_prepare or type(address) is not str or not address.isascii() or not 10<=len(address)<=100:
            raise NodeError("Expected explicit public payout address")
        value=self._rpc("validateaddress",[address])
        if (type(value) is not dict or value.get("isvalid") is not True or value.get("address")!=address or
                value.get("scriptPubKey")!=expected_script.hex() or value.get("iswitness") is not True or
                value.get("witness_version")!=1):
            raise NodeError("Native mainnet payout is not the already approved Taproot script")
        return expected_script

    def best_tip(self) -> str:
        """One authenticated local request, without creating a CLI per token."""
        return _hex(self._rpc("getbestblockhash", []), length=64)

    def chain_block(self, block: int | str) -> dict[str, Any]:
        if type(block) is int and 0 <= block <= 0x7fffffff:
            h = _hex(self._rpc("getblockhash", [block]), length=64)
        else:
            h = _hex(block, length=64)
        b = self._rpc("getblock", [h, 1])
        if not isinstance(b, dict) or _hex(b.get("hash"), length=64) != h:
            raise NodeError("Unexpected block result")
        return {"height": _nat(b.get("height")), "hash": h, "time": _nat(b.get("time")),
                "txs": _nat(b.get("nTx")), "nonce": _nat(b.get("nonce")),
                "bits": _hex(b.get("bits"), length=8), "work": b.get("powhash"),
                "previous": b.get("previousblockhash")}

    def chain_tx(self, txid: str) -> dict[str, Any]:
        h = _hex(txid, length=64)
        b = self._rpc("getrawtransaction", [h, True])
        if not isinstance(b, dict) or _hex(b.get("txid"), length=64) != h:
            raise NodeError("Unexpected transaction result")
        return b

    def graph_feed(self, count: int = 6) -> list[dict[str, Any]]:
        if type(count) is not int or not 1 <= count <= 12:
            raise NodeError("Graph feed count must be 1 to 12")
        if self._graph is None:
            raise NodeError("Local graph index not configured")
        return self._graph.t_graph_feed(count)

    def graph_who(self, identity: str) -> dict[str, Any]:
        if not isinstance(identity, str) or not 1 <= len(identity) <= 256 or not identity.isprintable():
            raise NodeError("Invalid graph identity")
        if self._graph is None:
            raise NodeError("Local graph index not configured")
        return self._graph.t_graph_who(identity)

    def _isolated_regtest(self) -> None:
        if not self._allow_regtest_submit:
            raise NodeError("Regtest mining disabled")
        b = self._rpc("getblockchaininfo", [])
        peers = self._rpc("getpeerinfo", [])
        if not isinstance(b, dict) or b.get("chain") != "regtest":
            raise NodeError("Never submit against a non-regtest node")
        if not isinstance(peers, list) or not all(isinstance(p, dict) and _loopback_peer(p.get("addr")) for p in peers):
            raise NodeError("Non-loopback or malformed regtest peer")

    def regtest_block_template(self) -> dict[str, Any]:
        self._isolated_regtest()
        t = self._rpc("getblocktemplate", [{"rules": ["segwit"]}])
        if not isinstance(t, dict):
            raise NodeError("Unexpected template result")
        _hex(t.get("previousblockhash"), length=64)
        _hex(t.get("bits"), length=8)
        return t

    def regtest_submit_block(self, block_hex: str) -> None:
        if not isinstance(block_hex, str) or len(block_hex) % 2 or not 162 <= len(block_hex) <= 2 * _MAX_BLOCK or not _HEX.fullmatch(block_hex):
            raise NodeError("Invalid serialized test block")
        self._isolated_regtest()
        result = self._rpc("submitblock", [block_hex.lower()])
        if result is not None:
            # Do not print remote strings to a model as directives.
            raise NodeError("Test block rejected or duplicate")