From 3a083d8ae7e8e273d157ad4b400b496073072fa5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 13:50:59 +0000 Subject: [PATCH] Release 0.3.14: a missing cookie after a reboot is waiting for the node Right after a reboot the node has not written its RPC cookie file yet. The app showed that as a red "Authentication problem" until the 30 s retry connected. - rpc: a cookie file that does not exist raises CookieMissing; other read errors stay authentication errors, and a refused cookie stays one too. - scanner: CookieMissing shows "Waiting for the node to write its RPC cookie file ()" in the waiting_node phase and checks again every 10 s. - connection test: a warning that the node may still be starting. - New texts in all five languages; version 0.3.14; changelog; CLAUDE.md state and Start9's current release-notes format. Tests written first: the missing-cookie and connection-test cases failed against the old behaviour; the refused-cookie case guards the red state. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 +++ CLAUDE.md | 26 +++++------ bitcoinmonetaryview/__init__.py | 2 +- bitcoinmonetaryview/diagnostics.py | 6 ++- bitcoinmonetaryview/node/rpc.py | 8 +++- bitcoinmonetaryview/scanner.py | 6 ++- bitcoinmonetaryview/static/i18n/de.js | 4 ++ bitcoinmonetaryview/static/i18n/es.js | 4 ++ bitcoinmonetaryview/static/i18n/fr.js | 4 ++ bitcoinmonetaryview/static/i18n/pl.js | 4 ++ tests/test_scanner.py | 64 +++++++++++++++++++++++++++ 11 files changed, 116 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ae033e2..0c64d64 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ All notable changes are documented here. This project uses [semantic versioning](https://semver.org/). +## [0.3.14] — 2026-11-10 + +- **After a reboot:** while the node has not yet written its RPC cookie file, the app now shows "Waiting for + the node to write its RPC cookie file" (with the file's path) instead of a red "Authentication problem", + and checks again every 10 seconds. A cookie the node refuses is still shown as an authentication problem. + The connection test says the node may still be starting. + ## [0.3.13] — 2026-11-10 - **A damaged `settings.json` no longer switches the web login off or deletes the scan results.** Until now a diff --git a/CLAUDE.md b/CLAUDE.md index 213ed40..c3712f6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -100,9 +100,10 @@ Practical notes from the first releases through the fork: back once Roots is on community-prod and tested against the Roots package on StartOS. The app itself and its README may name Roots. - `next` in our StartOS workspace is a copy of Start9-Community's own `next` branch; leave it (not ours). -- Release notes follow the guide's format: "Updated Monetary View to X.Y.Z." then short bullets - (New/Fix/Internal), then a link to the GitHub release, in all five languages (FR: no-break space before - ":" and ";"). +- Release notes follow the guide (`versions.md`): "Updated Monetary View to X.Y.Z.", then bullets under bold + headers once several categories are covered (**Security**, **Changes**, **Fixes**; localized), then a link + to the GitHub release, in all five languages (FR: no-break space before ":" and ";"). Only what users + observe: no mechanism, no internal package changes, no defect history. ## Umbrel official App Store @@ -131,19 +132,14 @@ Practical notes from the first releases through the fork: ## State (2026-11-10) -App 0.3.13 merged on `main` (fixes from a full code and security review: a damaged settings.json fails safe, +App v0.3.14 (0.3.13: fixes from a full code and security review — a damaged settings.json fails safe, weekly instead of daily gettxoutsetinfo, mutated-block check, request handling, actions pinned by commit, -unused code removed); `release.yml` not run yet. Released: v0.3.12. StartOS 0.3.12:0 in the Community Registry -and on Community Beta, Bitcoin category set (Start9 promoted it on its own within hours of merging #7; -promotion issue #8 closed). The maintainer's server runs StartOS 0.4.2 with Knots 29.3. Umbrel community store -0.3.12; official Umbrel App Store getumbrel/umbrel-apps#6328 at 0.3.12, waiting for review. Open: release -0.3.13 and the package updates (StartOS: exclude `..nocow`/`..old` from backups, mention the weekly -UTXO-size request in the descriptions); the Umbrel review; Roots wording once Roots is on community-prod. - -Idea for a later release (maintainer: "maybe later", not now): a missing RPC cookie file right after a -reboot (the node has not written it yet) shows as a red "Authentication problem" until the 30 s retry -connects; show it as waiting for the node instead (`scanner.py` NodeAuthError, `node/rpc.py`), keeping red -for wrong credentials. +unused code removed; 0.3.14: a missing cookie after a reboot shows as waiting for the node). StartOS +0.3.12:0 in the Community Registry and on Community Beta, Bitcoin category set (Start9 promoted it on its own +within hours of merging #7; promotion issue #8 closed). StartOS 0.3.14:0 in preparation (0.3.13:0 was only a +test build, never submitted). The maintainer's server runs StartOS 0.4.2 with Knots 29.3. Umbrel community +store 0.3.12; official Umbrel App Store getumbrel/umbrel-apps#6328 at 0.3.12, waiting for review. Open: the +Start9 PR for 0.3.14:0, then Umbrel; the Umbrel review; Roots wording once Roots is on community-prod. Lessons from 0.3.10:1-0.3.12: a StartOS user's btrfs data drive went read-only during a first full scan (fsync of a fragmented copy-on-write SQLite file). The app now creates its per-network directory diff --git a/bitcoinmonetaryview/__init__.py b/bitcoinmonetaryview/__init__.py index 3987491..92d3966 100644 --- a/bitcoinmonetaryview/__init__.py +++ b/bitcoinmonetaryview/__init__.py @@ -1,3 +1,3 @@ """BitcoinMonetaryView: see how much spam your Bitcoin node stores, based on the Monetary Node rules.""" -__version__ = "0.3.13" +__version__ = "0.3.14" diff --git a/bitcoinmonetaryview/diagnostics.py b/bitcoinmonetaryview/diagnostics.py index 4e10cc4..3fa240c 100644 --- a/bitcoinmonetaryview/diagnostics.py +++ b/bitcoinmonetaryview/diagnostics.py @@ -4,7 +4,7 @@ import time from .node.client import make_node -from .node.rpc import NodeAuthError, NodeError, RPCError +from .node.rpc import CookieMissing, NodeAuthError, NodeError, RPCError from .node.transport import NodeUnreachable @@ -30,6 +30,10 @@ def add(name, status, message, hint=""): ms = (time.monotonic() - t0) * 1000 add("Reachable", "ok", f"Connected to {t.describe()} ({ms:.0f} ms)") add("Authentication", "ok", "RPC credentials accepted") + except CookieMissing as e: + add("Authentication", "warn", str(e), + "The node writes this file when it starts, so it may still be starting. If it is running, check rpc_cookie_file.") + return checks except NodeAuthError as e: add("Authentication", "fail", str(e), "Check rpc_user/rpc_password, or point rpc_cookie_file to the node's .cookie file. " diff --git a/bitcoinmonetaryview/node/rpc.py b/bitcoinmonetaryview/node/rpc.py index 5af5565..3f381c0 100644 --- a/bitcoinmonetaryview/node/rpc.py +++ b/bitcoinmonetaryview/node/rpc.py @@ -22,6 +22,10 @@ class RPCForbidden(NodeError): """A call outside the read-only whitelist was attempted (never sent).""" +class CookieMissing(NodeError): + """The cookie file does not exist (yet): the node writes it when it starts.""" + + class RPCError(NodeError): def __init__(self, code, message, method=""): super().__init__(f"{method}: {message} (code {code})" if method else f"{message} (code {code})") @@ -101,6 +105,8 @@ def _auth(self, reload=False): if self._cookie_file: try: cred = read_cookie(self._cookie_file) + except FileNotFoundError: + raise CookieMissing(f"RPC cookie file {self._cookie_file} does not exist yet") from None except OSError as e: raise NodeAuthError(f"cannot read RPC cookie file: {e.strerror}") from None else: @@ -167,5 +173,5 @@ def close(self): self.transport.close() -__all__ = ["RPCClient", "RPCError", "RPCForbidden", "NodeError", "NodeAuthError", +__all__ = ["RPCClient", "RPCError", "RPCForbidden", "NodeError", "NodeAuthError", "CookieMissing", "NodeUnreachable", "check_allowed", "ALLOWED", "RPC_IN_WARMUP"] diff --git a/bitcoinmonetaryview/scanner.py b/bitcoinmonetaryview/scanner.py index 750b994..566bfaf 100644 --- a/bitcoinmonetaryview/scanner.py +++ b/bitcoinmonetaryview/scanner.py @@ -18,7 +18,7 @@ from . import __version__ from .node.client import default_dust_start, make_node, network_name -from .node.rpc import RPC_IN_WARMUP, NodeAuthError, NodeError, RPCError +from .node.rpc import RPC_IN_WARMUP, CookieMissing, NodeAuthError, NodeError, RPCError from .node.transport import NodeUnreachable from .rules import UPSTREAM_COMMIT from .rules import monetary_rules as mr @@ -258,6 +258,10 @@ def run(self): self.status.set(phase="error", detail=str(e), last_error=str(e)) self.status.event("error", str(e)) self.sleep(60) + except CookieMissing: + self.status.set(phase="waiting_node", detail=f"Waiting for the node to write its RPC cookie file " + f"({self.config.rpc_cookie_file})") + self.sleep(10) except NodeAuthError as e: self.status.set(phase="error", detail=str(e), last_error=str(e)) self.status.event("error", f"Authentication problem: {e}") diff --git a/bitcoinmonetaryview/static/i18n/de.js b/bitcoinmonetaryview/static/i18n/de.js index d24dd7a..79c70e5 100644 --- a/bitcoinmonetaryview/static/i18n/de.js +++ b/bitcoinmonetaryview/static/i18n/de.js @@ -441,6 +441,8 @@ "Check rpc_user/rpc_password, or point rpc_cookie_file to the node's .cookie file. On Start9 the RPC credentials are shown in the Bitcoin Core/Knots/Roots service's properties.": "Prüfe rpc_user/rpc_password oder lass rpc_cookie_file auf die .cookie-Datei des Nodes zeigen. Auf Start9 stehen die RPC-Zugangsdaten in den Eigenschaften des Bitcoin-Core-/Knots-/Roots-Dienstes.", "The node may still be starting up. Try again in a minute.": "Der Node startet vielleicht noch. Versuche es in einer Minute erneut.", + "The node writes this file when it starts, so it may still be starting. If it is running, check rpc_cookie_file.": + "Der Node schreibt diese Datei beim Start, er startet also vielleicht noch. Wenn er läuft, prüfe rpc_cookie_file.", "Scanning starts automatically once the node is fully synced.": "Das Scannen startet automatisch, sobald der Node vollständig synchronisiert ist.", "Node is fully synced": "Node ist vollständig synchronisiert", "Block statistics cover the available range only; the exact spam UTXO figure needs a non-pruned node.": @@ -487,6 +489,7 @@ [/^Loading spent-output filter: ([\d,]+) entries$/, (m, n) => `Lade Filter für ausgegebene Outputs: ${N(n)} Einträge`], [/^Spent-output filter loaded \(([\d,]+) spam outputs\)$/, (m, n) => `Filter für ausgegebene Outputs geladen (${N(n)} Spam-Outputs)`], [/^Your node is still syncing \(([\d.]+) %\)\. Scanning starts when it is done\.$/, (m, p) => `Dein Node synchronisiert noch (${N(p)} %). Das Scannen startet, sobald er fertig ist.`], + [/^Waiting for the node to write its RPC cookie file \((.+)\)$/, (m, p) => `Warte darauf, dass der Node seine RPC-Cookie-Datei schreibt (${p})`], [/^History scan runs daily (.+) \((.+)\)\. New blocks are still shown\.$/, (m, w, tz) => `Der Scan der Historie läuft täglich ${w} (${tz}). Neue Blöcke werden weiterhin angezeigt.`], [/^History scan runs daily (.+) \((.+)\)\.$/, (m, w, tz) => `Der Scan der Historie läuft täglich ${w} (${tz}).`], [/^The scan database was written by a newer version of Monetary View \(schema (\d+), this version knows (\d+)\)\. It is left as it is: update the app, or delete the database to scan again\.$/, (m, a, b) => `Die Scan-Datenbank wurde von einer neueren Version von Monetary View geschrieben (Schema ${a}, diese Version kennt ${b}). Sie bleibt unverändert: Aktualisiere die App oder lösche die Datenbank, um neu zu scannen.`], @@ -511,6 +514,7 @@ [/^UTXO set: ([\d,]+) entries$/, (m, n) => `UTXO-Set: ${N(n)} Einträge`], [/^Could not read the UTXO set size \((.+)\); will retry later$/s, (m, e) => `Größe des UTXO-Sets konnte nicht gelesen werden (${e}); neuer Versuch später`], // connection test + [/^RPC cookie file (.+) does not exist yet$/, (m, p) => `RPC-Cookie-Datei ${p} existiert noch nicht`], [/^Connected to (\S+) \((\d+) ms\)$/, (m, u, ms) => `Verbunden mit ${u} (${ms} ms)`], [/^Node answered with an error: (.+)$/s, (m, e) => `Node antwortete mit einem Fehler: ${e}`], [/^Chain: (\S+), height ([\d,]+)$/, (m, c, h) => `Chain: ${c}, Höhe ${N(h)}`], diff --git a/bitcoinmonetaryview/static/i18n/es.js b/bitcoinmonetaryview/static/i18n/es.js index 2453cee..76fd112 100644 --- a/bitcoinmonetaryview/static/i18n/es.js +++ b/bitcoinmonetaryview/static/i18n/es.js @@ -492,6 +492,8 @@ "Check rpc_user/rpc_password, or point rpc_cookie_file to the node's .cookie file. On Start9 the RPC credentials are shown in the Bitcoin Core/Knots/Roots service's properties.": "Comprueba rpc_user/rpc_password o haz que rpc_cookie_file apunte al archivo .cookie del nodo. En Start9, las credenciales RPC aparecen en las propiedades del servicio Bitcoin Core/Knots/Roots.", "The node may still be starting up. Try again in a minute.": "Puede que el nodo aún se esté iniciando. Vuelve a intentarlo en un minuto.", + "The node writes this file when it starts, so it may still be starting. If it is running, check rpc_cookie_file.": + "El nodo escribe este archivo al arrancar, así que quizá aún esté arrancando. Si ya funciona, revisa rpc_cookie_file.", "Scanning starts automatically once the node is fully synced.": "El escaneo empieza automáticamente cuando el nodo esté totalmente sincronizado.", "Node is fully synced": "El nodo está totalmente sincronizado", "Block statistics cover the available range only; the exact spam UTXO figure needs a non-pruned node.": @@ -538,6 +540,7 @@ [/^Loading spent-output filter: ([\d,]+) entries$/, (m, n) => `Cargando el filtro de outputs gastados: ${N(n)} entradas`], [/^Spent-output filter loaded \(([\d,]+) spam outputs\)$/, (m, n) => `Filtro de outputs gastados cargado (${N(n)} outputs de spam)`], [/^Your node is still syncing \(([\d.]+) %\)\. Scanning starts when it is done\.$/, (m, p) => `Tu nodo aún se está sincronizando (${N(p)} %). El escaneo empieza cuando termine.`], + [/^Waiting for the node to write its RPC cookie file \((.+)\)$/, (m, p) => `Esperando a que el nodo escriba su archivo de cookie RPC (${p})`], [/^History scan runs daily (.+) \((.+)\)\. New blocks are still shown\.$/, (m, w, tz) => `El escaneo del historial funciona a diario ${w} (${tz}). Los bloques nuevos se siguen mostrando.`], [/^History scan runs daily (.+) \((.+)\)\.$/, (m, w, tz) => `El escaneo del historial funciona a diario ${w} (${tz}).`], [/^The scan database was written by a newer version of Monetary View \(schema (\d+), this version knows (\d+)\)\. It is left as it is: update the app, or delete the database to scan again\.$/, (m, a, b) => `La base de datos del escaneo la escribió una versión más reciente de Monetary View (esquema ${a}; esta versión conoce el ${b}). Se deja tal cual: actualiza la aplicación o borra la base de datos para escanear de nuevo.`], @@ -562,6 +565,7 @@ [/^UTXO set: ([\d,]+) entries$/, (m, n) => `Conjunto UTXO: ${N(n)} entradas`], [/^Could not read the UTXO set size \((.+)\); will retry later$/s, (m, e) => `No se pudo leer el tamaño del conjunto UTXO (${e}); se reintentará más tarde`], // connection test + [/^RPC cookie file (.+) does not exist yet$/, (m, p) => `El archivo de cookie RPC ${p} aún no existe`], [/^Connected to (\S+) \((\d+) ms\)$/, (m, u, ms) => `Conectado con ${u} (${ms} ms)`], [/^Node answered with an error: (.+)$/s, (m, e) => `El nodo respondió con un error: ${e}`], [/^Chain: (\S+), height ([\d,]+)$/, (m, c, h) => `Cadena: ${c}, altura ${N(h)}`], diff --git a/bitcoinmonetaryview/static/i18n/fr.js b/bitcoinmonetaryview/static/i18n/fr.js index ae2bd2f..173f8b4 100644 --- a/bitcoinmonetaryview/static/i18n/fr.js +++ b/bitcoinmonetaryview/static/i18n/fr.js @@ -491,6 +491,8 @@ "Check rpc_user/rpc_password, or point rpc_cookie_file to the node's .cookie file. On Start9 the RPC credentials are shown in the Bitcoin Core/Knots/Roots service's properties.": "Vérifiez rpc_user/rpc_password, ou faites pointer rpc_cookie_file vers le fichier .cookie du nœud. Sur Start9, les identifiants RPC figurent dans les propriétés du service Bitcoin Core/Knots/Roots.", "The node may still be starting up. Try again in a minute.": "Le nœud est peut-être encore en train de démarrer. Réessayez dans une minute.", + "The node writes this file when it starts, so it may still be starting. If it is running, check rpc_cookie_file.": + "Le nœud écrit ce fichier au démarrage, il est donc peut-être encore en train de démarrer. S’il tourne, vérifiez rpc_cookie_file.", "Scanning starts automatically once the node is fully synced.": "L’analyse démarre automatiquement dès que le nœud est entièrement synchronisé.", "Node is fully synced": "Le nœud est entièrement synchronisé", "Block statistics cover the available range only; the exact spam UTXO figure needs a non-pruned node.": @@ -537,6 +539,7 @@ [/^Loading spent-output filter: ([\d,]+) entries$/, (m, n) => `Chargement du filtre des outputs dépensés : ${N(n)} entrées`], [/^Spent-output filter loaded \(([\d,]+) spam outputs\)$/, (m, n) => `Filtre des outputs dépensés chargé (${N(n)} outputs de spam)`], [/^Your node is still syncing \(([\d.]+) %\)\. Scanning starts when it is done\.$/, (m, p) => `Votre nœud est encore en cours de synchronisation (${N(p)} %). L’analyse démarrera une fois terminé.`], + [/^Waiting for the node to write its RPC cookie file \((.+)\)$/, (m, p) => `En attente que le nœud écrive son fichier cookie RPC (${p})`], [/^History scan runs daily (.+) \((.+)\)\. New blocks are still shown\.$/, (m, w, tz) => `L’analyse de l’historique tourne chaque jour ${w} (${tz}). Les nouveaux blocs restent affichés.`], [/^History scan runs daily (.+) \((.+)\)\.$/, (m, w, tz) => `L’analyse de l’historique tourne chaque jour ${w} (${tz}).`], [/^The scan database was written by a newer version of Monetary View \(schema (\d+), this version knows (\d+)\)\. It is left as it is: update the app, or delete the database to scan again\.$/, (m, a, b) => `La base de données d’analyse a été écrite par une version plus récente de Monetary View (schéma ${a}, cette version connaît le ${b}). Elle est laissée telle quelle : mettez l’application à jour ou supprimez la base de données pour relancer l’analyse.`], @@ -561,6 +564,7 @@ [/^UTXO set: ([\d,]+) entries$/, (m, n) => `Ensemble UTXO : ${N(n)} entrées`], [/^Could not read the UTXO set size \((.+)\); will retry later$/s, (m, e) => `Impossible de lire la taille de l’ensemble UTXO (${e}) ; nouvel essai plus tard`], // connection test + [/^RPC cookie file (.+) does not exist yet$/, (m, p) => `Le fichier cookie RPC ${p} n’existe pas encore`], [/^Connected to (\S+) \((\d+) ms\)$/, (m, u, ms) => `Connecté à ${u} (${ms} ms)`], [/^Node answered with an error: (.+)$/s, (m, e) => `Le nœud a répondu par une erreur : ${e}`], [/^Chain: (\S+), height ([\d,]+)$/, (m, c, h) => `Chaîne : ${c}, hauteur ${N(h)}`], diff --git a/bitcoinmonetaryview/static/i18n/pl.js b/bitcoinmonetaryview/static/i18n/pl.js index 872abd4..3490193 100644 --- a/bitcoinmonetaryview/static/i18n/pl.js +++ b/bitcoinmonetaryview/static/i18n/pl.js @@ -491,6 +491,8 @@ "Check rpc_user/rpc_password, or point rpc_cookie_file to the node's .cookie file. On Start9 the RPC credentials are shown in the Bitcoin Core/Knots/Roots service's properties.": "Sprawdź rpc_user/rpc_password albo ustaw rpc_cookie_file na plik .cookie węzła. Na Start9 dane logowania RPC są pokazane we właściwościach usługi Bitcoin Core/Knots/Roots.", "The node may still be starting up. Try again in a minute.": "Węzeł może się jeszcze uruchamiać. Spróbuj ponownie za minutę.", + "The node writes this file when it starts, so it may still be starting. If it is running, check rpc_cookie_file.": + "Węzeł zapisuje ten plik przy starcie, więc może jeszcze się uruchamiać. Jeśli działa, sprawdź rpc_cookie_file.", "Scanning starts automatically once the node is fully synced.": "Skanowanie zacznie się automatycznie, gdy węzeł będzie w pełni zsynchronizowany.", "Node is fully synced": "Węzeł jest w pełni zsynchronizowany", "Block statistics cover the available range only; the exact spam UTXO figure needs a non-pruned node.": @@ -542,6 +544,7 @@ [/^Spent-output filter loaded \(([\d,]+) spam outputs\)$/, (m, n) => `Filtr wydanych wyjść wczytany (${N(n)} ${F(n, "wyjście", "wyjścia", "wyjść")} spamu)`], [/^Your node is still syncing \(([\d.]+) %\)\. Scanning starts when it is done\.$/, (m, p) => `Twój węzeł wciąż się synchronizuje (${N(p)} %). Skanowanie zacznie się, gdy skończy.`], + [/^Waiting for the node to write its RPC cookie file \((.+)\)$/, (m, p) => `Czekam, aż węzeł zapisze swój plik cookie RPC (${p})`], [/^History scan runs daily (.+) \((.+)\)\. New blocks are still shown\.$/, (m, w, tz) => `Skanowanie historii działa codziennie ${w} (${tz}). Nowe bloki są nadal pokazywane.`], [/^History scan runs daily (.+) \((.+)\)\.$/, (m, w, tz) => `Skanowanie historii działa codziennie ${w} (${tz}).`], [/^The scan database was written by a newer version of Monetary View \(schema (\d+), this version knows (\d+)\)\. It is left as it is: update the app, or delete the database to scan again\.$/, (m, a, b) => `Bazę danych skanowania zapisała nowsza wersja Monetary View (schemat ${a}, ta wersja zna ${b}). Pozostaje bez zmian: zaktualizuj aplikację albo usuń bazę danych, aby skanować od nowa.`], @@ -568,6 +571,7 @@ [/^UTXO set: ([\d,]+) entries$/, (m, n) => `Zbiór UTXO: ${N(n)} ${F(n, "wpis", "wpisy", "wpisów")}`], [/^Could not read the UTXO set size \((.+)\); will retry later$/s, (m, e) => `Nie udało się odczytać rozmiaru zbioru UTXO (${e}); ponowna próba później`], // connection test + [/^RPC cookie file (.+) does not exist yet$/, (m, p) => `Plik cookie RPC ${p} jeszcze nie istnieje`], [/^Connected to (\S+) \((\d+) ms\)$/, (m, u, ms) => `Połączono z ${u} (${ms} ms)`], [/^Node answered with an error: (.+)$/s, (m, e) => `Węzeł odpowiedział błędem: ${e}`], [/^Chain: (\S+), height ([\d,]+)$/, (m, c, h) => `Łańcuch: ${c}, wysokość ${N(h)}`], diff --git a/tests/test_scanner.py b/tests/test_scanner.py index 78be55b..dc49936 100644 --- a/tests/test_scanner.py +++ b/tests/test_scanner.py @@ -1187,3 +1187,67 @@ def test_history_query_runs_once(self): a.history() a.trends() self.assertEqual(h.call_count, 1) + + +class CookieNotWrittenYet(unittest.TestCase): + """Right after a reboot the node has not written its cookie file yet: that is waiting for the node, not + an authentication problem. A cookie the node refuses is still one.""" + + def setUp(self): + self.dir = tempfile.mkdtemp() + self.cookie = os.path.join(self.dir, ".cookie") + self.chain = MockChain() + self.chain.build(5) + self.node = MockNode(self.chain, cookie_path=self.cookie) + self.scanners = [] + + def tearDown(self): + for s in self.scanners: + s.stop() + s.join(10) + self.node.stop() + shutil.rmtree(self.dir) + + def start(self): + cfg = Config(os.path.join(self.dir, "data"), cli={"rpc_url": self.node.url, "rpc_cookie_file": self.cookie, + "quick_pass_blocks": "0", "sample_every": "0"}, env={}) + s = Scanner(cfg) + self.scanners.append(s) + s.start() + return s + + def wait(self, s, phase, timeout=30): + t = time.time() + while time.time() - t < timeout: + if s.status.get("phase") == phase: + return + time.sleep(0.05) + self.fail(f"phase {phase} not reached: {s.status.snapshot()}") + + def test_missing_cookie_is_waiting_for_the_node(self): + os.unlink(self.cookie) + s = self.start() + self.wait(s, "waiting_node") + self.assertIn("cookie", s.status.get("detail")) + self.assertIn(self.cookie, s.status.get("detail")) # a wrong path shows up here + time.sleep(0.5) + self.assertEqual(s.status.get("phase"), "waiting_node") + self.assertNotIn("Authentication problem", " ".join(e["message"] for e in s.status.snapshot()["activity"])) + self.node.rotate_cookie() # the node has started and written it + s.wake.set() + self.wait(s, "live") + + def test_refused_cookie_is_still_an_authentication_problem(self): + with open(self.cookie, "w") as f: + f.write("__cookie__:wrong") + s = self.start() + self.wait(s, "error") + self.assertIn("Authentication problem", " ".join(e["message"] for e in s.status.snapshot()["activity"])) + + def test_connection_test_says_the_node_may_be_starting(self): + from bitcoinmonetaryview.diagnostics import run_connection_test + os.unlink(self.cookie) + cfg = Config(os.path.join(self.dir, "data"), cli={"rpc_url": self.node.url, "rpc_cookie_file": self.cookie}, env={}) + checks = {c["name"]: c for c in run_connection_test(cfg)} + self.assertEqual(checks["Authentication"]["status"], "warn") + self.assertIn("starts", checks["Authentication"]["hint"])