4 Commits
Author SHA1 Message Date
davideandClaude Sonnet 5.5 264441f5d6 Align docs with the code: stale columns, B-92 health threshold, duplicates
- modello-dati: drop 'da implementare' from fields B-73/B-80/B-82/B-85 shipped
  and the stale B-76 note; limiti-noti: remove a duplicated paragraph
- /health/ready threshold 360s -> 1800s in the spec (B-92, not yet built): with
  120s blocks 360s misfires ~5% of the time (e^-3)
- storico-bug/CLAUDE.md/README: register B-99, B-100, test count 698

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-18 00:32:24 +02:00
davideandClaude Sonnet 5.5 cef05943f9 Keep the fee-rate ceiling below the node's maxfeerate (B-100)
MAX_FEE_RATE_SAT_VB was exactly sendrawtransaction's default maxfeerate
(10 000 sat/vB); with vsize estimated upwards a rate at the ceiling would be
refused. Now 5 000.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-18 00:32:24 +02:00
davideandClaude Sonnet 5.5 2c0e71a74c Refuse an Electrum server that is not on the PLM chain (B-99, ELC-30)
PLM shares Bitcoin's genesis and powLimit, so a Bitcoin server passed every
header check. connect() now asks server.features and requires PLM's genesis.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-18 00:32:24 +02:00
davideandClaude Sonnet 5.5 1433813ec7 Install SQLAlchemy's asyncio extra so greenlet ships in the image
A clean `pip install .` in the Docker image left out greenlet, so
`alembic upgrade head` crashed on import of sqlalchemy.ext.asyncio and
the container restart-looped.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-17 16:29:21 +02:00
16 changed files with 109 additions and 38 deletions

No files matched your search

