From f5c6428625400364a2d684720b25e08e43cd639c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 08:52:22 +0000 Subject: [PATCH] Remove unused code; one way to build the node connection No change in behaviour, except that two unused options are gone. - Node layer (S2): RESTClient.headers and its helpers, Node.utxo_set_info, Node.last_latency, getblockcount on the whitelist; the mock node no longer serves them. - Store (S3): store.now, Store.lock, Store._seq, spam_utxo_count, size_on_disk and the readonly branch (the web server has its own read-only connections). - Settings (S4): Setting.file_ok, .group and .choices, json_schema with --print-settings-schema, UPSTREAM_DATE, the PROFILES labels, the fields of /api/settings the page does not use, and allow_pause_when_managed (pause is always available; an old value in settings.json is ignored). - S5: a test for the built-in HTTPS server (certificate made with openssl). - S9: node.client.make_node(config, timeout) replaces Scanner.make_node, the second copy in maybe_utxo_info and the Scanner built only to make a node in the connection test and the lookup. - S10: BlockNotConnected (a BlockInvalid) replaces matching "parent" in the error text. - S11: Scanner.node_busy() replaces the two copies of the latency rule. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 ++ README.md | 2 +- bitcoinmonetaryview/__main__.py | 8 +- bitcoinmonetaryview/config.py | 89 +++++++-------------- bitcoinmonetaryview/diagnostics.py | 7 +- bitcoinmonetaryview/node/client.py | 29 ++++--- bitcoinmonetaryview/node/rest.py | 22 ----- bitcoinmonetaryview/node/rpc.py | 1 - bitcoinmonetaryview/rules/__init__.py | 1 - bitcoinmonetaryview/rules/monetary_rules.py | 6 +- bitcoinmonetaryview/scanner.py | 70 +++++++--------- bitcoinmonetaryview/server.py | 6 +- bitcoinmonetaryview/static/app.js | 4 +- bitcoinmonetaryview/store.py | 50 +++--------- docs/settings.md | 3 - docs/startos.md | 4 +- tests/mocknode.py | 13 --- tests/test_node.py | 8 +- tests/test_rules.py | 8 ++ tests/test_scanner.py | 4 +- tests/test_server.py | 39 ++++++++- tests/test_store_fs.py | 3 +- 22 files changed, 159 insertions(+), 224 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dadbe2b..2482616 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -58,6 +58,12 @@ All notable changes are documented here. This project uses [semantic versioning] - **Docker health check** no longer goes through proxy settings in the container's environment. - **Build:** every GitHub Action in the build and release workflows is pinned to an exact commit, so a moved or compromised release tag of a third-party action cannot change the published image. +- **Removed:** the setting `allow_pause_when_managed` (Pause is always available; an old value in + `settings.json` is ignored) and the option `--print-settings-schema`, which nothing used. The settings API + now returns only what the dashboard shows. `getblockcount` is no longer on the RPC whitelist; the app never + called it. +- **Internal:** unused code removed in the node, store and settings layers; one shared way to build the node + connection; a test for the built-in HTTPS server. ## [0.3.12] — 2026-11-09 diff --git a/README.md b/README.md index d077fc1..b0ff2b1 100644 --- a/README.md +++ b/README.md @@ -232,7 +232,7 @@ exemptions: the OP_RETURN size test stays upstream's script-length rule. ## Security - **Read-only by construction**: the RPC client refuses every method that is not on a short whitelist - (`getblockchaininfo`, `getnetworkinfo`, `getbestblockhash`, `getblockcount`, `getblockhash`, + (`getblockchaininfo`, `getnetworkinfo`, `getbestblockhash`, `getblockhash`, `getblockheader`, `getblock` with verbosity 0, `gettxoutsetinfo` with `hash_type=none`) — also inside batch requests and with forbidden parameters. REST (`rest=1`) is used only if you have already enabled it. - **No access to the node's files.** Only the RPC cookie file is read, if you point to it — opened read-only. diff --git a/bitcoinmonetaryview/__main__.py b/bitcoinmonetaryview/__main__.py index e7b77ba..d962006 100644 --- a/bitcoinmonetaryview/__main__.py +++ b/bitcoinmonetaryview/__main__.py @@ -1,7 +1,6 @@ # SPDX-License-Identifier: AGPL-3.0-or-later """Entry point: python3 -m bitcoinmonetaryview""" -import json import logging import os import signal @@ -9,7 +8,7 @@ import threading from . import __version__ -from .config import Config, build_arg_parser, default_data_dir, json_schema +from .config import Config, build_arg_parser, default_data_dir def main(argv=None): @@ -17,13 +16,10 @@ def main(argv=None): if args.version: print(f"Monetary View {__version__}") return 0 - if args.print_settings_schema: - print(json.dumps(json_schema(), indent=2)) - return 0 data_dir = os.path.abspath(args.data_dir or default_data_dir()) os.makedirs(data_dir, mode=0o700, exist_ok=True) - cli = {k: v for k, v in vars(args).items() if k not in ("data_dir", "print_settings_schema", "check", "version")} + cli = {k: v for k, v in vars(args).items() if k not in ("data_dir", "check", "version")} try: config = Config(data_dir, cli=cli) except Exception as e: diff --git a/bitcoinmonetaryview/config.py b/bitcoinmonetaryview/config.py index f37a916..df05dd8 100644 --- a/bitcoinmonetaryview/config.py +++ b/bitcoinmonetaryview/config.py @@ -122,83 +122,55 @@ def _hosts(v): class Setting: - def __init__(self, name, conv, default, help, secret=False, file_ok=True, - ui_editable=False, kind="string", choices=None, group="general"): + def __init__(self, name, conv, default, help, secret=False, ui_editable=False, kind="string"): self.name, self.conv, self.default, self.help = name, conv, default, help - self.secret, self.file_ok, self.ui_editable = secret, file_ok, ui_editable - self.kind, self.choices, self.group = kind, choices, group + self.secret, self.ui_editable, self.kind = secret, ui_editable, kind SCHEMA = [ # --- node connection - Setting("rpc_url", _url, "http://127.0.0.1:8332", "Bitcoin Core/Knots/Roots RPC URL", group="node"), - Setting("rpc_user", _str, "", "RPC username (leave empty when using a cookie file)", group="node"), - Setting("rpc_password", _str, "", "RPC password", secret=True, group="node"), - Setting("rpc_cookie_file", _str, "", "Path to bitcoind's .cookie file (read-only)", group="node"), - Setting("rpc_cafile", _str, "", "Extra CA certificate (PEM) to trust for https RPC, e.g. Start9 root CA", - group="node"), - Setting("tor_proxy", _hostport, "", "SOCKS5 proxy for .onion RPC, e.g. 127.0.0.1:9050", group="node"), + Setting("rpc_url", _url, "http://127.0.0.1:8332", "Bitcoin Core/Knots/Roots RPC URL"), + Setting("rpc_user", _str, "", "RPC username (leave empty when using a cookie file)"), + Setting("rpc_password", _str, "", "RPC password", secret=True), + Setting("rpc_cookie_file", _str, "", "Path to bitcoind's .cookie file (read-only)"), + Setting("rpc_cafile", _str, "", "Extra CA certificate (PEM) to trust for https RPC, e.g. Start9 root CA"), + Setting("tor_proxy", _hostport, "", "SOCKS5 proxy for .onion RPC, e.g. 127.0.0.1:9050"), Setting("use_rest", _bool, True, "Use bitcoind's REST interface if it is already enabled (faster)", - kind="boolean", group="node"), - Setting("rpc_timeout", _int(5, 900), 120, "RPC timeout in seconds", kind="integer", group="node"), + kind="boolean"), + Setting("rpc_timeout", _int(5, 900), 120, "RPC timeout in seconds", kind="integer"), # --- scanning Setting("speed_profile", _choice("eco", "balanced", "full"), "eco", - "eco = gentlest on the node, full = fastest", ui_editable=True, kind="string", - choices=["eco", "balanced", "full"], group="scan"), + "eco = gentlest on the node, full = fastest", ui_editable=True, kind="string"), Setting("scan_window", _window, "", "Only scan history during this daily time window, e.g. 01:00-07:00", - ui_editable=True, group="scan"), + ui_editable=True), Setting("timezone", _tz, "UTC", "Time zone for scan_window (IANA name, e.g. Europe/Berlin)", - ui_editable=True, group="scan"), + ui_editable=True), Setting("quick_pass_blocks", _int(0, 50000), 1000, "Recent blocks analysed first for a quick result", - kind="integer", group="scan"), + kind="integer"), Setting("sample_every", _int(0, 100000), 100, "Before the full scan, analyse every Nth block of the history for an early whole-chain estimate " - "(0 = off)", kind="integer", group="scan"), + "(0 = off)", kind="integer"), Setting("carrier_policy", _bool, True, "Keep oversized OP_RETURNs that are verified payment-protocol envelopes (upstream carrier policy)", - kind="boolean", group="scan"), + kind="boolean"), Setting("dust_start_height", _opt_int(0, 10_000_000), None, "Height from which P2TR dust counts (auto: 767430 on mainnet, 0 on test networks)", - kind="integer", group="scan"), - Setting("bloom_mb", _int(8, 4096), 256, "Memory for the spent-output filter (MB)", kind="integer", - group="scan"), + kind="integer"), + Setting("bloom_mb", _int(8, 4096), 256, "Memory for the spent-output filter (MB)", kind="integer"), # --- web interface - Setting("bind", _str, "127.0.0.1", "Address the web interface listens on", file_ok=True, group="web"), - Setting("port", _int(1, 65535), 8338, "Port of the web interface", kind="integer", group="web"), - Setting("auth_user", _str, "", "Username for the web interface (optional basic auth)", group="web"), - Setting("auth_password", _str, "", "Password for the web interface", secret=True, group="web"), - Setting("tls_cert", _str, "", "TLS certificate (PEM) to serve the web interface over https", group="web"), - Setting("tls_key", _str, "", "TLS private key (PEM)", group="web"), + Setting("bind", _str, "127.0.0.1", "Address the web interface listens on"), + Setting("port", _int(1, 65535), 8338, "Port of the web interface", kind="integer"), + Setting("auth_user", _str, "", "Username for the web interface (optional basic auth)"), + Setting("auth_password", _str, "", "Password for the web interface", secret=True), + Setting("tls_cert", _str, "", "TLS certificate (PEM) to serve the web interface over https"), + Setting("tls_key", _str, "", "TLS private key (PEM)"), Setting("allowed_hosts", _hosts, [], "Extra Host names allowed for the web interface (comma separated)", - kind="array", group="web"), - Setting("allow_pause_when_managed", _bool, True, "Keep the pause/resume button in managed mode", - kind="boolean", group="web"), - Setting("log_level", _choice("debug", "info", "warning", "error"), "info", "Log verbosity", - choices=["debug", "info", "warning", "error"], group="general"), + kind="array"), + Setting("log_level", _choice("debug", "info", "warning", "error"), "info", "Log verbosity"), ] BY_NAME = {s.name: s for s in SCHEMA} -def json_schema(): - props = {} - for s in SCHEMA: - p = {"description": s.help} - p["type"] = {"string": "string", "boolean": "boolean", "integer": "integer", "array": "array"}[s.kind] - if s.name == "dust_start_height": - p["type"] = ["integer", "null"] - if s.choices: - p["enum"] = s.choices - if s.kind == "array": - p["items"] = {"type": "string"} - p["default"] = s.default - if s.secret: - p["writeOnly"] = True - props[s.name] = p - return {"$schema": "https://json-schema.org/draft/2020-12/schema", - "title": "Monetary View settings", "type": "object", - "additionalProperties": True, "properties": props} - - def default_data_dir(): return os.environ.get("BMV_DATA_DIR") or os.path.join(os.path.expanduser("~"), ".bitcoinmonetaryview") @@ -277,12 +249,12 @@ def _file_settings(self, warnings): if fdata is None: if self._file_values is None: warnings.append(f"{SETTINGS_FILE} could not be read ({error}); using defaults") - return {}, {s.name for s in SCHEMA if s.file_ok} + return {}, {s.name for s in SCHEMA} warnings.append(f"{SETTINGS_FILE} could not be read ({error}); keeping the previous settings") return self._file_values, self._file_unknown previous, good, unknown = self._file_values or {}, {}, set() for s in SCHEMA: - if not (s.file_ok and s.name in fdata): + if s.name not in fdata: continue try: good[s.name] = s.conv(fdata[s.name]) @@ -373,9 +345,7 @@ def public_view(self): v = self.values[s.name] if s.secret: v = "********" if v else "" - out.append({"name": s.name, "value": v, "default": s.default, "help": s.help, - "source": self.sources[s.name], "editable": self.can_edit(s.name), - "choices": s.choices, "group": s.group, "secret": s.secret}) + out.append({"name": s.name, "value": v, "source": self.sources[s.name], "editable": self.can_edit(s.name)}) return out @@ -409,7 +379,6 @@ def build_arg_parser(): ap.add_argument(flag, dest=s.name, default=None, type=_bool, metavar="true|false", help=s.help) else: ap.add_argument(flag, dest=s.name, default=None, help=s.help) - ap.add_argument("--print-settings-schema", action="store_true", help="print the settings JSON Schema and exit") ap.add_argument("--check", action="store_true", help="run the connection test and exit") ap.add_argument("--version", action="store_true", help="print version and exit") return ap diff --git a/bitcoinmonetaryview/diagnostics.py b/bitcoinmonetaryview/diagnostics.py index 99de592..4e10cc4 100644 --- a/bitcoinmonetaryview/diagnostics.py +++ b/bitcoinmonetaryview/diagnostics.py @@ -3,21 +3,20 @@ import time +from .node.client import make_node from .node.rpc import NodeAuthError, NodeError, RPCError from .node.transport import NodeUnreachable -def run_connection_test(scanner_or_config): +def run_connection_test(config): """Return a list of checks: {name, status: ok|warn|fail, message, hint}.""" - config = getattr(scanner_or_config, "config", scanner_or_config) - from .scanner import Scanner checks = [] def add(name, status, message, hint=""): checks.append({"name": name, "status": status, "message": message, "hint": hint}) try: - node = Scanner(config).make_node() + node = make_node(config) except ValueError as e: add("Settings", "fail", str(e), "Set rpc_url and either rpc_cookie_file or rpc_user/rpc_password.") return checks diff --git a/bitcoinmonetaryview/node/client.py b/bitcoinmonetaryview/node/client.py index ab1a666..6ff1e29 100644 --- a/bitcoinmonetaryview/node/client.py +++ b/bitcoinmonetaryview/node/client.py @@ -1,8 +1,6 @@ # SPDX-License-Identifier: AGPL-3.0-or-later """High-level, read-only view of a Bitcoin Core/Knots/Roots node (RPC + optional REST).""" -import time - from ..rules import monetary_rules as mr from .rest import RESTClient from .rpc import NodeAuthError, NodeError, NodeUnreachable, RPCClient, RPCError @@ -17,7 +15,6 @@ def __init__(self, url, user=None, password=None, cookie_file=None, timeout=timeout, proxy=proxy, cafile=cafile) self.rest = RESTClient(self.rpc.transport) self.use_rest = use_rest - self.last_latency = 0.0 self.batch_ok = True @property @@ -69,16 +66,9 @@ def header(self, block_hash): def block(self, block_hash): """Raw serialized block bytes (REST binary if available, else hex RPC).""" - t = time.monotonic() if self.rest.available: - raw = self.rest.block(block_hash) - else: - raw = bytes.fromhex(self.rpc.call("getblock", block_hash, 0)) - self.last_latency = time.monotonic() - t - return raw - - def utxo_set_info(self): - return self.rpc.call("gettxoutsetinfo", "none") + return self.rest.block(block_hash) + return bytes.fromhex(self.rpc.call("getblock", block_hash, 0)) def close(self): self.rpc.close() @@ -87,6 +77,21 @@ def close(self): NETWORKS = {"main": "mainnet", "test": "testnet3", "testnet4": "testnet4", "signet": "signet", "regtest": "regtest"} +def make_node(config, timeout=None): + """The node connection the settings describe (timeout: rpc_timeout unless given).""" + c = config + proxy = None + if c.tor_proxy: + host, port = c.tor_proxy.rsplit(":", 1) + proxy = (host.strip("[]"), int(port)) + node = Node(c.rpc_url, user=c.rpc_user or None, password=c.rpc_password, + cookie_file=c.rpc_cookie_file or None, proxy=proxy, cafile=c.rpc_cafile or None, + timeout=timeout or c.rpc_timeout, use_rest=c.use_rest) + # On a platform (StartOS, Umbrel) the app reaches the node over its internal network. + node.transport.trusted_network = c.platform + return node + + def network_name(chain): """getblockchaininfo.chain as the short name that also names the network's data directory.""" if chain not in NETWORKS: diff --git a/bitcoinmonetaryview/node/rest.py b/bitcoinmonetaryview/node/rest.py index 24284c6..45a5cde 100644 --- a/bitcoinmonetaryview/node/rest.py +++ b/bitcoinmonetaryview/node/rest.py @@ -12,7 +12,6 @@ from .transport import NodeError, Transport _HEX64 = re.compile(r"^[0-9a-f]{64}$") -MAX_HEADERS = 2000 def _check_hash(h): @@ -25,7 +24,6 @@ class RESTClient: def __init__(self, transport: Transport): self.transport = transport self.available = False - self.new_headers_syntax = True def probe(self): """Detect whether REST is enabled. Never fails loudly: REST is optional.""" @@ -41,23 +39,3 @@ def block(self, block_hash): if status != 200: raise NodeError(f"REST block request failed (HTTP {status})") return data - - def headers(self, start_hash, count=MAX_HEADERS): - """Up to `count` consecutive 80-byte headers starting at start_hash (inclusive).""" - count = max(1, min(int(count), MAX_HEADERS)) - h = _check_hash(start_hash) - if self.new_headers_syntax: - status, data = self.transport.request("GET", f"/rest/headers/{h}.bin?count={count}") - if status == 200: - return _split_headers(data) - self.new_headers_syntax = False # Core < 24 - status, data = self.transport.request("GET", f"/rest/headers/{count}/{h}.bin") - if status != 200: - raise NodeError(f"REST headers request failed (HTTP {status})") - return _split_headers(data) - - -def _split_headers(data): - if len(data) % 80: - raise NodeError("REST returned a truncated header list") - return [data[i:i + 80] for i in range(0, len(data), 80)] diff --git a/bitcoinmonetaryview/node/rpc.py b/bitcoinmonetaryview/node/rpc.py index 4945dc0..5af5565 100644 --- a/bitcoinmonetaryview/node/rpc.py +++ b/bitcoinmonetaryview/node/rpc.py @@ -49,7 +49,6 @@ def _height(p): "getblockchaininfo": _no_params, "getnetworkinfo": _no_params, "getbestblockhash": _no_params, - "getblockcount": _no_params, "getblockhash": lambda p: len(p) == 1 and _height(p[0]), "getblockheader": lambda p: len(p) in (1, 2) and _hash_param(p[0]) and (len(p) == 1 or isinstance(p[1], bool)), diff --git a/bitcoinmonetaryview/rules/__init__.py b/bitcoinmonetaryview/rules/__init__.py index 9539074..4ccfa78 100644 --- a/bitcoinmonetaryview/rules/__init__.py +++ b/bitcoinmonetaryview/rules/__init__.py @@ -9,4 +9,3 @@ UPSTREAM_REPO = "https://github.com/sambitcoin/BitcoinMonetaryNode" UPSTREAM_COMMIT = "492539256d43151973cb4cdf73c91d67c4be203c" -UPSTREAM_DATE = "2026-09-24" diff --git a/bitcoinmonetaryview/rules/monetary_rules.py b/bitcoinmonetaryview/rules/monetary_rules.py index 202dc54..919b32f 100644 --- a/bitcoinmonetaryview/rules/monetary_rules.py +++ b/bitcoinmonetaryview/rules/monetary_rules.py @@ -48,6 +48,10 @@ class BlockInvalid(ValueError): """The block bytes do not match their header or are malformed.""" +class BlockNotConnected(BlockInvalid): + """The block's header does not link to the expected parent: the chain changed.""" + + def classify_output(script, value, height, op_return_limit, dust_start_height=MAINNET_DUST_START, carrier_policy=None): """ @@ -375,7 +379,7 @@ def verify_block(result, expected_hash=None, expected_prev=None): if expected_hash is not None and up.dsha(header) != expected_hash: raise BlockInvalid("block hash does not match the requested hash") if expected_prev is not None and header[4:36] != expected_prev: - raise BlockInvalid("block does not connect to the expected parent") + raise BlockNotConnected("block does not connect to the expected parent") root, mutated = merkle_root(result["txids"]) if root != header[36:68]: raise BlockInvalid("merkle root mismatch: transaction data was altered") diff --git a/bitcoinmonetaryview/scanner.py b/bitcoinmonetaryview/scanner.py index c762451..750b994 100644 --- a/bitcoinmonetaryview/scanner.py +++ b/bitcoinmonetaryview/scanner.py @@ -17,8 +17,8 @@ import time from . import __version__ -from .node.client import Node, default_dust_start, network_name -from .node.rpc import RPC_IN_WARMUP, NodeAuthError, NodeError, RPCError, RPCClient +from .node.client import default_dust_start, make_node, network_name +from .node.rpc import RPC_IN_WARMUP, NodeAuthError, NodeError, RPCError from .node.transport import NodeUnreachable from .rules import UPSTREAM_COMMIT from .rules import monetary_rules as mr @@ -36,9 +36,9 @@ PROFILES = { # workers: parallel block requests; pause: sleep after each block as a multiple of its fetch time # procs: analysis worker processes (CPU cores used for parsing; one core is always left free) - "eco": {"workers": 1, "procs": 0, "pause": 1.0, "min_sleep": 0.05, "label": "Eco"}, - "balanced": {"workers": 2, "procs": 2, "pause": 0.25, "min_sleep": 0.0, "label": "Balanced"}, - "full": {"workers": 4, "procs": 4, "pause": 0.0, "min_sleep": 0.0, "label": "Full speed"}, + "eco": {"workers": 1, "procs": 0, "pause": 1.0, "min_sleep": 0.05}, + "balanced": {"workers": 2, "procs": 2, "pause": 0.25, "min_sleep": 0.0}, + "full": {"workers": 4, "procs": 4, "pause": 0.0, "min_sleep": 0.0}, } PHASE_LABELS = { @@ -230,19 +230,6 @@ def check_config(self): self.status.set(profile=self.config.speed_profile, scan_window=self.config.scan_window, timezone=self.config.timezone) - def make_node(self): - c = self.config - proxy = None - if c.tor_proxy: - host, port = c.tor_proxy.rsplit(":", 1) - proxy = (host.strip("[]"), int(port)) - node = Node(c.rpc_url, user=c.rpc_user or None, password=c.rpc_password, - cookie_file=c.rpc_cookie_file or None, proxy=proxy, cafile=c.rpc_cafile or None, - timeout=c.rpc_timeout, use_rest=c.use_rest) - # On a platform (StartOS, Umbrel) the app reaches the node over its internal network. - node.transport.trusted_network = c.platform - return node - def policy(self): return cp.Policy() if self.config.carrier_policy else None @@ -321,7 +308,7 @@ def session(self): self._conn_sig = self._sig(CONNECTION_KEYS) self._rules_sig = self._sig(RULES_KEYS) self.status.set(phase="connecting", detail=f"Connecting to {self.config.rpc_url}") - self.node = self.make_node() + self.node = make_node(self.config) info = self.node.chain_info() net = network_name(info.get("chain")) rest = self.node.probe_rest() @@ -552,9 +539,8 @@ def fetch_ordered(self, heights, hashes): """ prof = PROFILES[self.config.speed_profile] workers = prof["workers"] - if self.latency_ewma and self.latency_floor and self.latency_ewma > 3 * self.latency_floor \ - and self.latency_ewma > 0.5: - workers = 1 # node seems busy: back off + if self.node_busy(): + workers = 1 # back off apool = self.analysis_pool(prof["procs"]) def job(h, hx): @@ -625,7 +611,7 @@ def accept(self, height, hexhash, res, expected_prev): for attempt in range(3): if not isinstance(res, Exception): if expected_prev is not None and res["header"][4:36] != expected_prev: - raise mr.BlockInvalid("block does not connect to the expected parent") + raise mr.BlockNotConnected("block does not connect to the expected parent") return res if attempt == 2: raise res @@ -650,6 +636,11 @@ def shutdown_pool(self): self._pool = None self._pool_workers = None + def node_busy(self): + """The node answers more than three times slower than its best, and slower than 0.5 s.""" + return bool(self.latency_ewma and self.latency_floor and self.latency_ewma > 3 * self.latency_floor + and self.latency_ewma > 0.5) + def throttle(self, latency): prof = PROFILES[self.config.speed_profile] a = 0.2 @@ -659,8 +650,8 @@ def throttle(self, latency): else: self.latency_floor *= 1.0005 # let the baseline drift up slowly delay = max(prof["min_sleep"], prof["pause"] * latency) - if self.latency_ewma > 3 * self.latency_floor and self.latency_ewma > 0.5: - delay = max(delay, self.latency_ewma) # adaptive backoff: node is busy + if self.node_busy(): + delay = max(delay, self.latency_ewma) # adaptive backoff if delay > 0: self.wake.wait(delay) self.wake.clear() @@ -880,14 +871,12 @@ def full_pass(self, tip, info): h = heights[i] try: res = self.accept(h, hashes[i], res, expected_prev) - except mr.BlockInvalid as e: - if "parent" in str(e): - self.store.commit() - self.status.event("warning", f"Block {h:,} does not connect: chain changed while " - "scanning; checking for a reorganisation") - self.handle_reorg(int(self.node.chain_info()["blocks"])) - return - raise + except mr.BlockNotConnected: + self.store.commit() + self.status.event("warning", f"Block {h:,} does not connect: chain changed while " + "scanning; checking for a reorganisation") + self.handle_reorg(int(self.node.chain_info()["blocks"])) + return delta = self.store.apply_block_utxo(h, res, self.bloom) self.store.put_block(h, res, utxo_done=True, utxo_delta=delta) self.store.set_meta("full_next_height", h + 1) @@ -969,17 +958,12 @@ def maybe_utxo_info(self, force_first=False): prev_phase = self.status.get("phase") self.status.set(phase="utxo_info", detail="Asking the node for the total UTXO set size " "(read-only, may take a few minutes)") - c = self.config try: - proxy = None - if c.tor_proxy: - host, port = c.tor_proxy.rsplit(":", 1) - proxy = (host.strip("[]"), int(port)) - slow = RPCClient(c.rpc_url, user=c.rpc_user or None, password=c.rpc_password, - cookie_file=c.rpc_cookie_file or None, timeout=1800, proxy=proxy, - cafile=c.rpc_cafile or None) - res = slow.call("gettxoutsetinfo", "none") - slow.close() + slow = make_node(self.config, timeout=1800) # a full walk of the UTXO set without an index + try: + res = slow.rpc.call("gettxoutsetinfo", "none") + finally: + slow.close() import json self.store.set_meta("utxo_info", json.dumps(res)) self.store.set_meta("utxo_info_time", time.time()) diff --git a/bitcoinmonetaryview/server.py b/bitcoinmonetaryview/server.py index 633a637..689a2e4 100644 --- a/bitcoinmonetaryview/server.py +++ b/bitcoinmonetaryview/server.py @@ -29,6 +29,7 @@ from . import __version__ from .analytics import Analytics, block_from_result from .diagnostics import run_connection_test +from .node.client import make_node from .node.rpc import NodeError, RPCError from .rules import monetary_rules as mr from .rules import UPSTREAM_COMMIT, UPSTREAM_REPO @@ -174,7 +175,7 @@ def lookup(self, query): self._lookup_last = time.monotonic() sc = self.scanner if self._lookup_node is None: - self._lookup_node = sc.make_node() + self._lookup_node = make_node(self.config) node = self._lookup_node try: if hexhash is not None: @@ -262,7 +263,6 @@ def status(self): s["managed"] = c.managed s["managed_by"] = c.managed_by s["platform"] = c.managed_by or None - s["can_pause"] = (not c.managed) or c.allow_pause_when_managed s["can_rescan"] = not c.managed s["upstream"] = {"repo": UPSTREAM_REPO, "commit": UPSTREAM_COMMIT} s["auth_enabled"] = bool(c.auth_user) @@ -513,8 +513,6 @@ def do_POST(self): action = body.get("action") st = app.status() if action in ("pause", "resume"): - if not st["can_pause"]: - return self.error(403, "managed by the platform") app.scanner.pause() if action == "pause" else app.scanner.resume() return self.send_json({"ok": True}) if action == "rescan": diff --git a/bitcoinmonetaryview/static/app.js b/bitcoinmonetaryview/static/app.js index 7673313..17f485f 100644 --- a/bitcoinmonetaryview/static/app.js +++ b/bitcoinmonetaryview/static/app.js @@ -516,7 +516,7 @@ $("#m-elapsed").textContent = fmtDur(st.now - (st.full_started_at || st.started_at)); $("#m-eta").textContent = st.phase === "live" ? _t("done") : st.eta_seconds ? "~" + fmtDur(st.eta_seconds) : "–"; const pb = $("#pause-btn"); - pb.hidden = !st.can_pause || st.phase === "live"; + pb.hidden = st.phase === "live"; pb.textContent = st.paused ? _t("Resume") : _t("Pause"); $("#app-version").textContent = st.version || ""; // AGPL: the source of exactly this version (a modified copy must point to its own) @@ -1243,7 +1243,7 @@ h("div", { class: "form-row" }, h("label", null, _t("Scan window"), pinnedNote(win)), h("div", { class: "inline-fields" }, winInput, tzInput, saveWin), h("div", { class: "help", text: _t("Optional: only scan history during these hours. New blocks are always analysed.") })), h("div", { class: "form-row" }, h("label", { text: _t("Scanning") }), h("div", { style: { display: "flex", gap: "8px", flexWrap: "wrap" } }, - st.can_pause ? h("button", { class: "btn", type: "button", text: st.paused ? _t("Resume") : _t("Pause"), onclick: togglePause }) : null, + h("button", { class: "btn", type: "button", text: st.paused ? _t("Resume") : _t("Pause"), onclick: togglePause }), st.can_rescan ? h("button", { class: "btn btn-danger", type: "button", text: _t("Rescan from scratch"), onclick: async () => { if (!confirm(_t("Delete this app's results and scan the whole chain again? Your node is not affected."))) return; await post("/api/control", { action: "rescan" }).catch((e) => alert(_ts(e.message))); diff --git a/bitcoinmonetaryview/store.py b/bitcoinmonetaryview/store.py index f327430..d7a4af1 100644 --- a/bitcoinmonetaryview/store.py +++ b/bitcoinmonetaryview/store.py @@ -19,8 +19,6 @@ import sqlite3 import struct import sys -import threading -import time try: import fcntl @@ -245,27 +243,20 @@ def load(cls, path, mbytes, token): class Store: - def __init__(self, path, readonly=False, cache_mb=64): + def __init__(self, path, cache_mb=64): self.path = path - self.readonly = readonly - if readonly: - uri = "file:" + path + "?mode=ro" - self.db = sqlite3.connect(uri, uri=True, check_same_thread=False, timeout=30) - else: - os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True) - no_cow(os.path.dirname(path)) - self.db = sqlite3.connect(path, check_same_thread=False, timeout=30, isolation_level=None) - self._refuse_newer_schema() - self.db.execute("PRAGMA journal_mode=WAL") - self.db.execute("PRAGMA synchronous=NORMAL") - self.db.execute(f"PRAGMA wal_autocheckpoint={WAL_CHECKPOINT_PAGES}") - self.db.execute(f"PRAGMA journal_size_limit={WAL_SIZE_LIMIT}") - self.db.executescript(DDL) - if self.get_meta("schema_version") is None: - self.set_meta("schema_version", SCHEMA_VERSION) + os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True) + no_cow(os.path.dirname(path)) + self.db = sqlite3.connect(path, check_same_thread=False, timeout=30, isolation_level=None) + self._refuse_newer_schema() + self.db.execute("PRAGMA journal_mode=WAL") + self.db.execute("PRAGMA synchronous=NORMAL") + self.db.execute(f"PRAGMA wal_autocheckpoint={WAL_CHECKPOINT_PAGES}") + self.db.execute(f"PRAGMA journal_size_limit={WAL_SIZE_LIMIT}") + self.db.executescript(DDL) + if self.get_meta("schema_version") is None: + self.set_meta("schema_version", SCHEMA_VERSION) self.db.execute(f"PRAGMA cache_size=-{int(cache_mb) * 1024}") - self.lock = threading.RLock() - self._seq = 0 self.in_tx = False def _refuse_newer_schema(self): @@ -478,10 +469,6 @@ def iter_spam_outpoint_batches(self, batch=50_000): return yield rows - def spam_utxo_count(self): - r = self.db.execute("SELECT COALESCE(SUM(count),0) FROM utxo_hist").fetchone() - return r[0] - def reset(self): """Delete all analysis results (e.g. after a rules change). Settings are untouched.""" self.begin() @@ -494,21 +481,8 @@ def reset(self): self.discard_saved_bloom() self.commit() - def size_on_disk(self): - total = 0 - for suffix in ("", "-wal", "-shm"): - try: - total += os.path.getsize(self.path + suffix) - except OSError: - pass - return total - def close(self): try: self.commit() finally: self.db.close() - - -def now(): - return time.time() diff --git a/docs/settings.md b/docs/settings.md index 2a8fa87..c500294 100644 --- a/docs/settings.md +++ b/docs/settings.md @@ -24,8 +24,6 @@ fail safe instead: Settings given on the command line or in the environment are not affected by the file. -The machine-readable JSON Schema is printed by `python3 -m bitcoinmonetaryview --print-settings-schema`. - Special environment variables (not settings): `BMV_DATA_DIR` (data directory) and `BMV_MANAGED_BY`, set by platform packages. With any value the platform's proxy fronts the web interface (Host check and login are left to it) and plain-HTTP RPC on its internal network is not flagged. `startos` additionally shows the settings @@ -72,7 +70,6 @@ Umbrel has no settings screen for apps. | `tls_cert` | empty | TLS certificate (PEM) to serve the web interface over https. | | `tls_key` | empty | TLS private key (PEM). | | `allowed_hosts` | empty | Extra Host names allowed for the web interface (comma separated). | -| `allow_pause_when_managed` | true | Keep the pause/resume button in managed mode. | ## General diff --git a/docs/startos.md b/docs/startos.md index 29c3534..56f912f 100644 --- a/docs/startos.md +++ b/docs/startos.md @@ -9,8 +9,8 @@ Based on the [StartOS 0.4.0.x packaging guide](https://docs.start9.com/packaging | StartOS concept | How this app supports it | |---|---| -| **Settings via Actions + File Model** | Actions write `/data/settings.json` (`merge()`). The app reads it with the schema in [settings.md](settings.md) (`--print-settings-schema` prints JSON Schema). Missing values are defaults, unknown keys are ignored, and changes are applied live. An unreadable file or an invalid value keeps the previous setting; the web login and the spam rules are never taken from defaults by accident (see [settings.md](settings.md)). | -| **Managed mode** | Set `BMV_MANAGED_BY=startos`. The web UI then shows settings read-only ("managed by StartOS") and disables settings changes and the rescan button. Pause/resume stays (disable with `allow_pause_when_managed=false`). | +| **Settings via Actions + File Model** | Actions write `/data/settings.json` (`merge()`). The app reads it with the schema in [settings.md](settings.md). Missing values are defaults, unknown keys are ignored, and changes are applied live. An unreadable file or an invalid value keeps the previous setting; the web login and the spam rules are never taken from defaults by accident (see [settings.md](settings.md)). | +| **Managed mode** | Set `BMV_MANAGED_BY=startos`. The web UI then shows settings read-only ("managed by StartOS") and disables settings changes and the rescan button. Pause/resume stays available. | | **Dependency on Bitcoin Core / Knots / Roots** | `setupDependencies`: `bitcoind`, `kind: 'running'`, health checks `bitcoind` + `sync-progress`. Resolve the node with `sdk.host.getBridgeAddress(...)` (StartOS 0.4 no longer uses `bitcoind.startos`): prefer `rpc-local` (port 58332, bitcoind's own RPC **and REST**), fall back to the `rpc` proxy (port 8332, JSON-RPC only — the app then uses RPC and single calls instead of batches automatically). | | **Credentials** | Mount the node's `main` volume **read-only as a directory** (`mountDependency({ dependencyId: 'bitcoind', volumeId: 'main', subpath: null, mountpoint: '/mnt/bitcoind', readonly: true })`) and set `rpc_cookie_file=/mnt/bitcoind/.cookie`. Do not bind-mount the single file: bitcoind replaces `.cookie` on every restart, and a file bind mount would keep showing the old one. The app re-reads the cookie on HTTP 401. | | **Web UI interface** | Bind the app's port (8338) as a `ui` interface. The package protects it with the app's own basic auth (`auth_user` / `auth_password` in `settings.json`), set by a *Set Web Password* action that a critical task asks for; the action runs in any state and restarts a running service, so only the new password works. The Host-header check is delegated to the proxy in managed mode. | diff --git a/tests/mocknode.py b/tests/mocknode.py index fd6bb97..f3be33f 100644 --- a/tests/mocknode.py +++ b/tests/mocknode.py @@ -97,17 +97,6 @@ def do_GET(self): return self._send(404, b"not found", "text/plain") time.sleep(node.delay) return self._send(200, node.raw(i), "application/octet-stream") - if p.startswith("/rest/headers/"): - rest = p[len("/rest/headers/"):] - if "?count=" in rest: - hx, cnt = rest.split(".bin?count=") - else: - cnt, hx = rest[:-4].split("/") - i = node.chain.find(hx) - if i is None: - return self._send(404, b"not found", "text/plain") - hs = b"".join(r[:80] for r, _ in node.chain.blocks[i:i + int(cnt)]) - return self._send(200, hs, "application/octet-stream") return self._send(404, b"not found", "text/plain") def do_POST(self): @@ -178,8 +167,6 @@ def err(code, msg): return ok({"version": 290000, "subversion": "/Satoshi:29.0.0/", "connections": 8}) if m == "getbestblockhash": return ok(self.chain.tip_hex()) - if m == "getblockcount": - return ok(len(blocks) - 1) if m == "getblockhash": if not 0 <= p[0] < len(blocks): return err(-8, "Block height out of range") diff --git a/tests/test_node.py b/tests/test_node.py index 44cae6b..195dc01 100644 --- a/tests/test_node.py +++ b/tests/test_node.py @@ -8,7 +8,7 @@ import unittest from bitcoinmonetaryview.node import rpc as rpcmod -from bitcoinmonetaryview.node.client import Node as _Node +from bitcoinmonetaryview.node.client import Node as _Node, make_node from bitcoinmonetaryview.node.transport import NodeUnreachable, is_local_host, socks5_connect from bitcoinmonetaryview.rules import monetary_rules as mr from tests.mocknode import MockChain, MockNode @@ -142,8 +142,6 @@ def test_rpc_and_rest_blocks_equal(self): raw_rest = n.block(h) self.assertEqual(raw_rpc, raw_rest) self.assertEqual(n.block_hashes(0, 5), [mr.hash_to_hex(b[1]) for b in self.chain.blocks]) - hdrs = n.rest.headers(n.block_hash(1), 3) - self.assertEqual(len(hdrs), 3) finally: node.stop() @@ -242,9 +240,9 @@ def test_plaintext_warning_only_for_real_networks(self): d = tempfile.mkdtemp() try: cli = {"rpc_url": "http://10.0.3.1:58332", "rpc_user": "u", "rpc_password": "p"} - plain = Scanner(Config(d, cli=cli, env={})).make_node() + plain = make_node(Config(d, cli=cli, env={})) self.assertTrue(plain.transport.plaintext_remote) - managed = Scanner(Config(d, cli=cli, env={"BMV_MANAGED_BY": "startos"})).make_node() + managed = make_node(Config(d, cli=cli, env={"BMV_MANAGED_BY": "startos"})) self.assertFalse(managed.transport.plaintext_remote) finally: shutil.rmtree(d) diff --git a/tests/test_rules.py b/tests/test_rules.py index 414347a..f0f6d04 100644 --- a/tests/test_rules.py +++ b/tests/test_rules.py @@ -149,6 +149,14 @@ def test_tampered_witness(self): with self.assertRaisesRegex(mr.BlockInvalid, "witness"): mr.verify_block(res, expected_hash=h) + def test_not_connecting_is_its_own_error(self): + """S10: the scanner tells "does not connect" (a reorganisation) from bad data by type, not by text.""" + raw, h = bg.mixed_block(800000) + res = mr.analyze_block(raw, 800000) + with self.assertRaises(mr.BlockNotConnected): + mr.verify_block(res, expected_hash=h, expected_prev=b"\x22" * 32) + self.assertTrue(issubclass(mr.BlockNotConnected, mr.BlockInvalid)) + def test_wrong_parent(self): raw, h = bg.mixed_block(800000, prev=b"\x22" * 32) res = mr.analyze_block(raw, 800000) diff --git a/tests/test_scanner.py b/tests/test_scanner.py index e0c2ff8..78be55b 100644 --- a/tests/test_scanner.py +++ b/tests/test_scanner.py @@ -821,12 +821,12 @@ def test_disconnect_restores_bloom_entries(self): st.apply_block_utxo(2, r2, bloom) st.put_block(2, r2, True) st.commit() - self.assertEqual(st.spam_utxo_count(), 0) + self.assertEqual(st.db.execute("SELECT COALESCE(SUM(count),0) FROM utxo_hist").fetchone()[0], 0) fresh = Bloom(1) # as if rebuilt after a restart st.begin() st.disconnect_block(2, fresh) st.commit() - self.assertEqual(st.spam_utxo_count(), len(spam)) + self.assertEqual(st.db.execute("SELECT COALESCE(SUM(count),0) FROM utxo_hist").fetchone()[0], len(spam)) self.assertTrue(all(fresh.maybe(t, v) for t, v, *_ in spam)) st.close() finally: diff --git a/tests/test_server.py b/tests/test_server.py index 6565357..53b0797 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -14,6 +14,7 @@ from bitcoinmonetaryview.analytics import csv_safe from bitcoinmonetaryview.config import Config from bitcoinmonetaryview.scanner import Status +from bitcoinmonetaryview.node.client import make_node from bitcoinmonetaryview.server import host_allowed, make_server ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -385,9 +386,9 @@ def test_umbrel_mode(self): def test_internal_rpc_over_http_is_trusted(self): from bitcoinmonetaryview.scanner import Scanner - self.assertFalse(Scanner(self.config).make_node().transport.plaintext_remote) + self.assertFalse(make_node(self.config).transport.plaintext_remote) plain = Config(self.dir, cli={"rpc_url": "http://10.21.21.8:8332", "rpc_user": "u", "rpc_password": "p"}, env={}) - self.assertTrue(Scanner(plain).make_node().transport.plaintext_remote) + self.assertTrue(make_node(plain).transport.plaintext_remote) class OnDemandLookup(ServerTest): @@ -810,3 +811,37 @@ def test_connections_beyond_the_cap_are_closed(self): r, _ = self.req("GET", "/api/health") self.assertEqual(r.status, 200) idle[1].close() + + +@unittest.skipUnless(shutil.which("openssl"), "openssl not installed") +class BuiltInTLS(unittest.TestCase): + """S5: the web interface over https with tls_cert/tls_key, as the README recommends for LAN use.""" + + def test_serves_https_only(self): + import ssl + import subprocess + d = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, d) + subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "1", "-subj", + "/CN=localhost", "-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1", + "-keyout", "key.pem", "-out", "cert.pem"], cwd=d, check=True, capture_output=True) + port = free_port() + cfg = Config(d, cli={"port": str(port), "tls_cert": os.path.join(d, "cert.pem"), + "tls_key": os.path.join(d, "key.pem")}, env={}) + srv = make_server(cfg, StubScanner()) + threading.Thread(target=srv.serve_forever, daemon=True).start() + self.addCleanup(srv.server_close) + self.addCleanup(srv.shutdown) + ctx = ssl.create_default_context(cafile=os.path.join(d, "cert.pem")) + c = http.client.HTTPSConnection("127.0.0.1", port, context=ctx, timeout=10) + c.request("GET", "/api/health", headers={"Host": f"127.0.0.1:{port}"}) + r = c.getresponse() + self.assertEqual(r.status, 200) + self.assertTrue(json.loads(r.read())["ok"]) + self.assertGreaterEqual(c.sock.version(), "TLSv1.2") + c.close() + plain = http.client.HTTPConnection("127.0.0.1", port, timeout=5) + with self.assertRaises((http.client.HTTPException, ConnectionError, OSError)): + plain.request("GET", "/api/health") + plain.getresponse() + plain.close() diff --git a/tests/test_store_fs.py b/tests/test_store_fs.py index d1b474f..6ed7da2 100644 --- a/tests/test_store_fs.py +++ b/tests/test_store_fs.py @@ -82,8 +82,7 @@ def test_store_marks_its_network_directory(self): seen = [] with mock.patch.object(store, "no_cow", side_effect=seen.append): store.Store(os.path.join(self.dir, "mainnet", "bmv.sqlite")).close() - store.Store(os.path.join(self.dir, "mainnet", "bmv.sqlite"), readonly=True).db.close() - self.assertEqual(seen, [os.path.join(self.dir, "mainnet")]) # the writer only + self.assertEqual(seen, [os.path.join(self.dir, "mainnet")]) @unittest.skipUnless(BTRFS_DIR, "no btrfs test directory (set BMV_BTRFS_DIR)")