Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
8 changes: 2 additions & 6 deletions bitcoinmonetaryview/__main__.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,25 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Entry point: python3 -m bitcoinmonetaryview"""

import json
import logging
import os
import signal
import sys
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):
args = build_arg_parser().parse_args(argv)
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:
Expand Down
89 changes: 29 additions & 60 deletions bitcoinmonetaryview/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down Expand Up @@ -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])
Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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
7 changes: 3 additions & 4 deletions bitcoinmonetaryview/diagnostics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 17 additions & 12 deletions bitcoinmonetaryview/node/client.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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()
Expand All @@ -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:
Expand Down
22 changes: 0 additions & 22 deletions bitcoinmonetaryview/node/rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
from .transport import NodeError, Transport

_HEX64 = re.compile(r"^[0-9a-f]{64}$")
MAX_HEADERS = 2000


def _check_hash(h):
Expand All @@ -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."""
Expand All @@ -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)]
1 change: 0 additions & 1 deletion bitcoinmonetaryview/node/rpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)),
Expand Down
1 change: 0 additions & 1 deletion bitcoinmonetaryview/rules/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,3 @@

UPSTREAM_REPO = "https://github.com/sambitcoin/BitcoinMonetaryNode"
UPSTREAM_COMMIT = "492539256d43151973cb4cdf73c91d67c4be203c"
UPSTREAM_DATE = "2026-09-24"
6 changes: 5 additions & 1 deletion bitcoinmonetaryview/rules/monetary_rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
"""
Expand Down Expand Up @@ -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")
Expand Down
Loading
Loading