+1 -1
View File
@@ -142,7 +142,7 @@ digest-pinned base images, the Fernet key mounted as a file rather than an env v
returns only the latest 500 rows unfiltered; registration writes no audit row; the returns only the latest 500 rows unfiltered; registration writes no audit row; the
access log records Caddy's IP; app logs go only to the file. access log records Caddy's IP; app logs go only to the file.
Fix: `GET /health/ready` (Electrum connected, tip age < 360s, scheduler heartbeat < Fix: `GET /health/ready` (Electrum connected, tip age < 1800s, scheduler heartbeat <
30s) used as the container healthcheck; Electrum status in `/admin`; audit filters by 30s) used as the container healthcheck; Electrum status in `/admin`; audit filters by
event type, round, user and time, with pagination; `user_registered` audit row with event type, round, user and time, with pagination; `user_registered` audit row with
index and address; uvicorn proxy headers from Caddy only; logs also to stdout. index and address; uvicorn proxy headers from Caddy only; logs also to stdout.
+3 -2
View File
@@ -8,7 +8,7 @@ The user communicates in Italian in chat — reply to them in Italian. Everythin
## Project status ## Project status
All 10 stages of the original build order are code-complete and unit-tested — 697 tests, all under `tests/unit/` (`tests/integration/` is an empty package). Beyond them: Docker + Caddy deployment, admin dashboard (`/admin`), static test UI (`/`), pending-inclusive balance display, an SSE push channel layered over the original polling, self-service password change + admin password reset, and the reconciliation/corroboration machinery below. All 10 stages of the original build order are code-complete and unit-tested — 698 tests, all under `tests/unit/` (`tests/integration/` is an empty package). Beyond them: Docker + Caddy deployment, admin dashboard (`/admin`), static test UI (`/`), pending-inclusive balance display, an SSE push channel layered over the original polling, self-service password change + admin password reset, and the reconciliation/corroboration machinery below.
Verified on mainnet with real money: registration + address derivation, deposit crediting (at the time, 1-conf; deposits now need `deposit_confirmations`), a real 10 PLM bet (broadcast → confirmed → change credited back), and one full round cycle (close → draw on a real block hash → 70/30 payout with sat math checked against the broadcast tx → confirmation → close → next round auto-opened). **Withdrawal and the RBF bump path have never been exercised against a live broadcast** — unit-tested only. Verified on mainnet with real money: registration + address derivation, deposit crediting (at the time, 1-conf; deposits now need `deposit_confirmations`), a real 10 PLM bet (broadcast → confirmed → change credited back), and one full round cycle (close → draw on a real block hash → 70/30 payout with sat math checked against the broadcast tx → confirmation → close → next round auto-opened). **Withdrawal and the RBF bump path have never been exercised against a live broadcast** — unit-tested only.
@@ -49,7 +49,7 @@ PYTHONPATH=. python scripts/decrypt_master_key.py # ops recovery: decrypt+pr
PYTHONPATH=. python scripts/encrypt_master_key.py # ops bootstrap: import an externally-generated xprv (--overwrite to replace) PYTHONPATH=. python scripts/encrypt_master_key.py # ops bootstrap: import an externally-generated xprv (--overwrite to replace)
PYTHONPATH=. python scripts/electrum_smoke_test.py # manual check: connect, handshake, subscribe to headers, print the tip PYTHONPATH=. python scripts/electrum_smoke_test.py # manual check: connect, handshake, subscribe to headers, print the tip
python -m pytest # all 697 tests python -m pytest # all 698 tests
python -m pytest tests/unit/test_hd.py # one file python -m pytest tests/unit/test_hd.py # one file
python -m pytest tests/unit/test_hd.py::test_derivation_is_deterministic # one test python -m pytest tests/unit/test_hd.py::test_derivation_is_deterministic # one test
``` ```
@@ -160,6 +160,7 @@ One connection serves everything — deposit credits, broadcasts, confirmations,
- **Rotation.** `ELECTRUM_HOST`/`PORT` is primary, `ELECTRUM_FALLBACK_SERVERS` a comma-separated `host:port[:notls][:pin=<sha256>]` list (`client.py:parse_endpoints` rejects malformed entries at startup, not during the outage when the fallback is needed; `pin=` fixes the server's DER certificate hash, `ELECTRUM_CERT_PIN` does the same for the primary, B-84). The server **refuses to start with fewer than 2 fallbacks** (`config.validate_quorum_servers`, B-84; `ALLOW_NO_QUORUM=true` overrides it, development only). After any failed or dropped session the next server is tried immediately; the backoff (1s doubling to 30s) only kicks in once every server has had a turn. - **Rotation.** `ELECTRUM_HOST`/`PORT` is primary, `ELECTRUM_FALLBACK_SERVERS` a comma-separated `host:port[:notls][:pin=<sha256>]` list (`client.py:parse_endpoints` rejects malformed entries at startup, not during the outage when the fallback is needed; `pin=` fixes the server's DER certificate hash, `ELECTRUM_CERT_PIN` does the same for the primary, B-84). The server **refuses to start with fewer than 2 fallbacks** (`config.validate_quorum_servers`, B-84; `ALLOW_NO_QUORUM=true` overrides it, development only). After any failed or dropped session the next server is tried immediately; the backoff (1s doubling to 30s) only kicks in once every server has had a turn.
- **Bounded requests** (`_REQUEST_TIMEOUT_SECONDS` = 15s); a timeout tears the connection down. Unbounded waits used to hang `POST /bets` *while holding the per-user lock*, and could stall the confirmation poller permanently. - **Bounded requests** (`_REQUEST_TIMEOUT_SECONDS` = 15s); a timeout tears the connection down. Unbounded waits used to hang `POST /bets` *while holding the per-user lock*, and could stall the confirmation poller permanently.
- **The drop is observable**: `client.wait_closed()` resolves when the read loop dies, and `_run_once` races it against the notification consumers and a 60s `server.ping`. A server that keeps answering pings but stopped following the chain is caught too (B-86): at every ping, if no header has been *accepted* for 360s (`_STALL_SECONDS`), `_check_not_stalled` asks the other servers for their tip and ends the session with `ServerStalledError` if any is higher, so `run()` rotates; none higher means a quiet chain and the session goes on. Without it the listener sat on queues nobody would ever fill while `listener.client` still looked alive. - **The drop is observable**: `client.wait_closed()` resolves when the read loop dies, and `_run_once` races it against the notification consumers and a 60s `server.ping`. A server that keeps answering pings but stopped following the chain is caught too (B-86): at every ping, if no header has been *accepted* for 360s (`_STALL_SECONDS`), `_check_not_stalled` asks the other servers for their tip and ends the session with `ServerStalledError` if any is higher, so `run()` rotates; none higher means a quiet chain and the session goes on. Without it the listener sat on queues nobody would ever fill while `listener.client` still looked alive.
- **The chain is checked, not just the headers** (B-99, ELC-30): `ElectrumClient.connect` follows `server.version` with `server.features` and refuses a server whose `genesis_hash` is not PLM's. PLM shares Bitcoin's genesis *and* powLimit, so a Bitcoin Electrum server would pass every header check below; this is what tells them apart, for the quorum's connections too.
- **Headers are validated, not trusted** (`_apply_header`, async since B-74): the tip never regresses, a header must meet the difficulty target it claims *and* that target must be no easier than `draw.POW_LIMIT` (PLM's powLimit; `tests/unit/conftest.py` swaps in a regtest limit so tests can mine headers, and the tests of the limit itself put `MAINNET_POW_LIMIT` back), and every advance must be linked to the tip: a single block by its `prev_hash`, a jump by downloading the headers in between (`blockchain.block.headers`, ≤2016 per request) from the active server and checking each. Failure raises `HeaderValidationError`, which ends the session like a dropped connection and rotates away — that header is the draw's only entropy, so a fabricated one picks the winner. The listener keeps the last 10 headers (`_window`, built from the first header plus its 9 predecessors); a header that does not join the tip is a reorg, walked back to its fork point inside the window and followed (`_follow_reorg`), a fork older than the window ends the session. A followed reorg writes `chain_reorg_detected` *before* the window moves (`_record_reorg`, B-85), and a depth of 2 or more pauses the lottery with `paused_reason = 'reorg'` in the same transaction; a header at the tip's own height with a different hash is a reorg too, not ignored. One more header is refused *without* ending the session (B-64): one carrying no `hex` at all (nothing to validate or draw from, and applying the height alone would break the `tip_height`/`tip_header_hex` pairing). `_run_once` separately refuses to publish the client while *no* tip is known, so the ignore-don't-kill choice can't reopen B-63. - **Headers are validated, not trusted** (`_apply_header`, async since B-74): the tip never regresses, a header must meet the difficulty target it claims *and* that target must be no easier than `draw.POW_LIMIT` (PLM's powLimit; `tests/unit/conftest.py` swaps in a regtest limit so tests can mine headers, and the tests of the limit itself put `MAINNET_POW_LIMIT` back), and every advance must be linked to the tip: a single block by its `prev_hash`, a jump by downloading the headers in between (`blockchain.block.headers`, ≤2016 per request) from the active server and checking each. Failure raises `HeaderValidationError`, which ends the session like a dropped connection and rotates away — that header is the draw's only entropy, so a fabricated one picks the winner. The listener keeps the last 10 headers (`_window`, built from the first header plus its 9 predecessors); a header that does not join the tip is a reorg, walked back to its fork point inside the window and followed (`_follow_reorg`), a fork older than the window ends the session. A followed reorg writes `chain_reorg_detected` *before* the window moves (`_record_reorg`, B-85), and a depth of 2 or more pauses the lottery with `paused_reason = 'reorg'` in the same transaction; a header at the tip's own height with a different hash is a reorg too, not ignored. One more header is refused *without* ending the session (B-64): one carrying no `hex` at all (nothing to validate or draw from, and applying the height alone would break the `tip_height`/`tip_header_hex` pairing). `_run_once` separately refuses to publish the client while *no* tip is known, so the ignore-don't-kill choice can't reopen B-63.
- **A quorum corroborates every money-moving decision** (`_corroborate_majority`, 10s per server, asking only the *other* endpoints — never the active one, which is what a MITM controls): `corroborate_header` before a block seeds the draw (B-28), `corroborate_utxo_spent` before a UTXO missing from one `listunspent` is written off as externally spent (B-29), and `corroborate_utxo_credit` before a new outpoint credits a balance — same outpoint, same amount, confirmed (B-59). Balances move in both directions, so both directions need the same quorum — and since B-83 that includes `corroborate_utxo_reinstatement` before a UTXO written off as externally spent is put back (same outpoint, amount, confirmed; `deposits/service.py:find_reinstate_candidates` only reads, `reinstate_reappeared_utxos` writes what the quorum agreed on), and `confirmation_proven` before a tx is marked confirmed: `tx/confirmation.py:poll_once` takes the height the active server reports only as a *claim*, and the row confirms when a strict majority of at least 2 of the *other* servers return a `get_merkle` proof that recomputes to the merkle root of the block's header (`electrum/merkle.py`; the header is the tip we hold, or for an older block the one the quorum agrees on and that meets its own target). With no `network` nothing confirms. Since B-82 the pool-coin check before a payout is on the quorum too (`verify_pool_outpoints`, below). A quorum needs **at least 2 answers** and a strict majority of those that answered (B-84): fewer → returns **False**, since one voice decides nothing independently and an unreachable network proves nothing. Only `ALLOW_NO_QUORUM=true` keeps the old reduced rule (no other server → True, otherwise a majority of whoever answers). A failed credit corroboration only *delays*: `find_new_credit_candidates` re-offers the outpoint on the next refresh or `DepositReconciler` sweep. - **A quorum corroborates every money-moving decision** (`_corroborate_majority`, 10s per server, asking only the *other* endpoints — never the active one, which is what a MITM controls): `corroborate_header` before a block seeds the draw (B-28), `corroborate_utxo_spent` before a UTXO missing from one `listunspent` is written off as externally spent (B-29), and `corroborate_utxo_credit` before a new outpoint credits a balance — same outpoint, same amount, confirmed (B-59). Balances move in both directions, so both directions need the same quorum — and since B-83 that includes `corroborate_utxo_reinstatement` before a UTXO written off as externally spent is put back (same outpoint, amount, confirmed; `deposits/service.py:find_reinstate_candidates` only reads, `reinstate_reappeared_utxos` writes what the quorum agreed on), and `confirmation_proven` before a tx is marked confirmed: `tx/confirmation.py:poll_once` takes the height the active server reports only as a *claim*, and the row confirms when a strict majority of at least 2 of the *other* servers return a `get_merkle` proof that recomputes to the merkle root of the block's header (`electrum/merkle.py`; the header is the tip we hold, or for an older block the one the quorum agrees on and that meets its own target). With no `network` nothing confirms. Since B-82 the pool-coin check before a payout is on the quorum too (`verify_pool_outpoints`, below). A quorum needs **at least 2 answers** and a strict majority of those that answered (B-84): fewer → returns **False**, since one voice decides nothing independently and an unreachable network proves nothing. Only `ALLOW_NO_QUORUM=true` keeps the old reduced rule (no other server → True, otherwise a majority of whoever answers). A failed credit corroboration only *delays*: `find_new_credit_candidates` re-offers the outpoint on the next refresh or `DepositReconciler` sweep.
+1 -1
View File
@@ -62,7 +62,7 @@ python -m pytest # all tests
python -m pytest tests/unit/test_hd.py # one file python -m pytest tests/unit/test_hd.py # one file
``` ```
697 unit tests cover HD derivation, PSBT building, the Electrum client, bets, 698 unit tests cover HD derivation, PSBT building, the Electrum client, bets,
deposits, withdrawals, the round/draw engine, RBF fee-bumping, admin config, deposits, withdrawals, the round/draw engine, RBF fee-bumping, admin config,
the pending-inclusive balance calculation, and the SSE push channel. No the pending-inclusive balance calculation, and the SSE push channel. No
automated integration tests against a live Electrum connection — mainnet automated integration tests against a live Electrum connection — mainnet
+16
View File
@@ -7,6 +7,8 @@ import re
import ssl import ssl
from typing import NamedTuple from typing import NamedTuple
from app.wallet.plm_network import GENESIS_HASH
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -192,6 +194,20 @@ class ElectrumClient:
raise raise
self._read_task = asyncio.create_task(self._read_loop()) self._read_task = asyncio.create_task(self._read_loop())
await self.request("server.version", ["plm-lottery", "1.4"]) await self.request("server.version", ["plm-lottery", "1.4"])
try:
await self._check_genesis()
except ElectrumError:
self._read_task.cancel()
self._writer.close()
raise
async def _check_genesis(self) -> None:
"""The server must be on PLM's chain, not just any chain with valid headers: PLM shares
Bitcoin's genesis and powLimit, so only `server.features` tells them apart (B-99, ELC-30)."""
features = await self.request("server.features")
genesis = features.get("genesis_hash") if isinstance(features, dict) else None
if genesis != GENESIS_HASH:
raise ElectrumError(f"{self.host}:{self.port} is not on the PLM chain (genesis {genesis!r})")
def _check_pin(self) -> None: def _check_pin(self) -> None:
"""The server's DER certificate must hash to the pinned SHA-256 (B-84, ELC-03).""" """The server's DER certificate must hash to the pinned SHA-256 (B-84, ELC-03)."""
+4
View File
@@ -26,3 +26,7 @@ PLM_MAINNET = {
BIP44_COIN_TYPE = 746 BIP44_COIN_TYPE = 746
ACCOUNT_PATH = f"m/84h/{BIP44_COIN_TYPE}h/0h" ACCOUNT_PATH = f"m/84h/{BIP44_COIN_TYPE}h/0h"
# PLM shares Bitcoin's genesis block (palladiumcore chainparams.cpp) and its powLimit, so a
# Bitcoin Electrum server would pass every header check; the handshake asks for this instead.
GENESIS_HASH = "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"
+4 -2
View File
@@ -30,8 +30,10 @@ DUST_LIMIT_SATS = 294
# reason MIN_PASSWORD_LENGTH is shared in auth/security.py) and tx/broadcast.py's RBF # reason MIN_PASSWORD_LENGTH is shared in auth/security.py) and tx/broadcast.py's RBF
# bump escalation, which refuses to bump a pending_transaction past this rate (B-32) — # bump escalation, which refuses to bump a pending_transaction past this rate (B-32) —
# without a ceiling, a stuck transaction's fee climbed by 1 sat/vB every bump forever, # without a ceiling, a stuck transaction's fee climbed by 1 sat/vB every bump forever,
# eating further and further into the sender's change with no limit. # eating further and further into the sender's change with no limit. B-100: half of the node's own
MAX_FEE_RATE_SAT_VB = 10_000 # `sendrawtransaction` maxfeerate (0.1 PLM/kvB = 10 000 sat/vB, palladiumcore rpc/rawtransaction.cpp):
# vsize is estimated upwards, so a rate sitting exactly on the node's limit would be refused.
MAX_FEE_RATE_SAT_VB = 5_000
# Ceiling on how many UTXOs one *user* transaction (bet, withdrawal) may spend (B-48). # Ceiling on how many UTXOs one *user* transaction (bet, withdrawal) may spend (B-48).
# Every extra input costs ~68 vbytes of fee, and that fee comes out of the amount being # Every extra input costs ~68 vbytes of fee, and that fee comes out of the amount being
+4 -4
View File
@@ -50,7 +50,7 @@ esiste una API separata per l'amministrazione, solo un'autenticazione diversa.
| `GET` | `/admin/pending-transactions` | admin | [API-38](#get-adminpending-transactions) | | `GET` | `/admin/pending-transactions` | admin | [API-38](#get-adminpending-transactions) |
| `GET` | `/admin/bug-reports` | admin | [API-39](#get-adminbug-reports) | | `GET` | `/admin/bug-reports` | admin | [API-39](#get-adminbug-reports) |
| `POST` | `/admin/bug-reports/{report_id}/status` | admin | [API-40](#post-adminbug-reportsreport_idstatus) | | `POST` | `/admin/bug-reports/{report_id}/status` | admin | [API-40](#post-adminbug-reportsreport_idstatus) |
| `GET` | `/admin/electrum` | admin | [API-47](#get-adminelectrum) — *da implementare (B-86, B-92)* | | `GET` | `/admin/electrum` | admin | [API-47](#get-adminelectrum) — *da implementare (B-92)* |
| `GET` | `/health` | nessuna | [API-41](#get-health) | | `GET` | `/health` | nessuna | [API-41](#get-health) |
| `GET` | `/health/ready` | nessuna | [API-46](#get-healthready) — *da implementare (B-92)* | | `GET` | `/health/ready` | nessuna | [API-46](#get-healthready) — *da implementare (B-92)* |
| `GET` | `/`, `/admin`, `/guida`, `/report-bug` | nessuna | [API-42](#pagine-e-file-statici) | | `GET` | `/`, `/admin`, `/guida`, `/report-bug` | nessuna | [API-42](#pagine-e-file-statici) |
@@ -770,7 +770,7 @@ dei parametri operativi in
| `bet_amount_sats` | > 0 e ≤ 10 000 000 000 000 (100 000 PLM) | | `bet_amount_sats` | > 0 e ≤ 10 000 000 000 000 (100 000 PLM) |
| `round_duration_seconds` | 30 – 604 800 (7 giorni) | | `round_duration_seconds` | 30 – 604 800 (7 giorni) |
| `round_cooldown_seconds` | 0 – 86 400 | | `round_cooldown_seconds` | 0 – 86 400 |
| `fee_rate_sat_vb` | 1 – 10 000 (`MAX_FEE_RATE_SAT_VB`) | | `fee_rate_sat_vb` | 1 – 5 000 (`MAX_FEE_RATE_SAT_VB`) |
| `rbf_timeout_seconds` | 60 – 604 800 | | `rbf_timeout_seconds` | 60 – 604 800 |
| `draw_animation_seconds` | 0 – 600 | | `draw_animation_seconds` | 0 – 600 |
| `deposit_confirmations` | 1 – 100 | | `deposit_confirmations` | 1 – 100 |
@@ -941,7 +941,7 @@ dei parametri operativi in
ferma, [connessione-electrum.md](connessione-electrum.md) ELC-21). ferma, [connessione-electrum.md](connessione-electrum.md) ELC-21).
*Codice:* `app/api/routes/admin.py`, `app/electrum/listener.py:ElectrumListener.current_endpoint` · *Codice:* `app/api/routes/admin.py`, `app/electrum/listener.py:ElectrumListener.current_endpoint` ·
*Test:* — *Test:* —
*Stato:* da implementare (B-86, B-92) · *Oggi:* l'endpoint non esiste; *Stato:* da implementare (B-92) · *Oggi:* l'endpoint non esiste;
`/admin` mostra solo l'altezza della catena letta da `GET /rounds/current`. `/admin` mostra solo l'altezza della catena letta da `GET /rounds/current`.
#### GET /admin/bug-reports #### GET /admin/bug-reports
@@ -986,7 +986,7 @@ dei parametri operativi in
**tutte** queste condizioni sono vere, altrimenti `503` con lo stesso corpo e **tutte** queste condizioni sono vere, altrimenti `503` con lo stesso corpo e
`"status": "not_ready"`: `"status": "not_ready"`:
- la connessione Electrum è attiva (`listener.client` non nullo); - la connessione Electrum è attiva (`listener.client` non nullo);
- l'ultimo header è stato accettato da meno di 360 secondi - l'ultimo header è stato accettato da meno di 1800 secondi
([connessione-electrum.md](connessione-electrum.md) ELC-29); ([connessione-electrum.md](connessione-electrum.md) ELC-29);
- lo scheduler dei round ha battuto da meno di 30 secondi (il battito si - lo scheduler dei round ha battuto da meno di 30 secondi (il battito si
aggiorna a ogni giro e a ogni iterazione dell'attesa del blocco di aggiorna a ogni giro e a ogni iterazione dell'attesa del blocco di
+1 -1
View File
@@ -787,7 +787,7 @@ flowchart LR
*Codice:* `app/static/admin.js:startChainStatusPolling` · *Codice:* `app/static/admin.js:startChainStatusPolling` ·
`app/static/admin.js:connectAdminEvents` · `app/static/admin.js:connectAdminEvents` ·
`app/static/admin.js:onAdminServerEvent` `app/static/admin.js:onAdminServerEvent`
*Stato:* da implementare (B-86, B-92), solo per lo stato Electrum e i *Stato:* da implementare (B-92), solo per lo stato Electrum e i
filtri dell'audit · *Oggi:* il pannello mostra solo l'altezza della catena, filtri dell'audit · *Oggi:* il pannello mostra solo l'altezza della catena,
e l'audit log le ultime righe senza filtri. e l'audit log le ultime righe senza filtri.
+15 -2
View File
@@ -62,6 +62,16 @@ Le difese sono cinque.
di [ELC-14]. di [ELC-14].
*Codice:* `app/config.py:validate_quorum_servers`, `app/main.py:lifespan` · *Codice:* `app/config.py:validate_quorum_servers`, `app/main.py:lifespan` ·
*Test:* `tests/unit/test_electrum_listener.py` *Test:* `tests/unit/test_electrum_listener.py`
- **[ELC-30]** Subito dopo `server.version` la connessione chiede
`server.features`: il `genesis_hash` deve essere quello di PLM
(`000000000019d668…ce26f`). PLM condivide genesis e `powLimit` con Bitcoin
(`palladiumcore/src/chainparams.cpp`), quindi un server Electrum di Bitcoin
supererebbe ogni controllo sugli header di [ELC-11]; solo il genesis lo
distingue. Un genesis diverso o assente, o un errore alla richiesta, fa
fallire la connessione come un server irraggiungibile ([ELC-02]); vale anche
per le connessioni del quorum ([ELC-14]).
*Codice:* `app/electrum/client.py:ElectrumClient._check_genesis`, `app/wallet/plm_network.py:GENESIS_HASH` ·
*Test:* `tests/unit/test_electrum_client.py`
## 2. Richieste con limite di tempo ## 2. Richieste con limite di tempo
@@ -338,11 +348,14 @@ B-83).
- **[ELC-29]** Il listener espone lo stato della connessione: se è connesso, - **[ELC-29]** Il listener espone lo stato della connessione: se è connesso,
il server attivo, l'altezza della punta e da quanti secondi è stato il server attivo, l'altezza della punta e da quanti secondi è stato
accettato l'ultimo header. Lo leggono `GET /health/ready` (non pronto se non accettato l'ultimo header. Lo leggono `GET /health/ready` (non pronto se non
connesso o se l'ultimo header ha più di 360 secondi, connesso o se l'ultimo header ha più di 1800 secondi (con blocchi da 120 s
una soglia di 360 s scatterebbe a vuoto ogni ventina di blocchi,
e^-3 ≈ 5%; la rotazione di [ELC-21] resta a 360 s perché agisce solo se un
altro server ha davvero una punta più alta),
[api.md](api.md) B-92) e l'indicatore Electrum di `/admin`. L'altezza [api.md](api.md) B-92) e l'indicatore Electrum di `/admin`. L'altezza
corrente resta visibile anche nella barra di stato della catena di `/` (da corrente resta visibile anche nella barra di stato della catena di `/` (da
`chain_tip_height` di `GET /rounds/current`). `chain_tip_height` di `GET /rounds/current`).
*Codice:* `app/electrum/listener.py:ElectrumListener.current_endpoint`, `app/main.py:health` · *Test:* — *Codice:* `app/electrum/listener.py:ElectrumListener.current_endpoint`, `app/main.py:health` · *Test:* —
*Stato:* da implementare (B-86, B-92) · *Oggi:* `/health` risponde sempre *Stato:* da implementare (B-92) · *Oggi:* `/health` risponde sempre
`ok`; l'età dell'ultimo header non è registrata da nessuna parte e `/admin` `ok`; l'età dell'ultimo header non è registrata da nessuna parte e `/admin`
mostra solo l'altezza. mostra solo l'altezza.
-2
View File
@@ -16,8 +16,6 @@ Un limite che il [piano delle correzioni](piano-correzioni.md) chiuderà porta
atteso; quando la correzione entra nel codice, il limite si barra come atteso; quando la correzione entra nel codice, il limite si barra come
`~~[LIM-nn]~~ Rimosso: chiuso da B-nn`. `~~[LIM-nn]~~ Rimosso: chiuso da B-nn`.
Formato di ogni voce: descrizione, *Impatto*, *Mitigazione attuale*, *Per
chiuderlo*, e il codice coinvolto.
Formato di ogni voce: descrizione, *Impatto*, *Mitigazione attuale*, *Per Formato di ogni voce: descrizione, *Impatto*, *Mitigazione attuale*, *Per
chiuderlo*, e il codice coinvolto. chiuderlo*, e il codice coinvolto.
+13 -15
View File
@@ -53,8 +53,8 @@ leggono dalla rete, non da una tabella:
| Riserva del pool (il "pool" unico di oggi) | `m/84'/746'/0'/1/0` | nessuna tabella; `app/wallet/hd.py:derive_pool_key` | | Riserva del pool (il "pool" unico di oggi) | `m/84'/746'/0'/1/0` | nessuna tabella; `app/wallet/hd.py:derive_pool_key` |
| Montepremi di un round | `m/84'/746'/0'/2/<round_id>` | `rounds.pool_address` ([DAT-60]) | | Montepremi di un round | `m/84'/746'/0'/2/<round_id>` | `rounds.pool_address` ([DAT-60]) |
Il diagramma descrive lo schema **atteso**; le colonne e la tabella marcate Il diagramma descrive lo schema **atteso**; ciò che non esiste ancora è
"da implementare" non esistono ancora (vedi le tabelle di dettaglio). marcato *da implementare* nelle tabelle di dettaglio.
```mermaid ```mermaid
erDiagram erDiagram
@@ -103,11 +103,11 @@ erDiagram
bigint max_round_pool_sats "snapshot" bigint max_round_pool_sats "snapshot"
int draw_confirmations "snapshot" int draw_confirmations "snapshot"
string pool_address string pool_address
string server_seed_enc "cifrato fino alla rivelazione (da implementare)" string server_seed_enc "cifrato fino alla rivelazione"
string server_seed "in chiaro solo dopo la rivelazione (da implementare)" string server_seed "in chiaro solo dopo la rivelazione"
string server_seed_hash "da implementare" string server_seed_hash
string participants_hash "da implementare" string participants_hash
int draw_height "da implementare" int draw_height
datetime drawing_started_at datetime drawing_started_at
int draw_block_height int draw_block_height
string draw_block_hash string draw_block_hash
@@ -118,7 +118,7 @@ erDiagram
bigint fee_amount_sats bigint fee_amount_sats
bigint bump_reserve_sats bigint bump_reserve_sats
string payout_txid string payout_txid
datetime payout_blocked_at "da implementare" datetime payout_blocked_at
} }
round_participants { round_participants {
int id PK int id PK
@@ -126,10 +126,10 @@ erDiagram
int user_id FK int user_id FK
bigint bet_amount_sats bigint bet_amount_sats
string bet_txid string bet_txid
int bet_vout "da implementare" int bet_vout
datetime broadcast_at datetime broadcast_at
datetime confirmed_at datetime confirmed_at
int draw_position "UK con round_id (da implementare)" int draw_position "UK con round_id"
string status "building broadcast confirmed reorged_out" string status "building broadcast confirmed reorged_out"
} }
round_config { round_config {
@@ -142,10 +142,10 @@ erDiagram
int fee_rate_sat_vb int fee_rate_sat_vb
int rbf_timeout_seconds int rbf_timeout_seconds
int deposit_confirmations int deposit_confirmations
int draw_confirmations "da implementare" int draw_confirmations
bigint max_round_pool_sats bigint max_round_pool_sats
bool paused bool paused
string paused_reason "da implementare" string paused_reason
datetime updated_at datetime updated_at
} }
pending_transactions { pending_transactions {
@@ -709,8 +709,6 @@ Una scommessa: un utente in un round.
`app/tx/reconcile.py:_abandon` · `app/bets/confirmation.py:_on_bet_confirmed` · `app/tx/reconcile.py:_abandon` · `app/bets/confirmation.py:_on_bet_confirmed` ·
*Test:* `tests/unit/test_bets.py`, `tests/unit/test_confirmation.py`, *Test:* `tests/unit/test_bets.py`, `tests/unit/test_confirmation.py`,
`tests/unit/test_reconcile.py`, `tests/unit/test_pool_verification.py` `tests/unit/test_reconcile.py`, `tests/unit/test_pool_verification.py`
*Stato:* da implementare (B-76) · *Oggi:* qualunque eccezione del broadcast
cancella la riga come un rifiuto.
- **[DAT-25]** `broadcast_at` è l'istante della fase 1 di `place_bet`, appena - **[DAT-25]** `broadcast_at` è l'istante della fase 1 di `place_bet`, appena
prima del broadcast, e non viene mai riscritto (nemmeno da un bump RBF). Non prima del broadcast, e non viene mai riscritto (nemmeno da un bump RBF). Non
@@ -774,7 +772,7 @@ senza riavviare (vedi [limiti-noti.md](limiti-noti.md)).
| `round_duration_seconds` | Integer | `600` | 30 s – 7 giorni | Durata del round | Dal round **successivo** ([RND-05](ciclo-di-vita-del-round.md)) | | `round_duration_seconds` | Integer | `600` | 30 s – 7 giorni | Durata del round | Dal round **successivo** ([RND-05](ciclo-di-vita-del-round.md)) |
| `round_cooldown_seconds` | Integer | `30` | 0 s – 24 h | Pausa dopo la chiusura | Dal round **successivo**: la pausa dopo il round in corso è quella copiata alla sua apertura ([RND-05](ciclo-di-vita-del-round.md)) | | `round_cooldown_seconds` | Integer | `30` | 0 s – 24 h | Pausa dopo la chiusura | Dal round **successivo**: la pausa dopo il round in corso è quella copiata alla sua apertura ([RND-05](ciclo-di-vita-del-round.md)) |
| `draw_animation_seconds` | Integer | `20` | 0 – 600 s | Durata minima dell'animazione dell'estrazione nel frontend; non condiziona l'estrazione vera | Subito (letto da `GET /rounds/current`) | | `draw_animation_seconds` | Integer | `20` | 0 – 600 s | Durata minima dell'animazione dell'estrazione nel frontend; non condiziona l'estrazione vera | Subito (letto da `GET /rounds/current`) |
| `fee_rate_sat_vb` | Integer | `1` | 1 – `MAX_FEE_RATE_SAT_VB` (10 000) | Commissione di rete delle nuove transazioni | Subito, per le transazioni costruite dopo; quelle in volo tengono il proprio `fee_rate_sat_vb` | | `fee_rate_sat_vb` | Integer | `1` | 1 – `MAX_FEE_RATE_SAT_VB` (5 000) | Commissione di rete delle nuove transazioni | Subito, per le transazioni costruite dopo; quelle in volo tengono il proprio `fee_rate_sat_vb` |
| `rbf_timeout_seconds` | Integer | `900` | 60 s – 7 giorni | Dopo quanto senza conferme si fa un bump RBF | Subito, anche per le transazioni già in volo (il bumper lo rilegge a ogni giro) | | `rbf_timeout_seconds` | Integer | `900` | 60 s – 7 giorni | Dopo quanto senza conferme si fa un bump RBF | Subito, anche per le transazioni già in volo (il bumper lo rilegge a ogni giro) |
| `deposit_confirmations` | Integer | `6` | 1 – 100 | Conferme richieste per accreditare un deposito ([DAT-62]) | Subito, per gli accrediti successivi; gli output già accreditati restano | | `deposit_confirmations` | Integer | `6` | 1 – 100 | Conferme richieste per accreditare un deposito ([DAT-62]) | Subito, per gli accrediti successivi; gli output già accreditati restano |
| `draw_confirmations` | Integer | `3` | 1 – 20 | Conferme richieste sul blocco di estrazione ([DAT-62]) | Dal round **successivo**, copiato all'apertura ([DAT-61]) | | `draw_confirmations` | Integer | `3` | 1 – 20 | Conferme richieste sul blocco di estrazione ([DAT-62]) | Dal round **successivo**, copiato all'apertura ([DAT-61]) |
+2 -2
View File
@@ -618,7 +618,7 @@ con `docker compose logs app` ([architettura.md](architettura.md) ARC-09).
e il suo valore va in commissione, e quella sostituzione è l'ultima e il suo valore va in commissione, e quella sostituzione è l'ultima
(`change_too_small` ai tentativi successivi). Non si può fare nemmeno se (`change_too_small` ai tentativi successivi). Non si può fare nemmeno se
l'uscita non esiste o non basta all'aumento minimo, o se la commissione è già l'uscita non esiste o non basta all'aumento minimo, o se la commissione è già
al massimo (10.000 sat/vB, `max_fee_rate`); `replacement_rejected` è una al massimo (5.000 sat/vB, `max_fee_rate`); `replacement_rejected` è una
sostituzione che la rete ha rifiutato esplicitamente. Un pagamento ha un'uscita di riserva sostituzione che la rete ha rifiutato esplicitamente. Un pagamento ha un'uscita di riserva
(B-79) che l'aumento riduce; la riserva è dimensionata per arrivare a circa (B-79) che l'aumento riduce; la riserva è dimensionata per arrivare a circa
10 sat/vB, oltre la quale (o per un pagamento costruito prima di B-79, che 10 sat/vB, oltre la quale (o per un pagamento costruito prima di B-79, che
@@ -894,7 +894,7 @@ proposito.
| 6 | Riorganizzazione di 1 blocco | Solo su una rete di prova con due minatori, se disponibile | La punta segue il ramo nuovo senza chiudere la sessione; `chain_reorg_detected` con profondità 1; nessuna pausa. Con profondità 2: pausa con motivo `reorg` (B-85, B-74) | | 6 | Riorganizzazione di 1 blocco | Solo su una rete di prova con due minatori, se disponibile | La punta segue il ramo nuovo senza chiudere la sessione; `chain_reorg_detected` con profondità 1; nessuna pausa. Con profondità 2: pausa con motivo `reorg` (B-85, B-74) |
| 7 | Cronologia molto lunga | Indirizzo con risposta oltre 64 KiB (per esempio mille piccoli invii a un indirizzo di prova) | La connessione resta aperta (limite di 16 MiB); le uscite sotto `DUST_LIMIT_SATS` non vengono accreditate (B-75) | | 7 | Cronologia molto lunga | Indirizzo con risposta oltre 64 KiB (per esempio mille piccoli invii a un indirizzo di prova) | La connessione resta aperta (limite di 16 MiB); le uscite sotto `DUST_LIMIT_SATS` non vengono accreditate (B-75) |
| 8 | Tutte le riserve giù | Bloccare con il firewall ogni server di `ELECTRUM_FALLBACK_SERVERS` | Accrediti rinviati, estrazione in attesa, nessuna spesa esterna registrata, nessun denaro mosso; al ritorno dei server tutto riprende. Un avvio con meno di 2 riserve è rifiutato (B-84) | | 8 | Tutte le riserve giù | Bloccare con il firewall ogni server di `ELECTRUM_FALLBACK_SERVERS` | Accrediti rinviati, estrazione in attesa, nessuna spesa esterna registrata, nessun denaro mosso; al ritorno dei server tutto riprende. Un avvio con meno di 2 riserve è rifiutato (B-84) |
| 9 | Server connesso ma fermo | Un server Electrum di prova che smette di seguire la catena | Dopo 360 secondi senza avanzamento il listener passa a un server con una punta più alta (B-86); `GET /health/ready` risponde 503 nel frattempo (B-92) | | 9 | Server connesso ma fermo | Un server Electrum di prova che smette di seguire la catena | Dopo 360 secondi senza avanzamento il listener passa a un server con una punta più alta (B-86); `GET /health/ready` risponde 503 solo oltre 1800 secondi senza header (B-92) |
| 10 | Salto dell'orologio | Portare avanti l'orologio dell'host di 7 ore con transazioni `pending` | Nessuna transazione abbandonata per il solo tempo trascorso (B-78) | | 10 | Salto dell'orologio | Portare avanti l'orologio dell'host di 7 ore con transazioni `pending` | Nessuna transazione abbandonata per il solo tempo trascorso (B-78) |
| 11 | Disco pieno | Riempire il filesystem di `./data/db` durante l'attività | Nessuna transazione trasmessa senza la sua riga salvata prima; scommesse e prelievi falliscono prima dell'invio; liberato lo spazio, il sistema riprende senza interventi sul database | | 11 | Disco pieno | Riempire il filesystem di `./data/db` durante l'attività | Nessuna transazione trasmessa senza la sua riga salvata prima; scommesse e prelievi falliscono prima dell'invio; liberato lo spazio, il sistema riprende senza interventi sul database |
| 12 | Ripristino da backup | Backup, poi un round completo e una registrazione, poi [OPS-07] | Avvio in pausa con `START_PAUSED=true`; `restore_gap_detected` e registrazioni rifiutate; il round rigiocato non viene pagato una seconda volta (B-90, B-80, B-82) | | 12 | Ripristino da backup | Backup, poi un round completo e una registrazione, poi [OPS-07] | Avvio in pausa con `START_PAUSED=true`; `restore_gap_detected` e registrazioni rifiutate; il round rigiocato non viene pagato una seconda volta (B-90, B-80, B-82) |
+5 -3
View File
@@ -204,7 +204,7 @@ Note:
insieme» di [scommesse-e-prelievi.md](scommesse-e-prelievi.md): quel titolo e insieme» di [scommesse-e-prelievi.md](scommesse-e-prelievi.md): quel titolo e
le frasi che il test cerca vanno mantenuti. le frasi che il test cerca vanno mantenuti.
## Revisione della specifica del 2026-09-28 (B-73 … B-98) ## Revisione della specifica del 2026-09-28 (B-73 … B-100)
Quarta revisione, condotta sulla specifica in `docs/` invece che sul solo Quarta revisione, condotta sulla specifica in `docs/` invece che sul solo
codice: quattro analisi indipendenti (meccanica della coin, macchina a stati codice: quattro analisi indipendenti (meccanica della coin, macchina a stati
@@ -247,14 +247,16 @@ cifrava di nuovo il file sbagliato (vedi [operativita.md](operativita.md)).
| B-96 | Incoerenze minori di stato (prelievo ridotto sotto il minimo, importi di un pagamento abbandonato, audit mancanti, attesa in `closing` senza segnali, …) | Media | **aperto** | — | TX, BET, WDR, DEP | | B-96 | Incoerenze minori di stato (prelievo ridotto sotto il minimo, importi di un pagamento abbandonato, audit mancanti, attesa in `closing` senza segnali, …) | Media | **aperto** | — | TX, BET, WDR, DEP |
| B-97 | Le migrazioni possono eliminare in silenzio gli indici su espressione | Media | *da registrare* | `test_migrations.py` | DAT | | B-97 | Le migrazioni possono eliminare in silenzio gli indici su espressione | Media | *da registrare* | `test_migrations.py` | DAT |
| B-98 | La selezione delle monete si ferma alla prima che copre l'importo e rifiuta una scommessa pagabile | Media | **aperto** | — | BET, WDR | | B-98 | La selezione delle monete si ferma alla prima che copre l'importo e rifiuta una scommessa pagabile | Media | **aperto** | — | BET, WDR |
| B-99 | Un server Electrum di Bitcoin supera ogni controllo sugli header (PLM ne condivide genesis e `powLimit`): il genesis non veniva verificato | Media | *da registrare* | `test_electrum_client.py` | ELC |
| B-100 | Il tetto del fee rate coincide con il `maxfeerate` del nodo (10 000 sat/vB): una tariffa al tetto, con vsize stimato per eccesso, verrebbe rifiutata | Bassa | *da registrare* | — (costante; copertura da `test_rbf_dust.py`) | TX |
## Stato attuale ## Stato attuale
- **Corretti:** B-01 … B-70, tranne B-16, che è chiuso nella sostanza (il - **Corretti:** B-01 … B-70, tranne B-16, che è chiuso nella sostanza (il
crash è eliminato e `/guida` serve un segnaposto) ma lascia la guida vera crash è eliminato e `/guida` serve un segnaposto) ma lascia la guida vera
come limite accettato; dalla revisione del 2026-09-28: B-88, B-75, B-97, B-80, B-84, B-76, B-77, B-78, B-83, B-74, B-85, B-86, B-73, B-81, B-79, B-82, B-87, B-95. come limite accettato; dalla revisione del 2026-09-28: B-88, B-75, B-97, B-80, B-84, B-76, B-77, B-78, B-83, B-74, B-85, B-86, B-73, B-81, B-79, B-82, B-87, B-95, B-99, B-100.
- **Aperti:** B-71, B-72 (gravità bassa, operativi o di documentazione) e - **Aperti:** B-71, B-72 (gravità bassa, operativi o di documentazione) e
B-73 … B-98 dalla revisione del 2026-09-28 tranne i corretti (0 critici, B-73 … B-98 dalla revisione del 2026-09-28 tranne i corretti (0 critici,
3 alti, 5 medi), da implementare nell'ordine di 3 alti, 5 medi), da implementare nell'ordine di
[piano-correzioni.md](piano-correzioni.md). [piano-correzioni.md](piano-correzioni.md).
- **Prossimo numero libero:** `B-99`. - **Prossimo numero libero:** `B-101`.
+2 -2
View File
@@ -217,10 +217,10 @@ sostituibilità fin dal primo invio.
*Codice:* `app/tx/broadcast.py:RbfBumper._tick`, `app/tx/broadcast.py:should_bump` · *Codice:* `app/tx/broadcast.py:RbfBumper._tick`, `app/tx/broadcast.py:should_bump` ·
*Test:* `tests/unit/test_broadcast.py` *Test:* `tests/unit/test_broadcast.py`
- **[TX-10]** La nuova commissione punta a 1 sat/vB in più della tariffa - **[TX-10]** La nuova commissione punta a 1 sat/vB in più della tariffa
registrata (`_FEE_RATE_INCREMENT`), senza superare 10.000 sat/vB registrata (`_FEE_RATE_INCREMENT`), senza superare 5.000 sat/vB
(`MAX_FEE_RATE_SAT_VB`); l'aumento assoluto non è mai inferiore alla (`MAX_FEE_RATE_SAT_VB`); l'aumento assoluto non è mai inferiore alla
dimensione stimata della transazione per 1 sat/vB, il minimo richiesto da dimensione stimata della transazione per 1 sat/vB, il minimo richiesto da
BIP125 per una sostituzione. Una riga già a 10.000 sat/vB non viene più BIP125 per una sostituzione. Una riga già a 5.000 sat/vB non viene più
accelerata. Gli importi delle monete spese sono letti dalle transazioni accelerata. Gli importi delle monete spese sono letti dalle transazioni
precedenti come interi in satoshi. precedenti come interi in satoshi.
*Codice:* `app/tx/broadcast.py:bump_fee`, `app/tx/broadcast.py:_prevout_amount` · *Codice:* `app/tx/broadcast.py:bump_fee`, `app/tx/broadcast.py:_prevout_amount` ·
+1 -1
View File
@@ -5,7 +5,7 @@ requires-python = ">=3.12"
dependencies = [ dependencies = [
"fastapi>=0.115", "fastapi>=0.115",
"uvicorn[standard]>=0.32", "uvicorn[standard]>=0.32",
"sqlalchemy>=2.0", "sqlalchemy[asyncio]>=2.0",
"aiosqlite>=0.20", "aiosqlite>=0.20",
"alembic>=1.13", "alembic>=1.13",
"pydantic-settings>=2.6", "pydantic-settings>=2.6",
+37
View File
@@ -325,12 +325,30 @@ class _PinWriter(FakeWriter):
self.closed = True self.closed = True
def _answer_features(reader, writer, result=None):
"""Make `writer` answer `server.features` the moment it is asked: a reply fed up front
would be read before its request is registered, and dropped."""
from app.wallet.plm_network import GENESIS_HASH
original = writer.write
def write(data):
original(data)
sent = json.loads(data.decode())
if sent["method"] == "server.features":
reply = {"genesis_hash": GENESIS_HASH} if result is None else result
reader.feed_data((json.dumps({"id": sent["id"], "result": reply}) + "\n").encode())
writer.write = write
async def _connect_with_pin(monkeypatch, pin, der): async def _connect_with_pin(monkeypatch, pin, der):
import hashlib # noqa: F401 import hashlib # noqa: F401
writer = _PinWriter(der) writer = _PinWriter(der)
reader = asyncio.StreamReader() reader = asyncio.StreamReader()
reader.feed_data(b'{"id": 1, "result": ["fake", "1.4"]}\n') reader.feed_data(b'{"id": 1, "result": ["fake", "1.4"]}\n')
_answer_features(reader, writer)
async def fake_open_connection(host, port, **kwargs): async def fake_open_connection(host, port, **kwargs):
return reader, writer return reader, writer
@@ -413,3 +431,22 @@ async def test_only_a_server_error_object_is_an_explicit_refusal():
silent._read_task.cancel() silent._read_task.cancel()
finally: finally:
client_module._REQUEST_TIMEOUT_SECONDS = original client_module._REQUEST_TIMEOUT_SECONDS = original
async def test_a_server_on_another_chain_is_refused_at_the_handshake(monkeypatch):
"""ELC-30: Bitcoin's genesis (or no genesis at all) fails like an unreachable server."""
import pytest
bitcoin = "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26e"
for result in ({"genesis_hash": bitcoin}, {}):
writer = FakeWriter()
reader = asyncio.StreamReader()
reader.feed_data(b'{"id": 1, "result": ["fake", "1.4"]}\n')
_answer_features(reader, writer, result)
async def fake_open_connection(host, port, reader=reader, writer=writer, **kwargs):
return reader, writer
monkeypatch.setattr(asyncio, "open_connection", fake_open_connection)
with pytest.raises(ElectrumError, match="not on the PLM chain"):
await ElectrumClient("localhost", 1).connect()