From 3ee60a23da1fbaa687a43f205750d019b3448c17 Mon Sep 17 00:00:00 2001 From: Davide Grilli Date: Mon, 16 Nov 2026 15:31:47 +0100 Subject: [PATCH] B1: plm_engine takes the modules without a database (ADR-59) HD derivation (pure part), PSBT builder, Electrum client/merkle/quorum/scripthash, network profile, addresses and header checks move to plm_engine; the old stack imports them from there. A test forbids framework imports in the package. Co-Authored-By: Claude Sonnet 5.5 --- CLAUDE.md | 2 +- README.md | 2 +- app/api/routes/admin.py | 4 +- app/api/routes/qr.py | 2 +- app/bets/service.py | 4 +- app/deposits/reconcile.py | 2 +- app/deposits/service.py | 2 +- app/electrum/listener.py | 10 ++-- app/main.py | 2 +- app/rounds/scheduler.py | 8 +-- app/rounds/service.py | 4 +- app/tx/broadcast.py | 6 +-- app/tx/confirmation.py | 4 +- app/tx/outcome.py | 2 +- app/tx/reconcile.py | 6 +-- app/wallet/balance.py | 2 +- app/wallet/hd.py | 52 +++++-------------- app/wallet/verify.py | 2 +- app/withdrawals/service.py | 6 +-- ...04-accesso-rete-via-protocollo-electrum.md | 2 +- ...rizzi-bech32-plm-plm1-come-destinazione.md | 2 +- ...tto-prezzo-fisso-scommessa-utente-round.md | 2 +- ...missione-rete-toglie-dall-importo-muove.md | 2 +- ...ne-pagamento-esce-dalla-quota-vincitore.md | 2 +- ...ransazione-utente-conserva-uscita-resto.md | 2 +- ...1-tre-limiti-distinti-sul-numero-monete.md | 2 +- ...4-l-estrazione-commit-reveal-fra-server.md | 2 +- ...egli-header-concatenata-senza-ricalcolo.md | 2 +- docs/adr/ADR-35-aritmetica-satoshi-interi.md | 2 +- ...cchetto-senza-framework-ledger-simulato.md | 2 +- docs/api.md | 16 +++--- docs/architettura.md | 18 +++---- docs/ciclo-di-vita-del-round.md | 12 ++--- docs/connessione-electrum.md | 16 +++--- docs/legacy-fastapi-notes.md | 4 +- docs/limiti-noti.md | 10 ++-- docs/modello-dati.md | 12 ++--- docs/operativita.md | 2 +- docs/registrazione-e-depositi.md | 2 +- docs/scommesse-e-prelievi.md | 24 ++++----- docs/sicurezza.md | 4 +- docs/transazioni-e-riconciliazione.md | 4 +- {app/wallet => plm_engine}/address.py | 2 +- plm_engine/electrum/__init__.py | 1 + {app => plm_engine}/electrum/client.py | 2 +- {app => plm_engine}/electrum/merkle.py | 0 {app => plm_engine}/electrum/quorum.py | 0 {app => plm_engine}/electrum/scripthash.py | 0 plm_engine/hd.py | 52 +++++++++++++++++++ app/rounds/draw.py => plm_engine/headers.py | 11 +--- .../plm_network.py => plm_engine/network.py | 0 {app/wallet => plm_engine}/psbt_builder.py | 0 roadmap.md | 2 +- scripts/electrum_smoke_test.py | 2 +- tests/django/test_engine_package.py | 21 ++++++++ tests/django/test_lifecycle.py | 11 ---- tests/unit/conftest.py | 2 +- tests/unit/fake_network.py | 6 +-- tests/unit/test_admin.py | 2 +- tests/unit/test_balance.py | 2 +- tests/unit/test_bets.py | 2 +- tests/unit/test_broadcast.py | 8 +-- tests/unit/test_broadcast_outcome.py | 2 +- tests/unit/test_confirmation.py | 2 +- tests/unit/test_confirmation_proof.py | 6 +-- tests/unit/test_deposits.py | 2 +- tests/unit/test_draw.py | 24 ++++----- tests/unit/test_draw_proof.py | 2 +- tests/unit/test_electrum_client.py | 28 +++++----- tests/unit/test_electrum_listener.py | 10 ++-- tests/unit/test_hd.py | 2 +- tests/unit/test_master_key_check.py | 2 +- tests/unit/test_observability.py | 4 +- tests/unit/test_payout_builder.py | 4 +- tests/unit/test_pool_verification.py | 8 +-- tests/unit/test_psbt_builder.py | 16 +++--- tests/unit/test_rbf_dust.py | 4 +- tests/unit/test_reconcile_proof.py | 6 +-- tests/unit/test_restore_gap.py | 2 +- tests/unit/test_round_pool_address.py | 4 +- tests/unit/test_round_snapshot.py | 2 +- tests/unit/test_rounds_service.py | 2 +- tests/unit/test_scheduler.py | 8 +-- tests/unit/test_scripthash.py | 2 +- tests/unit/test_sqlite_transactions.py | 2 +- tests/unit/test_tx_versions.py | 6 +-- tests/unit/test_withdrawals.py | 6 +-- 87 files changed, 290 insertions(+), 260 deletions(-) rename {app/wallet => plm_engine}/address.py (95%) create mode 100644 plm_engine/electrum/__init__.py rename {app => plm_engine}/electrum/client.py (99%) rename {app => plm_engine}/electrum/merkle.py (100%) rename {app => plm_engine}/electrum/quorum.py (100%) rename {app => plm_engine}/electrum/scripthash.py (100%) create mode 100644 plm_engine/hd.py rename app/rounds/draw.py => plm_engine/headers.py (96%) rename app/wallet/plm_network.py => plm_engine/network.py (100%) rename {app/wallet => plm_engine}/psbt_builder.py (100%) create mode 100644 tests/django/test_engine_package.py diff --git a/CLAUDE.md b/CLAUDE.md index 19cf331..2bf10b1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,7 +8,7 @@ The user communicates in Italian in chat — reply to them in Italian. Everythin ## Project status -The migration from FastAPI to Django is in progress on branch `django-migration` (plan: [roadmap.md](roadmap.md), steps A1–A10 done). The suite has 1157 tests: the old stack's under `tests/unit/`, the Django ones under `tests/django/` (`tests/integration/` is an empty package). Open defects of the old stack are in [BUGS.md](BUGS.md); accepted limits in [docs/limiti-noti.md](docs/limiti-noti.md); every closed `B-nn` is in [docs/storico-bug.md](docs/storico-bug.md) (`git log --all --grep 'B-nn'` finds its commit). +The migration from FastAPI to Django is in progress on branch `django-migration` (plan: [roadmap.md](roadmap.md), steps A1–A10 done). The suite has 1168 tests: the old stack's under `tests/unit/`, the Django ones under `tests/django/` (`tests/integration/` is an empty package). Open defects of the old stack are in [BUGS.md](BUGS.md); accepted limits in [docs/limiti-noti.md](docs/limiti-noti.md); every closed `B-nn` is in [docs/storico-bug.md](docs/storico-bug.md) (`git log --all --grep 'B-nn'` finds its commit). **[docs/](docs/README.md) is the specification, and it is authoritative.** Every verifiable rule there has a stable requirement ID (`RND-04`, `BET-02`, …) with `*Codice:*`/`*Test:*` pointers to what implements it; the index is [docs/come-funziona.md](docs/come-funziona.md) and the ID convention and change workflow are in [docs/processo-di-modifica.md](docs/processo-di-modifica.md). A behaviour change starts in the spec: edit or add the requirement, implement it, cite the ID in the test docstring and the commit message, and ship spec + code + test in one commit. If this file and the spec disagree, the spec wins and this file is the one to fix. Before writing code, read the relevant spec documents and the "Architecture" section below. diff --git a/README.md b/README.md index 13e46de..3395f6c 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ python -m pytest # all tests python -m pytest tests/unit/test_hd.py # one file ``` -1157 unit tests cover HD derivation, PSBT building, the Electrum client, bets, +1168 unit tests cover HD derivation, PSBT building, the Electrum client, bets, deposits, withdrawals, the round/draw engine, RBF fee-bumping, admin config, the pending-inclusive balance calculation, and the SSE push channel. No automated integration tests against a live Electrum connection — mainnet diff --git a/app/api/routes/admin.py b/app/api/routes/admin.py index f6d683c..d530e58 100644 --- a/app/api/routes/admin.py +++ b/app/api/routes/admin.py @@ -17,9 +17,9 @@ from app.db.session import get_session from app.rounds.config import get_round_config from app.rounds.pause import pause_by_operator from app.rounds.service import get_active_round, payout_config_problem -from app.wallet.address import is_valid_plm_address +from plm_engine.address import is_valid_plm_address from app.wallet.hd import derive_user_wif -from app.wallet.psbt_builder import MAX_FEE_RATE_SAT_VB +from plm_engine.psbt_builder import MAX_FEE_RATE_SAT_VB router = APIRouter(prefix="/admin", tags=["admin"]) diff --git a/app/api/routes/qr.py b/app/api/routes/qr.py index 5ac66b2..2d9d84f 100644 --- a/app/api/routes/qr.py +++ b/app/api/routes/qr.py @@ -23,7 +23,7 @@ from fastapi.concurrency import run_in_threadpool from fastapi.responses import Response from app.api.errors import http_error -from app.wallet.address import is_valid_plm_address +from plm_engine.address import is_valid_plm_address router = APIRouter(tags=["qr"]) diff --git a/app/bets/service.py b/app/bets/service.py index 2e7e6ff..3e7880a 100644 --- a/app/bets/service.py +++ b/app/bets/service.py @@ -10,7 +10,7 @@ from app.api.errors import ApiError from app.audit.log import write_audit_log from app.db.base import begin_immediate from app.db.models import PendingTransaction, Round, RoundParticipant, User, UtxoEvent -from app.electrum.client import ElectrumClient +from plm_engine.electrum.client import ElectrumClient from app.rounds.config import get_round_config from app.rounds.events import broadcaster from app.rounds.service import open_new_round_if_needed, round_accepts_bets @@ -18,7 +18,7 @@ from app.tx.versions import delete_versions, record_version from app.tx.outcome import BroadcastOutcome, TransactionNetwork, broadcast_with_verdict from app.wallet.balance import compute_pending_balance, recompute_balance from app.wallet.hd import derive_user_key -from app.wallet.psbt_builder import ( +from plm_engine.psbt_builder import ( MAX_PARTICIPANTS_PER_ROUND, RECIPIENT_VOUT, BuiltTransaction, diff --git a/app/deposits/reconcile.py b/app/deposits/reconcile.py index 048d9d3..5ad5af1 100644 --- a/app/deposits/reconcile.py +++ b/app/deposits/reconcile.py @@ -23,7 +23,7 @@ from sqlalchemy.ext.asyncio import async_sessionmaker from app.db.models import User from app.electrum.listener import ElectrumListener -from app.electrum.scripthash import address_to_scripthash +from plm_engine.electrum.scripthash import address_to_scripthash logger = logging.getLogger(__name__) diff --git a/app/deposits/service.py b/app/deposits/service.py index 2ca337e..ca65b71 100644 --- a/app/deposits/service.py +++ b/app/deposits/service.py @@ -10,7 +10,7 @@ from app.db.base import begin_immediate from app.db.models import PendingTransaction, PendingTransactionTxid, RoundConfig, UtxoEvent from app.rounds.events import broadcaster from app.wallet.balance import recompute_balance -from app.wallet.psbt_builder import DUST_LIMIT_SATS +from plm_engine.psbt_builder import DUST_LIMIT_SATS logger = logging.getLogger(__name__) diff --git a/app/electrum/listener.py b/app/electrum/listener.py index 20e67ea..4d29e70 100644 --- a/app/electrum/listener.py +++ b/app/electrum/listener.py @@ -23,11 +23,11 @@ from app.deposits.service import ( reinstate_reappeared_utxos, ) from app.config import MIN_QUORUM_RESPONSES -from app.electrum.client import ElectrumClient, ElectrumEndpoint, ElectrumRpcError -from app.electrum.merkle import proof_matches_header -from app.electrum.quorum import ServerAnswers -from app.electrum.scripthash import address_to_scripthash -from app.rounds.draw import ( +from plm_engine.electrum.client import ElectrumClient, ElectrumEndpoint, ElectrumRpcError +from plm_engine.electrum.merkle import proof_matches_header +from plm_engine.electrum.quorum import ServerAnswers +from plm_engine.electrum.scripthash import address_to_scripthash +from plm_engine.headers import ( HeaderValidationError, header_hex_to_block_hash, header_meets_its_own_target, diff --git a/app/main.py b/app/main.py index ec9fcbf..6b2dd4c 100644 --- a/app/main.py +++ b/app/main.py @@ -27,7 +27,7 @@ from app.api.errors import ApiError from app.config import settings, validate_quorum_servers, validate_runtime_secrets from app.db.base import AsyncSessionLocal from app.deposits.reconcile import DepositReconciler -from app.electrum.client import ElectrumClient, ElectrumEndpoint, parse_endpoints +from plm_engine.electrum.client import ElectrumClient, ElectrumEndpoint, parse_endpoints from app.electrum.listener import ElectrumListener from app.rounds.scheduler import RoundScheduler from app.rounds.pause import pause_by_operator diff --git a/app/rounds/scheduler.py b/app/rounds/scheduler.py index b06c8a8..49d5808 100644 --- a/app/rounds/scheduler.py +++ b/app/rounds/scheduler.py @@ -13,9 +13,9 @@ from app.audit.log import write_audit_log from app.db.base import begin_immediate from app.db.models import AuditLog, PendingTransaction, Round, RoundParticipant, User from app.electrum.listener import ElectrumListener -from app.electrum.scripthash import address_to_scripthash +from plm_engine.electrum.scripthash import address_to_scripthash from app.rounds.config import get_round_config -from app.rounds.draw import ( +from plm_engine.draw import ( draw_index, draw_seed, new_server_seed, @@ -29,8 +29,8 @@ from app.tx.outcome import BroadcastOutcome, broadcast_with_verdict from app.tx.versions import record_version from app.wallet.hd import derive_pool_address, derive_round_pool_key from app.wallet.keystore import decrypt_round_seed, encrypt_round_seed -from app.wallet.plm_network import PLM_MAINNET -from app.wallet.psbt_builder import InsufficientFundsError, Utxo, build_payout_transaction +from plm_engine.network import PLM_MAINNET +from plm_engine.psbt_builder import InsufficientFundsError, Utxo, build_payout_transaction logger = logging.getLogger(__name__) diff --git a/app/rounds/service.py b/app/rounds/service.py index 08b9e34..05b5a07 100644 --- a/app/rounds/service.py +++ b/app/rounds/service.py @@ -8,10 +8,10 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.db.models import Round, RoundConfig from app.rounds.config import get_round_config from app.rounds.events import broadcaster -from app.rounds.draw import new_server_seed, server_seed_commitment +from plm_engine.draw import new_server_seed, server_seed_commitment from app.wallet.hd import derive_pool_address from app.wallet.keystore import encrypt_round_seed -from app.wallet.psbt_builder import ( +from plm_engine.psbt_builder import ( DUST_LIMIT_SATS, MAX_PARTICIPANTS_PER_ROUND, MAX_TX_INPUTS, diff --git a/app/tx/broadcast.py b/app/tx/broadcast.py index 8cfef99..5bb8173 100644 --- a/app/tx/broadcast.py +++ b/app/tx/broadcast.py @@ -22,13 +22,13 @@ from app.db.models import ( UtxoEvent, Withdrawal, ) -from app.electrum.client import ElectrumClient +from plm_engine.electrum.client import ElectrumClient from app.rounds.config import get_round_config from app.tx.outcome import BroadcastOutcome, TransactionNetwork, broadcast_with_verdict from app.tx.versions import record_version from app.wallet.hd import derive_pool_address, derive_round_pool_key, derive_user_key -from app.wallet.plm_network import PLM_MAINNET -from app.wallet.psbt_builder import DUST_LIMIT_SATS, MAX_FEE_RATE_SAT_VB, RBF_SEQUENCE, estimate_vsize +from plm_engine.network import PLM_MAINNET +from plm_engine.psbt_builder import DUST_LIMIT_SATS, MAX_FEE_RATE_SAT_VB, RBF_SEQUENCE, estimate_vsize logger = logging.getLogger(__name__) diff --git a/app/tx/confirmation.py b/app/tx/confirmation.py index 2f62974..287f387 100644 --- a/app/tx/confirmation.py +++ b/app/tx/confirmation.py @@ -8,8 +8,8 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker from app.db.base import begin_immediate from app.db.models import PendingTransaction -from app.electrum.client import ElectrumClient -from app.electrum.scripthash import address_to_scripthash +from plm_engine.electrum.client import ElectrumClient +from plm_engine.electrum.scripthash import address_to_scripthash from app.rounds.events import broadcaster from app.tx.broadcast import adopt_version from app.tx.pending_address import own_address_for diff --git a/app/tx/outcome.py b/app/tx/outcome.py index b8c6373..6cd0f9e 100644 --- a/app/tx/outcome.py +++ b/app/tx/outcome.py @@ -19,7 +19,7 @@ import logging from enum import Enum from typing import NamedTuple, Protocol -from app.electrum.client import ElectrumRpcError +from plm_engine.electrum.client import ElectrumRpcError logger = logging.getLogger(__name__) diff --git a/app/tx/reconcile.py b/app/tx/reconcile.py index 62775b5..913adc0 100644 --- a/app/tx/reconcile.py +++ b/app/tx/reconcile.py @@ -54,9 +54,9 @@ from app.db.models import ( UtxoEvent, Withdrawal, ) -from app.electrum.client import ElectrumClient -from app.electrum.quorum import ServerAnswers -from app.electrum.scripthash import address_to_scripthash +from plm_engine.electrum.client import ElectrumClient +from plm_engine.electrum.quorum import ServerAnswers +from plm_engine.electrum.scripthash import address_to_scripthash from app.rounds.events import broadcaster from app.rounds.pause import pause_automatically from app.tx.broadcast import adopt_version diff --git a/app/wallet/balance.py b/app/wallet/balance.py index 57a2169..16574fc 100644 --- a/app/wallet/balance.py +++ b/app/wallet/balance.py @@ -3,7 +3,7 @@ from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession from app.db.models import PendingTransaction, User, UtxoEvent -from app.wallet.plm_network import PLM_MAINNET +from plm_engine.network import PLM_MAINNET async def recompute_balance(session: AsyncSession, user_id: int) -> int: diff --git a/app/wallet/hd.py b/app/wallet/hd.py index aac926b..7677c14 100644 --- a/app/wallet/hd.py +++ b/app/wallet/hd.py @@ -1,12 +1,11 @@ import os -from embit import script from embit.bip32 import HDKey -from embit.ec import PrivateKey from app.config import settings +from plm_engine import hd as engine from app.wallet.keystore import decrypt_xprv, encrypt_xprv, write_secret_file -from app.wallet.plm_network import ACCOUNT_PATH, PLM_MAINNET +from plm_engine.network import ACCOUNT_PATH, PLM_MAINNET _account_key: HDKey | None = None @@ -31,55 +30,30 @@ def _load_account_key() -> HDKey: def derive_user_key(derivation_index: int) -> HDKey: - return _load_account_key().derive(f"0/{derivation_index}") + return engine.user_key(_load_account_key(), derivation_index) def derive_user_address(derivation_index: int) -> str: - pub = derive_user_key(derivation_index).to_public() - return script.p2wpkh(pub).address(network=PLM_MAINNET) + return engine.user_address(_load_account_key(), derivation_index) def derive_user_wif(derivation_index: int) -> str: - """Exports a user's raw private key (WIF) for manual server-side intervention - (e.g. sweeping funds back to a user, or out, if something gets stuck). This is - a custodial system — the server already holds the master key this is derived - from — but callers must still treat the result as a live secret: log access, - never persist it, never return it over an unauthenticated channel.""" - key = derive_user_key(derivation_index) - return PrivateKey(key.secret, compressed=True, network=PLM_MAINNET).wif(network=PLM_MAINNET) + """Exports a user's raw private key (WIF) for manual server-side intervention (e.g. sweeping funds back to a + user, or out, if something gets stuck). Callers must treat the result as a live secret: log access, never + persist it, never return it over an unauthenticated channel.""" + return engine.user_wif(_load_account_key(), derivation_index) def derive_pool_key(round_id: int | None = None) -> HDKey: - """A pool key. With a `round_id`, that round's own key on branch 2 of the account - (`m/84'/746'/0'/2/`, B-80, RND-35): its bets are paid to it and its - payout is signed with it, so one round's money and history never mix with another's. - Without one, the **reserve** key at branch 1, index 0 — the single pool address every - round used before B-80, still the pool of the rounds opened back then and the - destination of the payout's bump reserve. Branch 0 is users. Not a spec requirement - of the coin, an implementation choice to keep every key under the one encrypted - master key rather than in separate secrets.""" - if round_id is None: - return _load_account_key().derive("1/0") - if round_id < 1: - raise ValueError(f"invalid round id {round_id}") - return _load_account_key().derive(f"2/{round_id}") + """A pool key: a round's own (B-80, RND-35) or, without a `round_id`, the reserve key. See `plm_engine.hd`.""" + return engine.pool_key(_load_account_key(), round_id) def derive_pool_address(round_id: int | None = None) -> str: """The pool address of a round (B-80), or the reserve address without a `round_id`.""" - pub = derive_pool_key(round_id).to_public() - return script.p2wpkh(pub).address(network=PLM_MAINNET) + return engine.pool_address(_load_account_key(), round_id) def derive_round_pool_key(round_id: int, pool_address: str) -> HDKey: - """The key that controls `pool_address`, the address stored on round `round_id`. - - A round opened before B-80 stores the reserve address and is signed with the reserve - key; every other round with its own. Checking the derived address against the stored - one means a key can never be used for money it does not control, and a mismatch (a - different master key, a corrupted row) fails loudly instead of building a transaction - that spends someone else's coins.""" - for key in (derive_pool_key(round_id), derive_pool_key()): - if script.p2wpkh(key.to_public()).address(network=PLM_MAINNET) == pool_address: - return key - raise ValueError(f"round {round_id}: no pool key controls the stored address {pool_address!r}") + """The key that controls `pool_address`, the address stored on round `round_id` (see `plm_engine.hd`).""" + return engine.round_pool_key(_load_account_key(), round_id, pool_address) diff --git a/app/wallet/verify.py b/app/wallet/verify.py index 6bffaa0..dca0e7f 100644 --- a/app/wallet/verify.py +++ b/app/wallet/verify.py @@ -16,7 +16,7 @@ from embit import script from embit.bip32 import HDKey from app.config import ConfigError, settings -from app.wallet.plm_network import ACCOUNT_PATH, PLM_MAINNET +from plm_engine.network import ACCOUNT_PATH, PLM_MAINNET logger = logging.getLogger(__name__) diff --git a/app/withdrawals/service.py b/app/withdrawals/service.py index 8e3e9b4..00ac302 100644 --- a/app/withdrawals/service.py +++ b/app/withdrawals/service.py @@ -10,15 +10,15 @@ from app.api.errors import ApiError from app.audit.log import write_audit_log from app.db.base import begin_immediate from app.db.models import PendingTransaction, Round, User, UtxoEvent, Withdrawal -from app.electrum.client import ElectrumClient +from plm_engine.electrum.client import ElectrumClient from app.rounds.config import get_round_config from app.rounds.events import broadcaster from app.tx.versions import record_version from app.tx.outcome import BroadcastOutcome, TransactionNetwork, broadcast_with_verdict -from app.wallet.address import is_valid_plm_address +from plm_engine.address import is_valid_plm_address from app.wallet.balance import compute_pending_balance, recompute_balance from app.wallet.hd import derive_pool_address, derive_user_key -from app.wallet.psbt_builder import ( +from plm_engine.psbt_builder import ( BuiltTransaction, InsufficientFundsError, Utxo, diff --git a/docs/adr/ADR-04-accesso-rete-via-protocollo-electrum.md b/docs/adr/ADR-04-accesso-rete-via-protocollo-electrum.md index febe3cf..acc8008 100644 --- a/docs/adr/ADR-04-accesso-rete-via-protocollo-electrum.md +++ b/docs/adr/ADR-04-accesso-rete-via-protocollo-electrum.md @@ -15,4 +15,4 @@ conferme, altezza della catena). [ADR-26](ADR-26-validazione-degli-header-concatenata-senza-ricalcolo.md) e [ADR-52](ADR-52-riorganizzazioni-catena-contengono-invece-ignorarle.md) e i limiti [LIM-11], [LIM-12], [LIM-14]. Dettagli in [connessione-electrum.md](../connessione-electrum.md). -*Codice:* `app/electrum/client.py:ElectrumClient` · `app/electrum/listener.py:ElectrumListener` · `app/main.py:lifespan` +*Codice:* `plm_engine/electrum/client.py:ElectrumClient` · `app/electrum/listener.py:ElectrumListener` · `app/main.py:lifespan` diff --git a/docs/adr/ADR-05-indirizzi-bech32-plm-plm1-come-destinazione.md b/docs/adr/ADR-05-indirizzi-bech32-plm-plm1-come-destinazione.md index e15cfe0..c094a2d 100644 --- a/docs/adr/ADR-05-indirizzi-bech32-plm-plm1-come-destinazione.md +++ b/docs/adr/ADR-05-indirizzi-bech32-plm-plm1-come-destinazione.md @@ -13,5 +13,5 @@ rifiutato; lo stesso controllo vale per `fee_address` e per `/qr/{address}`. witness program valido, quindi la transazione si costruirebbe e i fondi sarebbero irrecuperabili. -*Codice:* `app/wallet/address.py:is_valid_plm_address` · `app/withdrawals/service.py:request_withdrawal` · `app/api/routes/admin.py:RoundConfigUpdate` · +*Codice:* `plm_engine/address.py:is_valid_plm_address` · `app/withdrawals/service.py:request_withdrawal` · `app/api/routes/admin.py:RoundConfigUpdate` · *Test:* `tests/unit/test_withdrawals.py::test_withdrawal_rejects_non_plm_address` diff --git a/docs/adr/ADR-15-biglietto-prezzo-fisso-scommessa-utente-round.md b/docs/adr/ADR-15-biglietto-prezzo-fisso-scommessa-utente-round.md index 0a4db88..cba0f00 100644 --- a/docs/adr/ADR-15-biglietto-prezzo-fisso-scommessa-utente-round.md +++ b/docs/adr/ADR-15-biglietto-prezzo-fisso-scommessa-utente-round.md @@ -13,5 +13,5 @@ Nessun deposito minimo. importi. Il costo è fotografato all'apertura del round ([ADR-10](ADR-10-parametri-round-fotografati-all-apertura.md)), così tutti i partecipanti di un round pagano la stessa posta (B-95). -*Codice:* `app/bets/service.py:place_bet` · `app/rounds/draw.py:draw_winner` · +*Codice:* `app/bets/service.py:place_bet` · `plm_engine/draw.py:draw_winner` · *Test:* `tests/unit/test_bets.py::test_place_bet_rejects_second_bet_same_round` diff --git a/docs/adr/ADR-16-commissione-rete-toglie-dall-importo-muove.md b/docs/adr/ADR-16-commissione-rete-toglie-dall-importo-muove.md index 40eec6f..f09e884 100644 --- a/docs/adr/ADR-16-commissione-rete-toglie-dall-importo-muove.md +++ b/docs/adr/ADR-16-commissione-rete-toglie-dall-importo-muove.md @@ -14,5 +14,5 @@ meno la commissione. delle scommesse, non moltiplicando il numero di giocatori per il costo (B-11); il prelievo registra sia l'importo richiesto sia quello inviato. -*Codice:* `app/wallet/psbt_builder.py:build_signed_transaction` · +*Codice:* `plm_engine/psbt_builder.py:build_signed_transaction` · *Test:* `tests/unit/test_psbt_builder.py::test_build_signed_transaction_deducts_fee_from_amount_not_change` diff --git a/docs/adr/ADR-17-commissione-pagamento-esce-dalla-quota-vincitore.md b/docs/adr/ADR-17-commissione-pagamento-esce-dalla-quota-vincitore.md index 1515385..5b5fbfe 100644 --- a/docs/adr/ADR-17-commissione-pagamento-esce-dalla-quota-vincitore.md +++ b/docs/adr/ADR-17-commissione-pagamento-esce-dalla-quota-vincitore.md @@ -29,5 +29,5 @@ commissione verso `fee_address` è quindi il 30% meno la riserva. riserva e una commissione sopra la soglia di polvere. Regole in [ciclo-di-vita-del-round.md](../ciclo-di-vita-del-round.md#4--pagamento) (B-79). -*Codice:* `app/wallet/psbt_builder.py:build_payout_transaction` · +*Codice:* `plm_engine/psbt_builder.py:build_payout_transaction` · *Test:* `tests/unit/test_payout_builder.py::test_payout_deducts_fee_only_from_winner_share`, `tests/unit/test_payout_builder.py::test_payout_at_the_participant_cap_pays_the_reserve_out_of_the_platform_share`, `tests/unit/test_broadcast.py::test_a_payout_is_bumped_out_of_its_reserve_output_and_nothing_else` diff --git a/docs/adr/ADR-19-ogni-transazione-utente-conserva-uscita-resto.md b/docs/adr/ADR-19-ogni-transazione-utente-conserva-uscita-resto.md index 26418d4..e246172 100644 --- a/docs/adr/ADR-19-ogni-transazione-utente-conserva-uscita-resto.md +++ b/docs/adr/ADR-19-ogni-transazione-utente-conserva-uscita-resto.md @@ -30,5 +30,5 @@ e di [TX-11](../transazioni-e-riconciliazione.md#rbf-accelerare-una-transazione- l'utente perde al più 294 sat. **Il pagamento del round** non ha un resto utente: la sua uscita riducibile è la riserva di [ADR-17](ADR-17-commissione-pagamento-esce-dalla-quota-vincitore.md). -*Codice:* `app/wallet/psbt_builder.py:build_signed_transaction` · `app/withdrawals/service.py:request_withdrawal` · `app/tx/broadcast.py:bump_fee` · +*Codice:* `plm_engine/psbt_builder.py:build_signed_transaction` · `app/withdrawals/service.py:request_withdrawal` · `app/tx/broadcast.py:bump_fee` · *Test:* `tests/unit/test_rbf_dust.py::test_a_minimum_change_is_dropped_into_the_fee_by_the_first_bump`, `tests/unit/test_rbf_dust.py::test_the_dust_boundary_of_what_a_bump_leaves`, `tests/unit/test_psbt_builder.py::test_build_signed_transaction_refuses_an_amount_that_would_leave_no_change`, `tests/unit/test_withdrawals.py::test_full_balance_withdrawal_keeps_a_bumpable_change_output`, `tests/unit/test_withdrawals.py::test_a_bet_from_a_balance_equal_to_the_bet_is_refused` diff --git a/docs/adr/ADR-21-tre-limiti-distinti-sul-numero-monete.md b/docs/adr/ADR-21-tre-limiti-distinti-sul-numero-monete.md index 84905ec..ae4c7b5 100644 --- a/docs/adr/ADR-21-tre-limiti-distinti-sul-numero-monete.md +++ b/docs/adr/ADR-21-tre-limiti-distinti-sul-numero-monete.md @@ -29,5 +29,5 @@ (B-95); se e come legarlo al costo di un attacco al 51% è una decisione non ancora presa ([LIM-24]). -*Codice:* `app/wallet/psbt_builder.py:select_utxos` · `app/bets/service.py:place_bet` · `app/wallet/psbt_builder.py:build_payout_transaction` · +*Codice:* `plm_engine/psbt_builder.py:select_utxos` · `app/bets/service.py:place_bet` · `plm_engine/psbt_builder.py:build_payout_transaction` · *Test:* `tests/unit/test_psbt_builder.py::test_select_utxos_never_exceeds_the_input_cap`, `tests/unit/test_bets.py::test_place_bet_rejects_the_bet_past_the_participant_cap`, `tests/unit/test_payout_builder.py::test_payout_at_the_participant_cap_stays_well_inside_relay_limits` diff --git a/docs/adr/ADR-24-l-estrazione-commit-reveal-fra-server.md b/docs/adr/ADR-24-l-estrazione-commit-reveal-fra-server.md index 807d9c9..aa14556 100644 --- a/docs/adr/ADR-24-l-estrazione-commit-reveal-fra-server.md +++ b/docs/adr/ADR-24-l-estrazione-commit-reveal-fra-server.md @@ -54,5 +54,5 @@ pubblicati, esito non calcolabile da chi produce o trasmette i blocchi. [ciclo-di-vita-del-round.md](../ciclo-di-vita-del-round.md#3--estrazione), endpoint in [api.md](../api.md) (B-73). -*Codice:* `app/rounds/draw.py:draw_winner` · `app/rounds/scheduler.py:RoundScheduler._close_and_draw` · `app/rounds/scheduler.py:RoundScheduler._complete_draw` · `app/rounds/service.py:open_new_round_if_needed` · `app/api/routes/rounds.py:round_proof` · +*Codice:* `plm_engine/draw.py:draw_winner` · `app/rounds/scheduler.py:RoundScheduler._close_and_draw` · `app/rounds/scheduler.py:RoundScheduler._complete_draw` · `app/rounds/service.py:open_new_round_if_needed` · `app/api/routes/rounds.py:round_proof` · *Test:* `tests/unit/test_draw.py`, `tests/unit/test_draw_proof.py` diff --git a/docs/adr/ADR-26-validazione-degli-header-concatenata-senza-ricalcolo.md b/docs/adr/ADR-26-validazione-degli-header-concatenata-senza-ricalcolo.md index 4f4c91f..8d2173c 100644 --- a/docs/adr/ADR-26-validazione-degli-header-concatenata-senza-ricalcolo.md +++ b/docs/adr/ADR-26-validazione-degli-header-concatenata-senza-ricalcolo.md @@ -31,5 +31,5 @@ in [connessione-electrum.md](../connessione-electrum.md#4-header-validati-non-cr ([LIM-14]); a fermare una catena fabbricata sono la concatenazione, il quorum ([ADR-07](ADR-07-ogni-decisione-sposta-denaro-base-risposta.md)) e il fatto che il seme dipende anche da `server_seed`. -*Codice:* `app/electrum/listener.py:ElectrumListener._apply_header` · `app/rounds/draw.py:header_meets_its_own_target` · +*Codice:* `app/electrum/listener.py:ElectrumListener._apply_header` · `plm_engine/headers.py:header_meets_its_own_target` · *Test:* `tests/unit/test_electrum_listener.py::test_a_multi_block_jump_is_validated_by_fetching_the_headers_in_between`, `tests/unit/test_electrum_listener.py::test_a_fork_is_walked_back_and_followed_instead_of_ending_the_session`, `tests/unit/test_electrum_listener.py::test_a_competing_header_at_the_tip_height_is_a_reorg_to_follow`, `tests/unit/test_draw.py::test_a_header_below_the_pow_limit_is_rejected_even_if_it_meets_its_own_target` diff --git a/docs/adr/ADR-35-aritmetica-satoshi-interi.md b/docs/adr/ADR-35-aritmetica-satoshi-interi.md index 07f1875..bad2e34 100644 --- a/docs/adr/ADR-35-aritmetica-satoshi-interi.md +++ b/docs/adr/ADR-35-aritmetica-satoshi-interi.md @@ -10,5 +10,5 @@ dalla rete: l'importo di una moneta spesa si ricava dalla transazione grezza, non dal valore decimale restituito dal server. -*Codice:* `app/tx/broadcast.py:_prevout_amount` · `app/wallet/psbt_builder.py:estimate_vsize` · +*Codice:* `app/tx/broadcast.py:_prevout_amount` · `plm_engine/psbt_builder.py:estimate_vsize` · *Test:* `tests/unit/test_broadcast.py::test_bump_fee_holds_no_session_open_during_network_calls` diff --git a/docs/adr/ADR-59-motore-plm-pacchetto-senza-framework-ledger-simulato.md b/docs/adr/ADR-59-motore-plm-pacchetto-senza-framework-ledger-simulato.md index b529dcf..015ebb5 100644 --- a/docs/adr/ADR-59-motore-plm-pacchetto-senza-framework-ledger-simulato.md +++ b/docs/adr/ADR-59-motore-plm-pacchetto-senza-framework-ledger-simulato.md @@ -37,4 +37,4 @@ cambiare viste né modelli. - Il ledger simulato non esiste in produzione: è escluso dal profilo `mainnet`. - Requisiti: `ARC` da aggiornare con l'implementazione. -*Codice:* da implementare · *Test:* da implementare +*Codice:* `plm_engine/` (`draw.py`, `headers.py`, `network.py`, `address.py`, `hd.py`, `psbt_builder.py`, `electrum/`); il caricamento della chiave cifrata resta in `app/wallet/hd.py` (stack vecchio) · *Test:* `tests/django/test_engine_package.py` (nessun import di framework), i test del motore sotto `tests/unit/` invariati diff --git a/docs/api.md b/docs/api.md index 2db51fd..6f49967 100644 --- a/docs/api.md +++ b/docs/api.md @@ -653,7 +653,7 @@ esiste una API separata per l'amministrazione, solo un'autenticazione diversa. - **Errori:** `404 round_not_found`; `422`. - **Effetti:** nessuno. *Codice:* `app/api/routes/rounds.py:round_proof`, - `app/rounds/draw.py:draw_winner` · + `plm_engine/draw.py:draw_winner` · *Test:* `tests/unit/test_draw_proof.py` ### QR @@ -673,7 +673,7 @@ esiste una API separata per l'amministrazione, solo un'autenticazione diversa. ripetuta costa solo una lettura in memoria. *Codice:* `app/api/routes/qr.py:address_qr`, `app/api/routes/qr.py:_render_png`, - `app/wallet/address.py:is_valid_plm_address` · + `plm_engine/address.py:is_valid_plm_address` · *Test:* `tests/unit/test_qr.py` ### Segnalazioni di bug @@ -1010,12 +1010,12 @@ dei parametri operativi in | `round_closing` | 400 | `app/bets/service.py:place_bet` | — | il round attivo non accetta più scommesse (scadenza passata o stato diverso da `open`), anche se scoperto dopo la costruzione | sì | | `already_betting` | 400 | `app/bets/service.py:place_bet` | — | l'utente ha già una riga di partecipazione nel round | sì | | `round_full` | 400 | `app/bets/service.py:place_bet` | `max_participants` | il round ha già 400 partecipanti (in qualunque stato) | sì | -| `insufficient_balance` | 400 | `app/bets/service.py:place_bet`, `app/withdrawals/service.py:request_withdrawal`, `app/wallet/psbt_builder.py:select_utxos` | `required_sats` (assente se sollevato da `select_utxos`) | le monete confermate e non spese non coprono l'importo | sì | +| `insufficient_balance` | 400 | `app/bets/service.py:place_bet`, `app/withdrawals/service.py:request_withdrawal`, `plm_engine/psbt_builder.py:select_utxos` | `required_sats` (assente se sollevato da `select_utxos`) | le monete confermate e non spese non coprono l'importo | sì | | `balance_pending_confirmation` | 400 | `app/withdrawals/service.py:request_withdrawal`; anche `app/bets/service.py:place_bet` | `pending_sats` | l'importo sarebbe coperto dal saldo comprensivo del non confermato, ma non da quello confermato | sì | -| `too_many_inputs` | 400 | `app/wallet/psbt_builder.py:select_utxos` | `max_inputs` | servirebbero più di 50 monete in ingresso | sì | -| `balance_leaves_no_change` | 400 | `app/wallet/psbt_builder.py:build_signed_transaction` (solo scommesse) | `required_extra_sats` | dopo la scommessa il resto sarebbe sotto il limite di polvere (294 sat) | sì | -| `amount_below_network_fee` | 400 | `app/wallet/psbt_builder.py:build_signed_transaction` | — | l'importo non copre la commissione di rete | sì | -| `amount_below_dust_limit` | 400 | `app/wallet/psbt_builder.py:build_signed_transaction` | — | al netto della commissione l'importo sarebbe polvere | sì | +| `too_many_inputs` | 400 | `plm_engine/psbt_builder.py:select_utxos` | `max_inputs` | servirebbero più di 50 monete in ingresso | sì | +| `balance_leaves_no_change` | 400 | `plm_engine/psbt_builder.py:build_signed_transaction` (solo scommesse) | `required_extra_sats` | dopo la scommessa il resto sarebbe sotto il limite di polvere (294 sat) | sì | +| `amount_below_network_fee` | 400 | `plm_engine/psbt_builder.py:build_signed_transaction` | — | l'importo non copre la commissione di rete | sì | +| `amount_below_dust_limit` | 400 | `plm_engine/psbt_builder.py:build_signed_transaction` | — | al netto della commissione l'importo sarebbe polvere | sì | | `broadcast_failed` | 502 | `app/bets/service.py:place_bet`, `app/withdrawals/service.py:request_withdrawal` | — (il motivo del rifiuto è nel `message`) | la rete ha rifiutato la trasmissione; tutto è stato annullato | sì | | `invalid_address` | 400 | `app/withdrawals/service.py:request_withdrawal`, `app/api/routes/qr.py:address_qr` | — | non è un indirizzo bech32 PLM valido | sì | | `withdrawal_to_own_address` | 400 | `app/withdrawals/service.py:request_withdrawal` | — | destinazione uguale all'indirizzo di deposito dell'utente | sì | @@ -1033,7 +1033,7 @@ dei parametri operativi in | `method_not_allowed` | 405 | gestore delle eccezioni HTTP in `app/main.py` | — | metodo non ammesso | sì | | `too_many_streams` | 503 | `app/api/routes/rounds.py` (SSE) | — | tetto globale degli stream raggiunto | sì | -Due codici di `app/wallet/psbt_builder.py` — `winner_share_below_network_fee` +Due codici di `plm_engine/psbt_builder.py` — `winner_share_below_network_fee` e `commission_below_dust_limit` — riguardano solo la costruzione del pagamento, che avviene nello scheduler e non attraverso l'API: non arrivano mai a un client (finiscono nel registro di audit, vedi diff --git a/docs/architettura.md b/docs/architettura.md index 544d9ad..3fcc972 100644 --- a/docs/architettura.md +++ b/docs/architettura.md @@ -183,20 +183,20 @@ sono vuoti e non sono elencati. | File | Responsabilità | |---|---| -| `app/wallet/plm_network.py` | Parametri della rete PLM per embit (`PLM_MAINNET`), coin type 746, `ACCOUNT_PATH` | +| `plm_engine/network.py` | Parametri della rete PLM per embit (`PLM_MAINNET`), coin type 746, `ACCOUNT_PATH` | | `app/wallet/keystore.py` | Cifratura/decifratura Fernet della master xprv | | `app/wallet/hd.py` | Generazione della master key, derivazione di indirizzi/chiavi utente (`0/i`), del montepremi di ogni round (`2/`, B-80) e dell'indirizzo di riserva (`1/0`), `derive_round_pool_key` che sceglie la chiave che controlla l'indirizzo salvato sul round, export WIF; la chiave d'account decifrata resta in cache nel processo | -| `app/wallet/address.py` | `is_valid_plm_address`: checksum bech32 + HRP `plm` | +| `plm_engine/address.py` | `is_valid_plm_address`: checksum bech32 + HRP `plm` | | `app/wallet/balance.py` | `recompute_balance` (saldo confermato), `compute_pending_balance` (saldo mostrato) — vedi [registrazione-e-depositi.md](registrazione-e-depositi.md) | -| `app/wallet/psbt_builder.py` | Selezione UTXO, costruzione e firma di scommessa, prelievo e pagamento; limiti `MAX_TX_INPUTS`, `MAX_PAYOUT_TX_INPUTS`, `MAX_PARTICIPANTS_PER_ROUND`, `DUST_LIMIT_SATS`; l'uscita di riserva per l'RBF sul pagamento (`payout_bump_reserve`, B-79) | +| `plm_engine/psbt_builder.py` | Selezione UTXO, costruzione e firma di scommessa, prelievo e pagamento; limiti `MAX_TX_INPUTS`, `MAX_PAYOUT_TX_INPUTS`, `MAX_PARTICIPANTS_PER_ROUND`, `DUST_LIMIT_SATS`; l'uscita di riserva per l'RBF sul pagamento (`payout_bump_reserve`, B-79) | ### Rete Electrum | File | Responsabilità | |---|---| -| `app/electrum/client.py` | `ElectrumClient` (JSON-RPC, timeout per richiesta), `ElectrumEndpoint`, `parse_endpoints`; limite di lettura di 16 MiB per riga, risposta troppo grande o malformata come errore della richiesta e non della connessione. *Da implementare:* pin del certificato per endpoint (B-84) | +| `plm_engine/electrum/client.py` | `ElectrumClient` (JSON-RPC, timeout per richiesta), `ElectrumEndpoint`, `parse_endpoints`; limite di lettura di 16 MiB per riga, risposta troppo grande o malformata come errore della richiesta e non della connessione. *Da implementare:* pin del certificato per endpoint (B-84) | | `app/electrum/listener.py` | `ElectrumListener`: l'unica connessione, rotazione, keepalive, validazione header, corroborazione, sottoscrizioni e accredito — vedi [connessione-electrum.md](connessione-electrum.md). Il docstring della classe cita un metodo `add_address` che non esiste: l'indirizzo di un nuovo utente si aggiunge con `address_for_new_user` | -| `app/electrum/scripthash.py` | `address_to_scripthash`: scripthash Electrum di un indirizzo | +| `plm_engine/electrum/scripthash.py` | `address_to_scripthash`: scripthash Electrum di un indirizzo | ### Dominio @@ -210,7 +210,7 @@ sono vuoti e non sono elencati. | `app/withdrawals/confirmation.py` | Gestore di conferma per il tipo `withdrawal` | | `app/rounds/service.py` | Round attivo, scadenza, accettazione scommesse, `rounds_can_open`, apertura del round, quota del vincitore | | `app/rounds/scheduler.py` | `RoundScheduler`: chiusura, estrazione, pagamento e suoi tentativi | -| `app/rounds/draw.py` | Matematica degli header (hash, prev-hash, target) e scelta del vincitore. Seme commit-reveal e impronta dei partecipanti | +| `plm_engine/headers.py` | Matematica degli header (hash, prev-hash, target) e scelta del vincitore. Seme commit-reveal e impronta dei partecipanti | | `app/rounds/config.py` | `get_round_config`: la riga unica di `round_config`, creata se manca | | `app/rounds/confirmation.py` | Gestore di conferma per il tipo `payout` | | `app/rounds/events.py` | `RoundEventBroadcaster` e il singleton `broadcaster` (SSE) | @@ -413,7 +413,7 @@ implementare» non esistono ancora nel codice (vedi [ARC-60] e [ARC-22]). (`host:porta[:notls][:pin=]` separati da virgola, [ARC-30]); un elenco di riserva malformato blocca l'avvio. L'ordine di rotazione viene scritto nel log. - *Codice:* `app/electrum/client.py:parse_endpoints` · + *Codice:* `plm_engine/electrum/client.py:parse_endpoints` · *Test:* `tests/unit/test_electrum_client.py` - **[ARC-60]** **Controlli di avvio.** Dopo [ARC-19] e [ARC-20] e prima di @@ -526,7 +526,7 @@ implementare» non esistono ancora nel codice (vedi [ARC-60] e [ARC-22]). *Codice:* `app/electrum/listener.py:ElectrumListener.run` · `app/electrum/listener.py:ElectrumListener._apply_header` · `app/electrum/listener.py:ElectrumListener._check_not_stalled` · - `app/electrum/client.py:ElectrumClient.connect` · + `plm_engine/electrum/client.py:ElectrumClient.connect` · *Test:* `tests/unit/test_electrum_listener.py`, `tests/unit/test_electrum_client.py` - **[ARC-27]** **`RoundScheduler`.** A ogni giro (5s) chiama `open_new_round_if_needed` e poi avanza il round attivo, in qualunque stato @@ -609,7 +609,7 @@ La configurazione è divisa in due posti con regole diverse. codice (vedi [limiti-noti.md](limiti-noti.md)). Le conferme dei depositi sono invece configurabili ([ARC-31]). *Codice:* `app/rounds/service.py:winner_share` · - `app/wallet/psbt_builder.py` · `app/tx/confirmation.py` + `plm_engine/psbt_builder.py` · `app/tx/confirmation.py` ## Aggiornamenti in tempo reale (SSE) diff --git a/docs/ciclo-di-vita-del-round.md b/docs/ciclo-di-vita-del-round.md index e788950..9462729 100644 --- a/docs/ciclo-di-vita-del-round.md +++ b/docs/ciclo-di-vita-del-round.md @@ -131,7 +131,7 @@ richiesta di scommessa (vedi `GET /rounds/current` e dalla prova pubblica ([RND-37]) fin dall'apertura. `server_seed` non è esposto da nessun endpoint, `/admin` compreso, finché il vincitore non è salvato ([RND-18]). - *Codice:* `app/rounds/service.py:open_new_round_if_needed`, `app/rounds/draw.py:new_server_seed`, `app/wallet/keystore.py:encrypt_round_seed`, `app/api/routes/rounds.py:current_round` · + *Codice:* `app/rounds/service.py:open_new_round_if_needed`, `plm_engine/draw.py:new_server_seed`, `app/wallet/keystore.py:encrypt_round_seed`, `app/api/routes/rounds.py:current_round` · *Test:* `tests/unit/test_rounds_service.py`, `tests/unit/test_draw_proof.py` - **[RND-35]** **Un indirizzo del montepremi per round**: all'apertura il round riceve un proprio indirizzo `m/84'/746'/0'/2/`, salvato in @@ -227,7 +227,7 @@ giocata, ma il montepremi pubblicizzato non supera mai quello che verrà pagato. Dopo il commit si invia una notifica SSE; da quel momento `participants_hash` e `draw_height` sono pubblici ([RND-37]). - *Codice:* `app/rounds/scheduler.py:RoundScheduler._close_and_draw`, `app/rounds/draw.py:participants_hash` · + *Codice:* `app/rounds/scheduler.py:RoundScheduler._close_and_draw`, `plm_engine/draw.py:participants_hash` · *Test:* `tests/unit/test_scheduler.py`, `tests/unit/test_draw.py`, `tests/unit/test_draw_proof.py` - **[RND-33]** L'altezza del blocco di estrazione è fissata all'ingresso in `drawing` come `draw_height = tip_at_close + 1`, dove `tip_at_close` è @@ -293,7 +293,7 @@ flowchart TB partecipanti; vincitore = il partecipante con `draw_position` uguale all'indice. **Probabilità uguale per tutti**: ogni partecipante ha una e una sola posizione nell'elenco, indipendentemente dall'importo. - *Codice:* `app/rounds/draw.py:draw_seed`, `app/rounds/draw.py:draw_index`, `app/rounds/draw.py:draw_winner`, `app/rounds/scheduler.py:RoundScheduler._complete_draw` · + *Codice:* `plm_engine/draw.py:draw_seed`, `plm_engine/draw.py:draw_index`, `plm_engine/draw.py:draw_winner`, `app/rounds/scheduler.py:RoundScheduler._complete_draw` · *Test:* `tests/unit/test_draw.py`, `tests/unit/test_draw_proof.py` - **[RND-18]** **Verificabile**: in un'unica transazione del database il round salva altezza e hash del blocco (`draw_block_height` = `draw_height`, @@ -416,7 +416,7 @@ del montepremi del round. round si spendono le monete confermate dell'indirizzo condiviso, scelte dalla più grande fino a coprire il montepremi; non abbastanza monete dà `insufficient pool UTXOs`. - *Codice:* `app/rounds/scheduler.py:RoundScheduler._trigger_payout`, `app/wallet/psbt_builder.py:build_payout_transaction` · + *Codice:* `app/rounds/scheduler.py:RoundScheduler._trigger_payout`, `plm_engine/psbt_builder.py:build_payout_transaction` · *Test:* `tests/unit/test_scheduler.py`, `tests/unit/test_payout_builder.py`, `tests/unit/test_round_pool_address.py`, `tests/unit/test_pool_verification.py::test_the_payout_spends_exactly_the_verified_bet_outputs_and_nothing_else` - **[RND-23]** La transazione ha un'uscita verso l'indirizzo del vincitore, una verso l'indirizzo delle commissioni fotografato all'apertura @@ -430,7 +430,7 @@ del montepremi del round. delle commissioni meno la riserva, è inferiore a 294 sat, il pagamento non si costruisce (`winner_share_below_network_fee`, `commission_below_dust_limit`). - *Codice:* `app/wallet/psbt_builder.py:build_payout_transaction` · + *Codice:* `plm_engine/psbt_builder.py:build_payout_transaction` · *Test:* `tests/unit/test_payout_builder.py::test_payout_deducts_fee_only_from_winner_share`, `tests/unit/test_payout_builder.py::test_payout_folds_excess_input_value_into_the_reserve_output`, `tests/unit/test_payout_builder.py::test_payout_leaves_a_dust_sized_excess_to_the_network_fee`, `tests/unit/test_payout_builder.py::test_payout_with_one_participant_at_the_smallest_viable_pool` - **[RND-24]** **Prima si scrive, poi si invia**: prima dell'invio il round registra importo del vincitore (`winner_amount_sats`), commissioni @@ -489,7 +489,7 @@ del montepremi del round. sat/vB è la costante `PAYOUT_BUMP_RESERVE_SAT_VB`. La riserva è tolta dalla quota delle commissioni, mai da quella del vincitore; è ciò che l'RBF riduce ([RND-27]). - *Codice:* `app/wallet/psbt_builder.py:build_payout_transaction`, `app/wallet/psbt_builder.py:payout_bump_reserve`, `app/wallet/hd.py:derive_pool_key` · + *Codice:* `plm_engine/psbt_builder.py:build_payout_transaction`, `plm_engine/psbt_builder.py:payout_bump_reserve`, `app/wallet/hd.py:derive_pool_key` · *Test:* `tests/unit/test_payout_builder.py`, `tests/unit/test_scheduler.py::test_trigger_payout_always_carries_a_bump_reserve_to_the_reserve_address` - **[RND-39]** **Verifica prima del pagamento**: prima di costruire il pagamento, le uscite delle scommesse dei partecipanti vengono verificate diff --git a/docs/connessione-electrum.md b/docs/connessione-electrum.md index c2d9bd1..76313f4 100644 --- a/docs/connessione-electrum.md +++ b/docs/connessione-electrum.md @@ -33,7 +33,7 @@ Le difese sono cinque. voci vuote sono ignorate e i duplicati eliminati mantenendo la prima posizione. Una voce malformata blocca l'avvio subito, non durante il guasto in cui servirebbe. - *Codice:* `app/electrum/client.py:parse_endpoints` · + *Codice:* `plm_engine/electrum/client.py:parse_endpoints` · *Test:* `tests/unit/test_electrum_client.py` - **[ELC-02]** Dopo ogni sessione fallita o caduta si prova **subito** il server successivo nell'elenco, a rotazione; l'attesa crescente (da 1s @@ -51,7 +51,7 @@ Le difese sono cinque. irraggiungibile e si passa al successivo ([ELC-02]). Senza pin la fiducia non viene dal TLS ma dal quorum ([§ 5](#5-il-quorum)). Ogni connessione si apre con la stretta di mano `server.version`. - *Codice:* `app/electrum/client.py:ElectrumClient.connect`, `app/electrum/client.py:ElectrumClient._check_pin`, `app/main.py:_make_electrum_client` · + *Codice:* `plm_engine/electrum/client.py:ElectrumClient.connect`, `plm_engine/electrum/client.py:ElectrumClient._check_pin`, `app/main.py:_make_electrum_client` · *Test:* `tests/unit/test_electrum_client.py` - **[ELC-19]** Il server **rifiuta di avviarsi** se, dopo l'eliminazione dei duplicati, l'elenco contiene meno di **2 server di riserva** oltre al @@ -70,7 +70,7 @@ Le difese sono cinque. 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` · + *Codice:* `plm_engine/electrum/client.py:ElectrumClient._check_genesis`, `plm_engine/network.py:GENESIS_HASH` · *Test:* `tests/unit/test_electrum_client.py` ## 2. Richieste con limite di tempo @@ -82,7 +82,7 @@ Le difese sono cinque. Senza questo limite una risposta mai arrivata poteva bloccare una scommessa (con il blocco per-utente acquisito) o fermare per sempre il controllo delle conferme. - *Codice:* `app/electrum/client.py:ElectrumClient.request`, `app/electrum/client.py:ElectrumClient._read_loop` · + *Codice:* `plm_engine/electrum/client.py:ElectrumClient.request`, `plm_engine/electrum/client.py:ElectrumClient._read_loop` · *Test:* `tests/unit/test_electrum_client.py` - **[ELC-20]** Una riga di risposta può essere lunga fino a **16 MiB** (16 777 216 byte). Una riga più lunga, o una riga che non è JSON valido, @@ -91,7 +91,7 @@ Le difese sono cinque. cui rispondeva fallisce subito con un errore se il suo `id` si legge nei primi o negli ultimi 256 byte della riga; altrimenti fallisce allo scadere di [ELC-04]. - *Codice:* `app/electrum/client.py:ElectrumClient.connect`, `app/electrum/client.py:ElectrumClient._read_loop` · + *Codice:* `plm_engine/electrum/client.py:ElectrumClient.connect`, `plm_engine/electrum/client.py:ElectrumClient._read_loop` · *Test:* `tests/unit/test_electrum_client.py` ## 3. Caduta rilevata @@ -107,7 +107,7 @@ Le difese sono cinque. errore nell'aggiornamento di **un** utente dopo una notifica del suo indirizzo non termina la sessione ([DEP-16](registrazione-e-depositi.md#deposito)). - *Codice:* `app/electrum/listener.py:ElectrumListener._run_once`, `app/electrum/client.py:ElectrumClient.wait_closed`, `app/electrum/listener.py:ElectrumListener._consume_scripthash` · + *Codice:* `app/electrum/listener.py:ElectrumListener._run_once`, `plm_engine/electrum/client.py:ElectrumClient.wait_closed`, `app/electrum/listener.py:ElectrumListener._consume_scripthash` · *Test:* `tests/unit/test_electrum_client.py`, `tests/unit/test_state_consistency.py` - **[ELC-07]** Una connessione viene resa disponibile al resto del sistema **solo dopo** che il primo header è stato applicato: se il client c'è, @@ -192,7 +192,7 @@ passare a un altro server. powLimit un header costa in media 2³² hash, 43 µs per un ASIC da 100 TH/s. Ciò che protegge davvero l'estrazione è il quorum sul blocco ([ELC-15]). - *Codice:* `app/rounds/draw.py:header_meets_its_own_target`, `app/electrum/listener.py:ElectrumListener._apply_header` · + *Codice:* `plm_engine/headers.py:header_meets_its_own_target`, `app/electrum/listener.py:ElectrumListener._apply_header` · *Test:* `tests/unit/test_draw.py`, `tests/unit/test_electrum_listener.py` - **[ELC-12]** **Ogni** avanzamento della punta deve essere collegato alla punta corrente. Un avanzamento di un blocco deve avere come `prev_hash` @@ -205,7 +205,7 @@ passare a un altro server. (`T+1`, o `H` stesso per un avanzamento di un blocco) a non agganciarsi alla punta, non si chiude la sessione: è una possibile riorganizzazione e si segue [ELC-23]. - *Codice:* `app/rounds/draw.py:header_prev_hash`, `app/electrum/listener.py:ElectrumListener._apply_header`, `app/electrum/listener.py:ElectrumListener._fetch_headers`, `app/electrum/client.py:ElectrumClient.get_block_headers` · + *Codice:* `plm_engine/headers.py:header_prev_hash`, `app/electrum/listener.py:ElectrumListener._apply_header`, `app/electrum/listener.py:ElectrumListener._fetch_headers`, `plm_engine/electrum/client.py:ElectrumClient.get_block_headers` · *Test:* `tests/unit/test_draw.py`, `tests/unit/test_electrum_listener.py` - **[ELC-13]** Un header accettato aggiorna insieme altezza e contenuto della punta (mai uno senza l'altro) e la finestra di [ELC-22]. Ogni notifica di diff --git a/docs/legacy-fastapi-notes.md b/docs/legacy-fastapi-notes.md index 6cfa502..4fd6916 100644 --- a/docs/legacy-fastapi-notes.md +++ b/docs/legacy-fastapi-notes.md @@ -4,7 +4,7 @@ ## Project status (old stack) -All 10 stages of the original build order are code-complete and unit-tested — 1157 tests, the old stack's under `tests/unit/` and the Django ones under `tests/django/` (`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 — 1168 tests, the old stack's under `tests/unit/` and the Django ones under `tests/django/` (`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. @@ -30,7 +30,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/electrum_smoke_test.py # manual check: connect, handshake, subscribe to headers, print the tip -python -m pytest # all 1157 tests +python -m pytest # all 1168 tests python -m pytest tests/unit/test_hd.py # one file python -m pytest tests/unit/test_hd.py::test_derivation_is_deterministic # one test ``` diff --git a/docs/limiti-noti.md b/docs/limiti-noti.md index e161010..f665b2e 100644 --- a/docs/limiti-noti.md +++ b/docs/limiti-noti.md @@ -74,7 +74,7 @@ implementato il [piano delle correzioni](piano-correzioni.md). o riserva e non conferma nemmeno al tetto del fee rate resta in attesa, visibile, e non viene abbandonata ([ADR-51](adr/ADR-51-dubbio-liberano-mai-fondi.md)). - *Codice:* `app/tx/broadcast.py:bump_fee` · `app/wallet/psbt_builder.py:build_payout_transaction` · `app/tx/reconcile.py:reconcile_once` + *Codice:* `app/tx/broadcast.py:bump_fee` · `plm_engine/psbt_builder.py:build_payout_transaction` · `app/tx/reconcile.py:reconcile_once` - **[LIM-03]** **L'attesa in `closing` non ha un limite proprio.** Il round aspetta ogni scommessa `building`/`broadcast`. A porre fine all'attesa di @@ -254,7 +254,7 @@ implementato il [piano delle correzioni](piano-correzioni.md). prova pubblica. Resta accettata la collusione fra operatore e minatore ([LIM-25]). - *Codice:* `app/rounds/draw.py:draw_winner` · `app/rounds/scheduler.py:RoundScheduler._close_and_draw` + *Codice:* `plm_engine/draw.py:draw_winner` · `app/rounds/scheduler.py:RoundScheduler._close_and_draw` - **[LIM-14]** **La validazione degli header non ricostruisce la difficoltà reale.** Il bersaglio dichiarato non può essere più facile del limite di rete @@ -275,7 +275,7 @@ implementato il [piano delle correzioni](piano-correzioni.md). riorganizzazioni ([ADR-52](adr/ADR-52-riorganizzazioni-catena-contengono-invece-ignorarle.md)); una validazione completa con le regole di ricalcolo della difficoltà di PLM resta fuori scopo. - *Codice:* `app/rounds/draw.py:header_meets_its_own_target` · `app/electrum/listener.py:ElectrumListener._apply_header` + *Codice:* `plm_engine/headers.py:header_meets_its_own_target` · `app/electrum/listener.py:ElectrumListener._apply_header` - **[LIM-15]** **La sottoscrizione di un nuovo indirizzo è a sforzo singolo.** Se fallisce subito dopo la registrazione, l'indirizzo resta non @@ -328,7 +328,7 @@ implementato il [piano delle correzioni](piano-correzioni.md). - *Per chiuderlo:* un contributo di casualità che l'operatore non conosce (segreti dei giocatori, beacon esterno), scartato in [ADR-24](adr/ADR-24-l-estrazione-commit-reveal-fra-server.md). - *Codice:* `app/rounds/draw.py:draw_winner` · `app/rounds/service.py:open_new_round_if_needed` + *Codice:* `plm_engine/draw.py:draw_winner` · `app/rounds/service.py:open_new_round_if_needed` - **[LIM-27]** **Le soglie di conferma differiscono da quelle del portafoglio di riferimento.** `PalladiumWallet` considera spendibile un'uscita normale @@ -369,7 +369,7 @@ implementato il [piano delle correzioni](piano-correzioni.md). consolidamento automatico; recuperarle è un'operazione manuale ([operativita.md](operativita.md#intervento-manuale-sui-fondi)). - *Codice:* `app/rounds/scheduler.py:RoundScheduler._trigger_payout` · `app/wallet/psbt_builder.py:build_payout_transaction` + *Codice:* `app/rounds/scheduler.py:RoundScheduler._trigger_payout` · `plm_engine/psbt_builder.py:build_payout_transaction` ### Prodotto e interfacce diff --git a/docs/modello-dati.md b/docs/modello-dati.md index 3dc6e47..873f096 100644 --- a/docs/modello-dati.md +++ b/docs/modello-dati.md @@ -636,7 +636,7 @@ restano nella tabella come storico. `fee_amount_sats`) e non riscrive `bump_reserve_sats`. La regola di dominio è in [ciclo-di-vita-del-round.md](ciclo-di-vita-del-round.md) (B-79). *Codice:* `app/rounds/scheduler.py:RoundScheduler._trigger_payout` · - `app/wallet/psbt_builder.py:build_payout_transaction` · + `plm_engine/psbt_builder.py:build_payout_transaction` · `app/tx/broadcast.py:bump_fee` · *Test:* `tests/unit/test_scheduler.py::test_trigger_payout_always_carries_a_bump_reserve_to_the_reserve_address`, `tests/unit/test_broadcast.py::test_a_payout_is_bumped_out_of_its_reserve_output_and_nothing_else`, `tests/unit/test_migrations.py::test_the_bump_reserve_column_exists_at_head_and_is_nullable` @@ -720,7 +720,7 @@ Una scommessa: un utente in un round. l'outpoint che l'elenco dell'estrazione pubblica e che il pagamento spende ([DAT-11]). *Codice:* `app/bets/service.py:place_bet` · - `app/wallet/psbt_builder.py:RECIPIENT_VOUT` · *Test:* `tests/unit/test_bets.py` + `plm_engine/psbt_builder.py:RECIPIENT_VOUT` · *Test:* `tests/unit/test_bets.py` - **[DAT-66]** `draw_position` si scrive una sola volta, all'ingresso in `drawing` ([DAT-65]), per ogni partecipante `confirmed` del round: i @@ -741,7 +741,7 @@ Una scommessa: un utente in un round. Per questo il montepremi si calcola sommando questa colonna, non moltiplicando il numero di partecipanti per il costo (B-11). *Codice:* `app/bets/service.py:place_bet` · - `app/wallet/psbt_builder.py:build_signed_transaction` · + `plm_engine/psbt_builder.py:build_signed_transaction` · `app/api/routes/rounds.py:current_round` · *Test:* `tests/unit/test_bets.py`, `tests/unit/test_round_snapshot.py` - **[DAT-27]** Il numero di righe di un round, contando tutti gli stati, non @@ -752,7 +752,7 @@ Una scommessa: un utente in un round. anche quando la somma dei `bet_amount_sats` del round, contando tutti gli stati, ha già raggiunto quel tetto; la regola di dominio è in [scommesse-e-prelievi.md](scommesse-e-prelievi.md) (B-95). - *Codice:* `app/bets/service.py:place_bet` · `app/wallet/psbt_builder.py` · + *Codice:* `app/bets/service.py:place_bet` · `plm_engine/psbt_builder.py` · *Test:* `tests/unit/test_bets.py`, `tests/unit/test_round_snapshot.py` ### `round_config` @@ -1109,7 +1109,7 @@ dall'utente. scrivono insieme alla creazione e non cambiano più: un bump RBF riduce il resto, non l'output del destinatario. *Codice:* `app/withdrawals/service.py:request_withdrawal` · - `app/wallet/psbt_builder.py:build_signed_transaction` · + `plm_engine/psbt_builder.py:build_signed_transaction` · *Test:* `tests/unit/test_withdrawals.py` ### `bug_reports` @@ -1249,7 +1249,7 @@ letti con una scansione completa. piattaforma. La ripartizione è nel codice, non in `round_config`. *Codice:* `app/rounds/service.py:winner_share` · `app/rounds/scheduler.py:RoundScheduler._trigger_payout` · - `app/wallet/psbt_builder.py:build_payout_transaction` · + `plm_engine/psbt_builder.py:build_payout_transaction` · *Test:* `tests/unit/test_payout_builder.py`, `tests/unit/test_scheduler.py`, `tests/unit/test_pool_verification.py::test_a_reorged_out_bet_is_excluded_and_the_split_is_computed_on_what_is_there` - ~~**[DAT-47]**~~ Assorbito da [RND-12](ciclo-di-vita-del-round.md): l'attesa diff --git a/docs/operativita.md b/docs/operativita.md index d75a65b..7fd9625 100644 --- a/docs/operativita.md +++ b/docs/operativita.md @@ -67,7 +67,7 @@ dovranno allora rispettare quel proprietario. motivo nell'output di `docker compose logs app`. *Codice:* `Dockerfile` (`CMD`), `app/main.py:lifespan`, `app/config.py:validate_runtime_secrets`, - `app/electrum/client.py:parse_endpoints`, `app/wallet/hd.py:_load_account_key` · + `plm_engine/electrum/client.py:parse_endpoints`, `app/wallet/hd.py:_load_account_key` · *Test:* `tests/unit/test_config.py`, `tests/unit/test_electrum_client.py` - **[OPS-03]** Il database SQLite lavora in modalità **WAL**: accanto a diff --git a/docs/registrazione-e-depositi.md b/docs/registrazione-e-depositi.md index ed09308..2c5e991 100644 --- a/docs/registrazione-e-depositi.md +++ b/docs/registrazione-e-depositi.md @@ -211,7 +211,7 @@ Gli aggiornamenti dello stesso utente sono messi in fila ([DEP-15]). questo documento. Non è spendibile in modo economico e, se accreditata, farebbe crescere senza limite il lavoro di ogni aggiornamento; chiunque può inviarne a qualunque indirizzo pubblico. - *Codice:* `app/deposits/service.py:find_new_credit_candidates`, `app/deposits/service.py:credit_confirmed_utxos`, `app/wallet/psbt_builder.py:DUST_LIMIT_SATS`, `app/wallet/psbt_builder.py:select_utxos` · + *Codice:* `app/deposits/service.py:find_new_credit_candidates`, `app/deposits/service.py:credit_confirmed_utxos`, `plm_engine/psbt_builder.py:DUST_LIMIT_SATS`, `plm_engine/psbt_builder.py:select_utxos` · *Test:* `tests/unit/test_deposits.py`, `tests/unit/test_psbt_builder.py` - **[DEP-02]** Un aggiornamento dell'indirizzo di un utente legge l'elenco delle monete non spese (`listunspent`) dal server Electrum attivo e procede diff --git a/docs/scommesse-e-prelievi.md b/docs/scommesse-e-prelievi.md index b8ed809..198e03b 100644 --- a/docs/scommesse-e-prelievi.md +++ b/docs/scommesse-e-prelievi.md @@ -11,7 +11,7 @@ delle risposte e il catalogo completo dei codici di errore sono in [api.md](api.md); cosa succede a una transazione dopo l'invio in [transazioni-e-riconciliazione.md](transazioni-e-riconciliazione.md). -Costanti citate in questo documento (tutte in `app/wallet/psbt_builder.py`): +Costanti citate in questo documento (tutte in `plm_engine/psbt_builder.py`): | Costante | Valore | Significato | |---|---|---| @@ -58,7 +58,7 @@ cifra. Il **costo** è quello del round ([BET-21]): | **[BET-10]** | Il costo meno la commissione di rete resta positivo e di almeno 294 sat | `amount_below_network_fee`, `amount_below_dust_limit` | *Codice:* `app/bets/service.py:place_bet`, `app/rounds/service.py:round_accepts_bets`, -`app/wallet/psbt_builder.py:select_utxos`, `app/wallet/psbt_builder.py:build_signed_transaction` · +`plm_engine/psbt_builder.py:select_utxos`, `plm_engine/psbt_builder.py:build_signed_transaction` · *Test:* `tests/unit/test_bets.py`, `tests/unit/test_withdrawals.py`, `tests/unit/test_psbt_builder.py` (nessun test verifica `no_round_open`) @@ -74,7 +74,7 @@ ancora `open` oltre la scadenza. lascia 1 PLM di resto. Lo stesso vale per il prelievo: la riduzione di [WDR-09] scatta solo quando nessuna combinazione di monete lascia un resto sufficiente. - *Codice:* `app/wallet/psbt_builder.py:select_utxos` · + *Codice:* `plm_engine/psbt_builder.py:select_utxos` · *Test:* `tests/unit/test_psbt_builder.py` - **[BET-21]** Il **costo** di una scommessa è il `bet_amount_sats` @@ -107,7 +107,7 @@ ancora `open` oltre la scadenza. il numero di monete non impedisca mai di pagare un round. La differenza lascia spazio ad altre monete presenti sull'indirizzo del montepremi del round (pagamenti arrivati da fuori). - *Codice:* `app/wallet/psbt_builder.py:MAX_PARTICIPANTS_PER_ROUND`, `app/bets/service.py:place_bet` · + *Codice:* `plm_engine/psbt_builder.py:MAX_PARTICIPANTS_PER_ROUND`, `app/bets/service.py:place_bet` · *Test:* `tests/unit/test_payout_builder.py`, `tests/unit/test_bets.py` Con un indirizzo per round @@ -151,7 +151,7 @@ flowchart TB l'**indirizzo del montepremi del round** (`rounds.pool_address`, [RND-35](ciclo-di-vita-del-round.md#0--apertura)), e il resto (monete spese meno il costo) verso l'indirizzo dell'utente. - *Codice:* `app/wallet/psbt_builder.py:select_utxos`, `app/wallet/psbt_builder.py:build_signed_transaction`, `app/bets/service.py:place_bet` · + *Codice:* `plm_engine/psbt_builder.py:select_utxos`, `plm_engine/psbt_builder.py:build_signed_transaction`, `app/bets/service.py:place_bet` · *Test:* `tests/unit/test_psbt_builder.py`, `tests/unit/test_round_pool_address.py` - **[BET-13]** La **commissione di rete** è la dimensione stimata della transazione per `fee_rate_sat_vb` (1 sat/vB predefinito, modificabile da @@ -160,7 +160,7 @@ flowchart TB (`bet_amount_sats`) è proprio questo netto. Per questo il montepremi si calcola sommando gli importi effettivi delle scommesse, non moltiplicando il numero di giocatori per il costo. - *Codice:* `app/wallet/psbt_builder.py:build_signed_transaction`, `app/bets/service.py:place_bet` · + *Codice:* `plm_engine/psbt_builder.py:build_signed_transaction`, `app/bets/service.py:place_bet` · *Test:* `tests/unit/test_psbt_builder.py`, `tests/unit/test_rounds_route.py` - **[BET-14]** Il **resto** torna sempre allo stesso indirizzo dell'utente ed è sempre di almeno 294 sat (`DUST_LIMIT_SATS`). A differenza del prelievo, la @@ -171,7 +171,7 @@ flowchart TB [TX-11](transazioni-e-riconciliazione.md#rbf-accelerare-una-transazione-lenta): un resto di 294 sat non regge una riduzione (l'aumento minimo è di 141 sat a 1 sat/vB), quindi garantisce una sola accelerazione, che lo elimina. - *Codice:* `app/wallet/psbt_builder.py:build_signed_transaction` · + *Codice:* `plm_engine/psbt_builder.py:build_signed_transaction` · *Test:* `tests/unit/test_withdrawals.py` (i test del resto delle scommesse sono lì: `test_a_bet_from_a_balance_equal_to_the_bet_is_refused`, `test_a_bet_with_a_dust_limit_of_headroom_is_accepted`), @@ -225,7 +225,7 @@ flowchart TB - **[BET-19]** Tutte le scommesse hanno **la stessa probabilità** di vincere, indipendentemente dall'importo netto e da tutto il resto ([RND-17](ciclo-di-vita-del-round.md#3--estrazione)). - *Codice:* `app/rounds/draw.py:draw_winner` · + *Codice:* `plm_engine/draw.py:draw_winner` · *Test:* `tests/unit/test_draw.py` ## Prelievo @@ -254,8 +254,8 @@ HTTP 400 prima che si muova qualunque cifra: | **[WDR-06]** | L'importo si copre con al massimo 50 monete (`MAX_TX_INPUTS`) | `too_many_inputs` (parametro `max_inputs`) | | **[WDR-07]** | L'importo meno la commissione di rete resta positivo e di almeno 294 sat | `amount_below_network_fee`, `amount_below_dust_limit` | -*Codice:* `app/withdrawals/service.py:request_withdrawal`, `app/wallet/address.py:is_valid_plm_address`, -`app/wallet/psbt_builder.py:build_signed_transaction` · +*Codice:* `app/withdrawals/service.py:request_withdrawal`, `plm_engine/address.py:is_valid_plm_address`, +`plm_engine/psbt_builder.py:build_signed_transaction` · *Test:* `tests/unit/test_withdrawals.py`, `tests/unit/test_psbt_builder.py` La struttura è identica alla scommessa: transazione firmata dall'indirizzo @@ -267,7 +267,7 @@ solo se la rete rifiuta esplicitamente, RBF se non conferma in tempo. grande, ingressi sostituibili BIP125); all'indirizzo esterno arriva l'importo meno la commissione di rete, il resto torna all'indirizzo dell'utente. - *Codice:* `app/wallet/psbt_builder.py:build_signed_transaction` · + *Codice:* `plm_engine/psbt_builder.py:build_signed_transaction` · *Test:* `tests/unit/test_psbt_builder.py`, `tests/unit/test_withdrawals.py` - **[WDR-09]** **Resto garantito.** Se l'importo richiesto lascerebbe un resto inferiore a 294 sat (`DUST_LIMIT_SATS`) — ad esempio il prelievo @@ -279,7 +279,7 @@ solo se la rete rifiuta esplicitamente, RBF se non conferma in tempo. (`amount_sent_sats`). Come per la scommessa ([BET-14]), questo resto è l'uscita che l'RBF riduce o elimina ([TX-11](transazioni-e-riconciliazione.md#rbf-accelerare-una-transazione-lenta)). - *Codice:* `app/wallet/psbt_builder.py:build_signed_transaction`, `app/withdrawals/service.py:request_withdrawal` · + *Codice:* `plm_engine/psbt_builder.py:build_signed_transaction`, `app/withdrawals/service.py:request_withdrawal` · *Test:* `tests/unit/test_withdrawals.py`, `tests/unit/test_psbt_builder.py` - **[WDR-15]** L'importo ridotto da [WDR-09] viene verificato di nuovo contro il minimo di [WDR-04]: se è sceso sotto `bet_amount_sats`, il diff --git a/docs/sicurezza.md b/docs/sicurezza.md index 255989e..9c69916 100644 --- a/docs/sicurezza.md +++ b/docs/sicurezza.md @@ -203,7 +203,7 @@ sì che un backup dei dati non contenga entrambe. `m/84'/746'/0'/0/`, un indice per utente, P2WPKH con HRP `plm`. *Codice:* `app/wallet/hd.py:derive_user_key`, `app/wallet/hd.py:derive_user_address`, - `app/wallet/plm_network.py` · + `plm_engine/network.py` · *Test:* `tests/unit/test_hd.py` - **[SEC-08]** Le chiavi del montepremi — una per round, @@ -684,7 +684,7 @@ di discrezione, non una protezione: la pagina è pubblica, gli endpoint no. persi. Il prelievo verso il proprio indirizzo di deposito è rifiutato, e così quello verso un indirizzo del montepremi, di riserva o delle commissioni ([scommesse-e-prelievi.md](scommesse-e-prelievi.md#prelievo)). - *Codice:* `app/wallet/address.py:is_valid_plm_address`, + *Codice:* `plm_engine/address.py:is_valid_plm_address`, `app/withdrawals/service.py:request_withdrawal` · *Test:* `tests/unit/test_withdrawals.py`, `tests/unit/test_qr.py`, `tests/unit/test_round_pool_address.py` diff --git a/docs/transazioni-e-riconciliazione.md b/docs/transazioni-e-riconciliazione.md index cb769ec..63b4655 100644 --- a/docs/transazioni-e-riconciliazione.md +++ b/docs/transazioni-e-riconciliazione.md @@ -124,7 +124,7 @@ monete: `transaction already in block chain`) resta solo una scorciatoia che salta la verifica: un messaggio non riconosciuto non può più far liberare le monete di una transazione partita, al massimo costa una verifica in più. - *Codice:* `app/tx/outcome.py:broadcast_with_verdict`, `app/electrum/client.py:ElectrumRpcError`, `app/electrum/listener.py:ElectrumListener.transaction_known`, `app/bets/service.py:_release_failed_bet`, `app/withdrawals/service.py:_release_failed_withdrawal` · + *Codice:* `app/tx/outcome.py:broadcast_with_verdict`, `plm_engine/electrum/client.py:ElectrumRpcError`, `app/electrum/listener.py:ElectrumListener.transaction_known`, `app/bets/service.py:_release_failed_bet`, `app/withdrawals/service.py:_release_failed_withdrawal` · *Test:* `tests/unit/test_broadcast_outcome.py`, `tests/unit/test_electrum_client.py`, `tests/unit/test_bets.py`, `tests/unit/test_withdrawals.py` - **[TX-20]** **Invio incerto.** Se l'invio di una scommessa o di un prelievo finisce senza una risposta del server (timeout, connessione caduta, errore @@ -177,7 +177,7 @@ monete: il listener non lo tiene più, è quello su cui il quorum concorda. Senza quorum, o con una prova non valida, la riga resta `pending` e si riprova al giro successivo. - *Codice:* `app/tx/confirmation.py:poll_once`, `app/electrum/listener.py:ElectrumListener.confirmation_proven`, `app/electrum/merkle.py:proof_matches_header` · + *Codice:* `app/tx/confirmation.py:poll_once`, `app/electrum/listener.py:ElectrumListener.confirmation_proven`, `plm_engine/electrum/merkle.py:proof_matches_header` · *Test:* `tests/unit/test_confirmation_proof.py` - **[TX-07]** Alla conferma la riga passa a `confirmed` e, nella stessa transazione del database, viene chiamato il gestore del suo tipo; poi si diff --git a/app/wallet/address.py b/plm_engine/address.py similarity index 95% rename from app/wallet/address.py rename to plm_engine/address.py index a7bae9c..ed2c0b3 100644 --- a/app/wallet/address.py +++ b/plm_engine/address.py @@ -12,7 +12,7 @@ tells the user (bech32 `plm1q...` only). from embit import script from embit.base import EmbitError -from app.wallet.plm_network import PLM_MAINNET +from plm_engine.network import PLM_MAINNET _BECH32_PREFIX = PLM_MAINNET["bech32"] + "1" diff --git a/plm_engine/electrum/__init__.py b/plm_engine/electrum/__init__.py new file mode 100644 index 0000000..6bd7e8a --- /dev/null +++ b/plm_engine/electrum/__init__.py @@ -0,0 +1 @@ +"""Electrum client and the pure checks around it (ADR-59, roadmap B1).""" diff --git a/app/electrum/client.py b/plm_engine/electrum/client.py similarity index 99% rename from app/electrum/client.py rename to plm_engine/electrum/client.py index 58ec96e..0cf2788 100644 --- a/app/electrum/client.py +++ b/plm_engine/electrum/client.py @@ -7,7 +7,7 @@ import re import ssl from typing import NamedTuple -from app.wallet.plm_network import GENESIS_HASH +from plm_engine.network import GENESIS_HASH logger = logging.getLogger(__name__) diff --git a/app/electrum/merkle.py b/plm_engine/electrum/merkle.py similarity index 100% rename from app/electrum/merkle.py rename to plm_engine/electrum/merkle.py diff --git a/app/electrum/quorum.py b/plm_engine/electrum/quorum.py similarity index 100% rename from app/electrum/quorum.py rename to plm_engine/electrum/quorum.py diff --git a/app/electrum/scripthash.py b/plm_engine/electrum/scripthash.py similarity index 100% rename from app/electrum/scripthash.py rename to plm_engine/electrum/scripthash.py diff --git a/plm_engine/hd.py b/plm_engine/hd.py new file mode 100644 index 0000000..d5218fa --- /dev/null +++ b/plm_engine/hd.py @@ -0,0 +1,52 @@ +"""HD derivation from an account key, pure (ADR-59, roadmap B1): no settings, no files, no database. + +The account key (`m/84'/746'/0'`) is handed in by whoever holds the master key; this module only +derives from it. Branch 0 is users, branch 1 the reserve pool key, branch 2 one pool key per round +(B-80, RND-35). +""" + +from embit import script +from embit.bip32 import HDKey +from embit.ec import PrivateKey + +from .network import PLM_MAINNET + + +def user_key(account: HDKey, derivation_index: int) -> HDKey: + return account.derive(f"0/{derivation_index}") + + +def address_of(key: HDKey) -> str: + return script.p2wpkh(key.to_public()).address(network=PLM_MAINNET) + + +def user_address(account: HDKey, derivation_index: int) -> str: + return address_of(user_key(account, derivation_index)) + + +def user_wif(account: HDKey, derivation_index: int) -> str: + key = user_key(account, derivation_index) + return PrivateKey(key.secret, compressed=True, network=PLM_MAINNET).wif(network=PLM_MAINNET) + + +def pool_key(account: HDKey, round_id: int | None = None) -> HDKey: + """A round's own key on branch 2, or the reserve key (branch 1, index 0) without a `round_id`.""" + if round_id is None: + return account.derive("1/0") + if round_id < 1: + raise ValueError(f"invalid round id {round_id}") + return account.derive(f"2/{round_id}") + + +def pool_address(account: HDKey, round_id: int | None = None) -> str: + return address_of(pool_key(account, round_id)) + + +def round_pool_key(account: HDKey, round_id: int, stored_address: str) -> HDKey: + """The key that controls `stored_address`, the address stored on round `round_id`: the round's own, or + the reserve key for a round opened before B-80. A mismatch fails loudly instead of building a transaction + that spends someone else's coins.""" + for key in (pool_key(account, round_id), pool_key(account)): + if address_of(key) == stored_address: + return key + raise ValueError(f"round {round_id}: no pool key controls the stored address {stored_address!r}") diff --git a/app/rounds/draw.py b/plm_engine/headers.py similarity index 96% rename from app/rounds/draw.py rename to plm_engine/headers.py index eff8ff1..00ded1b 100644 --- a/app/rounds/draw.py +++ b/plm_engine/headers.py @@ -1,3 +1,5 @@ +"""Block-header checks, pure (ADR-59, roadmap B1): the hash, the previous hash and the proof-of-work floor (ELC-11).""" + import hashlib # Byte offsets of a standard 80-byte block header: version(4) + prev_block(32) + @@ -90,12 +92,3 @@ def header_meets_its_own_target(header_hex: str) -> bool: # The draw primitives live in `plm_engine.draw` (shared with the Django site); re-exported here so the # old modules and their tests keep working until the old backend is removed (roadmap D1). -from plm_engine.draw import ( # noqa: E402,F401 - draw_index, - draw_seed, - draw_winner, - new_server_seed, - participants_hash, - server_seed_commitment, - sha256_hex, -) diff --git a/app/wallet/plm_network.py b/plm_engine/network.py similarity index 100% rename from app/wallet/plm_network.py rename to plm_engine/network.py diff --git a/app/wallet/psbt_builder.py b/plm_engine/psbt_builder.py similarity index 100% rename from app/wallet/psbt_builder.py rename to plm_engine/psbt_builder.py diff --git a/roadmap.md b/roadmap.md index 67ee470..32334fa 100644 --- a/roadmap.md +++ b/roadmap.md @@ -39,7 +39,7 @@ Uscita: un giocatore completa il round dimostrativo in `localhost`, l'operatore Uscita: flusso completo su regtest; un riavvio durante il broadcast, due richieste concorrenti e una riorganizzazione simulata lasciano dati e fondi riconciliabili. -- [ ] **B1 · Pacchetto `plm_engine`** (le primitive dell'estrazione sono già state spostate in A4). Spostamento dei moduli senza database (derivazione HD, `psbt_builder`, client Electrum, `merkle`, `draw`) e dei loro test, senza cambiare il comportamento. *Requisiti:* ADR-59. *Test:* i test esistenti dei moduli passano invariati. +- [x] **B1 · Pacchetto `plm_engine`** (le primitive dell'estrazione sono già state spostate in A4). Spostamento dei moduli senza database (derivazione HD, `psbt_builder`, client Electrum, `merkle`, `draw`) e dei loro test, senza cambiare il comportamento. *Requisiti:* ADR-59. *Test:* i test esistenti dei moduli passano invariati. - [ ] **B2 · Profilo di rete.** `PLM_NETWORK=regtest|mainnet` (hrp, prefissi, genesis, powLimit), conferma esplicita per `mainnet`, validazione degli indirizzi con l'hrp del profilo. *Requisiti:* ADR-58, ELC-30. *Test:* indirizzi e genesis per ciascun profilo. - [ ] **B3 · Ambiente regtest e fixture.** Compose con nodo e Fulcrum regtest (profilo `regtest`), script che genera blocchi e fondi, fixture di integrazione che si salta se il regtest non c'è. *Test:* smoke di connessione e generazione di un blocco. - [ ] **B4 · Modelli di catena.** UTXO, transazioni con tutte le versioni TXID, depositi, assegnazione dell'indice HD; la chiave di firma è accessibile solo al processo worker. *Requisiti:* DAT, TX. *Test:* vincoli, derivazione identica a parità di input. diff --git a/scripts/electrum_smoke_test.py b/scripts/electrum_smoke_test.py index 585c961..0b3e5f4 100644 --- a/scripts/electrum_smoke_test.py +++ b/scripts/electrum_smoke_test.py @@ -7,7 +7,7 @@ Usage: PYTHONPATH=. python scripts/electrum_smoke_test.py import asyncio from app.config import settings -from app.electrum.client import ElectrumClient +from plm_engine.electrum.client import ElectrumClient async def main() -> None: diff --git a/tests/django/test_engine_package.py b/tests/django/test_engine_package.py new file mode 100644 index 0000000..692bbe5 --- /dev/null +++ b/tests/django/test_engine_package.py @@ -0,0 +1,21 @@ +"""B1 — `plm_engine` is framework-free: it never imports Django, the old FastAPI stack or a database layer (ADR-59).""" + +import ast +from pathlib import Path + +import pytest + +ENGINE = Path(__file__).resolve().parents[2] / "plm_engine" +FORBIDDEN = {"django", "apps", "app", "config", "sqlalchemy", "fastapi", "alembic"} + + +@pytest.mark.parametrize("path", sorted(ENGINE.rglob("*.py")), ids=lambda p: str(p.relative_to(ENGINE))) +def test_the_engine_imports_no_framework(path): + tree = ast.parse(path.read_text()) + imported = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + imported |= {alias.name.split(".")[0] for alias in node.names} + elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module: + imported.add(node.module.split(".")[0]) + assert not imported & FORBIDDEN, f"{path.name} imports {sorted(imported & FORBIDDEN)}" diff --git a/tests/django/test_lifecycle.py b/tests/django/test_lifecycle.py index 8b339a3..ef22075 100644 --- a/tests/django/test_lifecycle.py +++ b/tests/django/test_lifecycle.py @@ -462,14 +462,3 @@ def test_the_round_secret_needs_the_right_key(settings): settings.SECRET_KEY = "another-key-" + "y" * 50 with pytest.raises(RuntimeError): decrypt_seed(token) - - -def test_the_old_draw_module_and_the_engine_share_one_implementation(): - """ADR-59: the primitives live once, in `plm_engine.draw`; the old module re-exports them.""" - import plm_engine.draw as engine - from app.rounds import draw as old - - for name in ("draw_seed", "draw_index", "draw_winner", "participants_hash", "new_server_seed", - "server_seed_commitment", "sha256_hex"): - assert getattr(old, name) is getattr(engine, name) - assert engine.sha256_hex(b"x") == hashlib.sha256(b"x").hexdigest() diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py index 1b2fa69..9e5ce53 100644 --- a/tests/unit/conftest.py +++ b/tests/unit/conftest.py @@ -38,6 +38,6 @@ def _registration_open(monkeypatch): # target (`0x207fffff`) and this swaps in a limit that allows it. Done at import, not in a # fixture, because some test modules mine headers while they are being collected. The # tests that exercise the limit itself put `MAINNET_POW_LIMIT` back with monkeypatch. -from app.rounds import draw as _draw # noqa: E402 +from plm_engine import headers as _draw # noqa: E402 _draw.POW_LIMIT = (1 << 256) - 1 diff --git a/tests/unit/fake_network.py b/tests/unit/fake_network.py index 3f9f999..a3e695a 100644 --- a/tests/unit/fake_network.py +++ b/tests/unit/fake_network.py @@ -1,6 +1,6 @@ """Test doubles for what the services ask of the network (B-76 and after).""" -from app.electrum.client import ElectrumRpcError +from plm_engine.electrum.client import ElectrumRpcError def rpc_error(message: str, code: int = -26) -> ElectrumRpcError: @@ -72,7 +72,7 @@ class ScriptedNetwork(FakeNetwork): self.rebroadcast_calls: list[str] = [] async def get_histories(self, scripthash): - from app.electrum.quorum import ServerAnswers + from plm_engine.electrum.quorum import ServerAnswers self.history_calls += 1 return ServerAnswers(self.active, self.others, self.others_needed) @@ -81,7 +81,7 @@ class ScriptedNetwork(FakeNetwork): return self.spender async def rebroadcast_everywhere(self, raw_tx_hex): - from app.electrum.quorum import ServerAnswers + from plm_engine.electrum.quorum import ServerAnswers self.rebroadcast_calls.append(raw_tx_hex) active, others = self.rebroadcast if self.rebroadcast is not None else (None, (None, None)) diff --git a/tests/unit/test_admin.py b/tests/unit/test_admin.py index ac061f2..dc548c7 100644 --- a/tests/unit/test_admin.py +++ b/tests/unit/test_admin.py @@ -150,7 +150,7 @@ async def test_admin_exports_user_privkey(client): from app.db import base as db_base from app.db.models import User from app.wallet.hd import derive_user_address, derive_user_key - from app.wallet.plm_network import PLM_MAINNET + from plm_engine.network import PLM_MAINNET async with db_base.AsyncSessionLocal() as session: user = User( diff --git a/tests/unit/test_balance.py b/tests/unit/test_balance.py index a6293a5..32400d9 100644 --- a/tests/unit/test_balance.py +++ b/tests/unit/test_balance.py @@ -119,7 +119,7 @@ async def test_pending_balance_does_not_double_count_change_already_credited(ses pending = (await session.scalars(select(PendingTransaction))).one() from embit.transaction import Transaction - from app.wallet.plm_network import PLM_MAINNET + from plm_engine.network import PLM_MAINNET tx = Transaction.parse(bytes.fromhex(pending.raw_tx_hex)) change_vout, change_out = next( diff --git a/tests/unit/test_bets.py b/tests/unit/test_bets.py index 82795bf..0762d8e 100644 --- a/tests/unit/test_bets.py +++ b/tests/unit/test_bets.py @@ -13,7 +13,7 @@ from app.db.models import AuditLog, PendingTransaction, Round, RoundConfig, Roun from app.rounds.events import broadcaster from app.rounds.service import open_new_round_if_needed from app.wallet.hd import derive_user_address -from app.wallet.psbt_builder import MAX_PARTICIPANTS_PER_ROUND, MAX_TX_INPUTS +from plm_engine.psbt_builder import MAX_PARTICIPANTS_PER_ROUND, MAX_TX_INPUTS from tests.unit.fake_network import FakeNetwork, rpc_error diff --git a/tests/unit/test_broadcast.py b/tests/unit/test_broadcast.py index 02e5752..b74570a 100644 --- a/tests/unit/test_broadcast.py +++ b/tests/unit/test_broadcast.py @@ -11,8 +11,8 @@ from app.config import settings from app.db.base import Base from app.db.models import PendingTransaction, User from app.tx.broadcast import RbfError, bump_fee, should_bump -from app.wallet.plm_network import PLM_MAINNET -from app.wallet.psbt_builder import MAX_FEE_RATE_SAT_VB, Utxo, build_signed_transaction, estimate_vsize +from plm_engine.network import PLM_MAINNET +from plm_engine.psbt_builder import MAX_FEE_RATE_SAT_VB, Utxo, build_signed_transaction, estimate_vsize def _key(seed_byte: int) -> HDKey: @@ -224,7 +224,7 @@ async def test_bump_fee_raises_when_no_change_output(session_factory): from embit.transaction import Transaction, TransactionInput, TransactionOutput from app.wallet.hd import derive_user_address, derive_user_key - from app.wallet.psbt_builder import RBF_SEQUENCE + from plm_engine.psbt_builder import RBF_SEQUENCE signer = derive_user_key(0) my_address = derive_user_address(0) @@ -576,7 +576,7 @@ async def _seed_payout(session_factory, *, n: int = 3, bet: int = 1_000_000_000, from app.db.models import Round from app.rounds.service import winner_share from app.wallet.hd import derive_pool_address, derive_round_pool_key - from app.wallet.psbt_builder import build_payout_transaction + from plm_engine.psbt_builder import build_payout_transaction pool_address = derive_pool_address(1) pool_key = derive_round_pool_key(1, pool_address) diff --git a/tests/unit/test_broadcast_outcome.py b/tests/unit/test_broadcast_outcome.py index 357fa9f..796255d 100644 --- a/tests/unit/test_broadcast_outcome.py +++ b/tests/unit/test_broadcast_outcome.py @@ -16,7 +16,7 @@ from sqlalchemy import select from app.bets.service import BetError, place_bet from app.db.models import AuditLog, PendingTransaction, RoundParticipant, User, UtxoEvent, Withdrawal -from app.electrum.client import ElectrumEndpoint, ElectrumError +from plm_engine.electrum.client import ElectrumEndpoint, ElectrumError from app.electrum.listener import ElectrumListener from app.rounds.events import broadcaster from app.rounds.scheduler import RoundScheduler diff --git a/tests/unit/test_confirmation.py b/tests/unit/test_confirmation.py index a0c6b65..40c2e92 100644 --- a/tests/unit/test_confirmation.py +++ b/tests/unit/test_confirmation.py @@ -8,7 +8,7 @@ from sqlalchemy import select from app.config import settings from app.db.base import Base from app.db.models import PendingTransaction, Round, RoundParticipant, User -from app.electrum.scripthash import address_to_scripthash +from plm_engine.electrum.scripthash import address_to_scripthash from app.tx.confirmation import poll_once from tests.unit.fake_network import FakeNetwork from app.wallet.hd import derive_pool_address, derive_user_address diff --git a/tests/unit/test_confirmation_proof.py b/tests/unit/test_confirmation_proof.py index 02ab2cb..42d1011 100644 --- a/tests/unit/test_confirmation_proof.py +++ b/tests/unit/test_confirmation_proof.py @@ -15,10 +15,10 @@ from sqlalchemy import select import app.bets.confirmation # noqa: F401 (registers the "bet" handler) from app.db.models import AuditLog, PendingTransaction, Round, RoundParticipant, User, UtxoEvent -from app.electrum.client import ElectrumEndpoint +from plm_engine.electrum.client import ElectrumEndpoint from app.electrum.listener import ElectrumListener -from app.electrum.merkle import header_merkle_root, merkle_root_from_branch, proof_matches_header -from app.rounds.draw import header_meets_its_own_target +from plm_engine.electrum.merkle import header_merkle_root, merkle_root_from_branch, proof_matches_header +from plm_engine.headers import header_meets_its_own_target from app.tx.confirmation import poll_once from app.wallet.hd import derive_user_address from tests.unit.fake_network import FakeNetwork diff --git a/tests/unit/test_deposits.py b/tests/unit/test_deposits.py index 589321f..e818c79 100644 --- a/tests/unit/test_deposits.py +++ b/tests/unit/test_deposits.py @@ -215,7 +215,7 @@ async def test_find_new_credit_candidates_skips_unconfirmed_and_already_known(se async def test_dust_is_never_credited_nor_offered_as_a_candidate(session_factory, user_id): """DEP-01 / B-75: anyone can send dust to a public address.""" from app.deposits.service import find_new_credit_candidates - from app.wallet.psbt_builder import DUST_LIMIT_SATS + from plm_engine.psbt_builder import DUST_LIMIT_SATS entries = [ {"tx_hash": "e1" * 32, "tx_pos": 0, "height": 100, "value": DUST_LIMIT_SATS - 1}, diff --git a/tests/unit/test_draw.py b/tests/unit/test_draw.py index 1629d2b..0e96902 100644 --- a/tests/unit/test_draw.py +++ b/tests/unit/test_draw.py @@ -1,7 +1,7 @@ import pytest -from app.rounds.draw import ( - draw_winner, +from plm_engine.draw import draw_winner +from plm_engine.headers import ( header_hex_to_block_hash, header_meets_its_own_target, header_prev_hash, @@ -58,7 +58,7 @@ def test_draw_seed_is_the_sha256_of_the_three_32_byte_values_read_big_endian(): """RND-17: the algorithm, written out here independently of the code under test.""" import hashlib - from app.rounds.draw import draw_seed + from plm_engine.draw import draw_seed expected = int.from_bytes( hashlib.sha256(bytes.fromhex(_SEED) + bytes.fromhex(_BLOCK) + bytes.fromhex(_LIST_HASH)).digest(), "big" @@ -67,7 +67,7 @@ def test_draw_seed_is_the_sha256_of_the_three_32_byte_values_read_big_endian(): def test_draw_seed_depends_on_all_three_inputs(): - from app.rounds.draw import draw_seed + from plm_engine.draw import draw_seed base = draw_seed(_SEED, _BLOCK, _LIST_HASH) assert draw_seed("12" * 32, _BLOCK, _LIST_HASH) != base # without the secret nobody can predict it @@ -76,7 +76,7 @@ def test_draw_seed_depends_on_all_three_inputs(): def test_draw_winner_is_deterministic_and_within_range(): - from app.rounds.draw import draw_index, draw_seed + from plm_engine.draw import draw_index, draw_seed participants = ["addrA", "addrB", "addrC"] winner = draw_winner(participants, _SEED, _BLOCK, _LIST_HASH) @@ -99,7 +99,7 @@ def test_equal_odds_every_position_can_win(): over 0..n-1 (checked over many seeds, not exactly).""" from collections import Counter - from app.rounds.draw import draw_index, draw_seed + from plm_engine.draw import draw_index, draw_seed wins = Counter(draw_index(draw_seed(f"{i:064x}", _BLOCK, _LIST_HASH), 4) for i in range(2000)) assert set(wins) == {0, 1, 2, 3} @@ -109,13 +109,13 @@ def test_equal_odds_every_position_can_win(): def test_server_seed_commitment_is_sha256_of_the_32_bytes(): import hashlib - from app.rounds.draw import server_seed_commitment + from plm_engine.draw import server_seed_commitment assert server_seed_commitment(_SEED) == hashlib.sha256(bytes.fromhex(_SEED)).hexdigest() def test_new_server_seeds_are_32_random_bytes_in_hex(): - from app.rounds.draw import new_server_seed + from plm_engine.draw import new_server_seed seeds = {new_server_seed() for _ in range(20)} assert len(seeds) == 20 @@ -126,7 +126,7 @@ def test_participants_hash_encodes_one_txid_vout_address_line_per_participant(): """RND-14: sha256 of `txid:vout:address\n` lines in draw_position order, UTF-8.""" import hashlib - from app.rounds.draw import participants_hash + from plm_engine.draw import participants_hash rows = [("aa" * 32, 0, "plm1qfirst"), ("bb" * 32, 1, "plm1qsecond")] text = f"{'aa' * 32}:0:plm1qfirst\n{'bb' * 32}:1:plm1qsecond\n" @@ -139,7 +139,7 @@ def test_participants_hash_encodes_one_txid_vout_address_line_per_participant(): def test_pow_limit_is_the_mainnet_constant(): """B-74, ELC-11: PLM mainnet's `consensus.powLimit`, 00000000ffff…ffff.""" - from app.rounds import draw + from plm_engine import headers as draw assert draw.MAINNET_POW_LIMIT == int("00000000" + "ff" * 28, 16) assert draw.MAINNET_POW_LIMIT == (1 << 224) - 1 @@ -152,7 +152,7 @@ def test_a_header_below_the_pow_limit_is_rejected_even_if_it_meets_its_own_targe powLimit in force it is rejected however its hash falls.""" import struct - from app.rounds import draw + from plm_engine import headers as draw def build(nonce: int) -> str: return ( @@ -167,7 +167,7 @@ def test_a_header_below_the_pow_limit_is_rejected_even_if_it_meets_its_own_targe def test_a_real_mainnet_header_passes_with_the_mainnet_pow_limit(monkeypatch): - from app.rounds import draw + from plm_engine import headers as draw monkeypatch.setattr(draw, "POW_LIMIT", draw.MAINNET_POW_LIMIT) assert header_meets_its_own_target(_REAL_HEADER_HEX) is True diff --git a/tests/unit/test_draw_proof.py b/tests/unit/test_draw_proof.py index b076753..74cf21f 100644 --- a/tests/unit/test_draw_proof.py +++ b/tests/unit/test_draw_proof.py @@ -340,7 +340,7 @@ async def test_a_different_block_gives_a_different_draw_but_never_a_different_li for block in ("01" * 32, "02" * 32, "03" * 32, "04" * 32, "05" * 32, "06" * 32): async with session_factory() as session: round_ = await session.get(Round, round_id) - from app.rounds.draw import draw_index, draw_seed + from plm_engine.draw import draw_index, draw_seed seed = decrypt_round_seed(round_.server_seed_enc) winners.add(draw_index(draw_seed(seed, block, round_.participants_hash), 8)) diff --git a/tests/unit/test_electrum_client.py b/tests/unit/test_electrum_client.py index 44dc22a..73d2a86 100644 --- a/tests/unit/test_electrum_client.py +++ b/tests/unit/test_electrum_client.py @@ -1,7 +1,7 @@ import asyncio import json -from app.electrum.client import ElectrumClient, ElectrumError +from plm_engine.electrum.client import ElectrumClient, ElectrumError class FakeWriter: @@ -81,7 +81,7 @@ async def test_request_times_out_instead_of_hanging_forever(monkeypatch): """B-01: a server that owes us a reply and never sends one used to hang the caller permanently — which meant a POST /bets could hang while holding the per-user lock, and the confirmation poller could stop polling for good.""" - from app.electrum import client as client_module + from plm_engine.electrum import client as client_module monkeypatch.setattr(client_module, "_REQUEST_TIMEOUT_SECONDS", 0.05) client, reader, writer = await _client_with_fake_transport() @@ -124,7 +124,7 @@ async def test_pending_request_fails_when_the_connection_drops(): def test_parse_endpoints_puts_the_primary_first_and_dedupes(): - from app.electrum.client import ElectrumEndpoint, parse_endpoints + from plm_engine.electrum.client import ElectrumEndpoint, parse_endpoints endpoints = parse_endpoints( "primary.example", 50002, True, "second.example:50002, third.example:50001:notls, primary.example:50002" @@ -137,7 +137,7 @@ def test_parse_endpoints_puts_the_primary_first_and_dedupes(): def test_parse_endpoints_handles_an_empty_fallback_list(): - from app.electrum.client import ElectrumEndpoint, parse_endpoints + from plm_engine.electrum.client import ElectrumEndpoint, parse_endpoints assert parse_endpoints("only.example", 50002, True, "") == [ElectrumEndpoint("only.example", 50002, True)] assert parse_endpoints("only.example", 50002, True, " , ") == [ @@ -150,7 +150,7 @@ def test_parse_endpoints_rejects_a_malformed_entry(): the fallback is the thing that's needed.""" import pytest - from app.electrum.client import parse_endpoints + from plm_engine.electrum.client import parse_endpoints for bad in ["nohost:", "host:notaport", "host", "host:50002:weird"]: with pytest.raises(ValueError): @@ -169,7 +169,7 @@ async def _send_request(client, writer, reader): async def test_the_line_limit_is_16_mib_and_connect_applies_it(monkeypatch): """ELC-20 / B-75: the StreamReader is opened with a 16 MiB limit, not 64 KiB.""" - from app.electrum import client as client_module + from plm_engine.electrum import client as client_module assert client_module._MAX_LINE_BYTES == 16 * 1024 * 1024 seen = {} @@ -190,7 +190,7 @@ async def test_an_oversized_reply_fails_its_request_and_keeps_the_connection(mon """ELC-20 / B-75: the reply is discarded to its newline (even when it arrives in pieces), the request whose id is in its head fails at once, and the next reply on the same connection is still delivered.""" - from app.electrum import client as client_module + from plm_engine.electrum import client as client_module monkeypatch.setattr(client_module, "_MAX_LINE_BYTES", 1024) client, reader, writer = await _client_with_fake_transport() @@ -216,7 +216,7 @@ async def test_an_oversized_reply_fails_its_request_and_keeps_the_connection(mon async def test_an_oversized_reply_with_the_id_at_the_end_also_fails_its_request(monkeypatch): """ELC-20: the id is looked for in the last bytes of the line too.""" - from app.electrum import client as client_module + from plm_engine.electrum import client as client_module monkeypatch.setattr(client_module, "_MAX_LINE_BYTES", 1024) client, reader, writer = await _client_with_fake_transport() @@ -263,7 +263,7 @@ _PIN = "ab" * 32 def test_parse_endpoints_reads_pins_on_fallbacks_and_the_primary(): """ELC-01 / ELC-03 / B-84: `host:port:pin=` and `host:port::pin=`, plus ELECTRUM_CERT_PIN for the primary; the pin is normalised to lower case.""" - from app.electrum.client import ElectrumEndpoint, parse_endpoints + from plm_engine.electrum.client import ElectrumEndpoint, parse_endpoints endpoints = parse_endpoints( "primary.example", @@ -284,7 +284,7 @@ def test_parse_endpoints_rejects_malformed_pins(): """ELC-01 / B-84: a bad pin blocks the start, like any malformed entry.""" import pytest - from app.electrum.client import parse_endpoints + from plm_engine.electrum.client import parse_endpoints for bad in [ "h:1:pin=", @@ -328,7 +328,7 @@ class _PinWriter(FakeWriter): 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 + from plm_engine.network import GENESIS_HASH original = writer.write @@ -393,7 +393,7 @@ async def test_a_connection_with_another_certificate_fails_like_an_unreachable_s async def test_main_builds_clients_with_the_endpoint_pin(): """ELC-03 / B-84: app.main hands each endpoint's pin to its client.""" - from app.electrum.client import ElectrumEndpoint + from plm_engine.electrum.client import ElectrumEndpoint from app.main import _make_electrum_client assert _make_electrum_client(ElectrumEndpoint("h", 1, True, _PIN)).pin == _PIN @@ -404,8 +404,8 @@ async def test_only_a_server_error_object_is_an_explicit_refusal(): """B-76 / TX-04: a JSON-RPC `error` reply is an ElectrumRpcError carrying the server's wording (string or object); a timeout or a dropped connection is a plain ElectrumError — they say nothing about whether the server acted.""" - from app.electrum import client as client_module - from app.electrum.client import ElectrumRpcError + from plm_engine.electrum import client as client_module + from plm_engine.electrum.client import ElectrumRpcError client, reader, writer = await _client_with_fake_transport() task = asyncio.create_task(client.request("blockchain.transaction.broadcast", ["00"])) diff --git a/tests/unit/test_electrum_listener.py b/tests/unit/test_electrum_listener.py index dae79bd..6bddba3 100644 --- a/tests/unit/test_electrum_listener.py +++ b/tests/unit/test_electrum_listener.py @@ -19,9 +19,9 @@ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine from app.db.base import Base from app.db.models import AuditLog, RoundConfig, User, UtxoEvent -from app.electrum.client import ElectrumEndpoint +from plm_engine.electrum.client import ElectrumEndpoint from app.electrum.listener import ElectrumListener -from app.rounds.draw import HeaderValidationError, header_hex_to_block_hash, header_meets_its_own_target +from plm_engine.headers import HeaderValidationError, header_hex_to_block_hash, header_meets_its_own_target @pytest.fixture @@ -456,7 +456,7 @@ def _fake_address(i: int) -> str: actually parses it) — distinct per index, since User.address is unique.""" from embit import script - from app.wallet.plm_network import PLM_MAINNET + from plm_engine.network import PLM_MAINNET payload = (i + 1).to_bytes(20, "big") return script.Script(b"\x00\x14" + payload).address(network=PLM_MAINNET) @@ -973,7 +973,7 @@ async def test_a_header_that_does_not_join_the_tip_and_has_no_connection_to_foll async def test_a_header_easier_than_the_pow_limit_ends_the_session(session_factory, monkeypatch): """B-74, ELC-11: with the real powLimit back in force, a header mined at the trivial target is refused as the first header and as an advance alike.""" - from app.rounds import draw + from plm_engine import headers as draw chain = _mine_chain(91, 10) listener, client = await _listener_at(session_factory, chain, 100) @@ -1393,7 +1393,7 @@ async def test_nobody_answering_agrees_on_nothing(session_factory): async def test_a_header_without_valid_work_is_not_an_answer(session_factory, monkeypatch): """ELC-11 applies to the draw block too: a junk header is discarded, not counted.""" - from app.rounds import draw + from plm_engine import headers as draw real = _mine_header("00" * 32) monkeypatch.setattr(draw, "POW_LIMIT", draw.MAINNET_POW_LIMIT) # real == easy header: refused diff --git a/tests/unit/test_hd.py b/tests/unit/test_hd.py index 18a1143..f940568 100644 --- a/tests/unit/test_hd.py +++ b/tests/unit/test_hd.py @@ -1,6 +1,6 @@ from embit.bip32 import HDKey -from app.wallet.plm_network import PLM_MAINNET +from plm_engine.network import PLM_MAINNET def test_p2wpkh_address_uses_plm_hrp(): diff --git a/tests/unit/test_master_key_check.py b/tests/unit/test_master_key_check.py index a4a9d00..8f36493 100644 --- a/tests/unit/test_master_key_check.py +++ b/tests/unit/test_master_key_check.py @@ -12,7 +12,7 @@ from embit import script from app.config import ConfigError, settings from app.wallet import hd from app.wallet.keystore import encrypt_round_seed -from app.wallet.plm_network import PLM_MAINNET +from plm_engine.network import PLM_MAINNET from app.wallet.verify import load_sample, sample_problems, verify_master_key diff --git a/tests/unit/test_observability.py b/tests/unit/test_observability.py index 5b9ba6c..1f9ff57 100644 --- a/tests/unit/test_observability.py +++ b/tests/unit/test_observability.py @@ -82,7 +82,7 @@ def test_the_scheduler_beats_on_every_tick(monkeypatch): async def test_the_electrum_status_endpoint(client, listener): - from app.electrum.client import ElectrumEndpoint + from plm_engine.electrum.client import ElectrumEndpoint listener._endpoints = [ElectrumEndpoint("a.example", 50002, True), ElectrumEndpoint("b.example", 50002, True)] listener.client = object() @@ -99,7 +99,7 @@ async def test_the_electrum_status_endpoint(client, listener): async def test_the_listener_records_why_it_moved_to_another_server(): from app.electrum.listener import ServerStalledError, _rotation_reason - from app.rounds.draw import HeaderValidationError + from plm_engine.headers import HeaderValidationError assert _rotation_reason(ServerStalledError("x")) == "stalled_tip" assert _rotation_reason(HeaderValidationError("x")) == "invalid_header" diff --git a/tests/unit/test_payout_builder.py b/tests/unit/test_payout_builder.py index 2e442c5..c4eb0e0 100644 --- a/tests/unit/test_payout_builder.py +++ b/tests/unit/test_payout_builder.py @@ -3,8 +3,8 @@ from embit import script from embit.bip32 import HDKey from embit.transaction import Transaction -from app.wallet.plm_network import PLM_MAINNET -from app.wallet.psbt_builder import ( +from plm_engine.network import PLM_MAINNET +from plm_engine.psbt_builder import ( DUST_LIMIT_SATS, MAX_PARTICIPANTS_PER_ROUND, MAX_PAYOUT_TX_INPUTS, diff --git a/tests/unit/test_pool_verification.py b/tests/unit/test_pool_verification.py index 24ab9e2..bd5acf7 100644 --- a/tests/unit/test_pool_verification.py +++ b/tests/unit/test_pool_verification.py @@ -15,14 +15,14 @@ from sqlalchemy import select from app.config import MIN_QUORUM_RESPONSES from app.db.models import AuditLog, PendingTransaction, Round, RoundConfig, RoundParticipant, User -from app.electrum.client import ElectrumEndpoint +from plm_engine.electrum.client import ElectrumEndpoint from app.electrum.listener import ElectrumListener -from app.electrum.scripthash import address_to_scripthash +from plm_engine.electrum.scripthash import address_to_scripthash from app.rounds.scheduler import RoundScheduler from app.rounds.service import payout_config_problem, winner_share from app.wallet.hd import derive_pool_address -from app.wallet.plm_network import PLM_MAINNET -from app.wallet.psbt_builder import ( +from plm_engine.network import PLM_MAINNET +from plm_engine.psbt_builder import ( DUST_LIMIT_SATS, MAX_PARTICIPANTS_PER_ROUND, MAX_TX_INPUTS, diff --git a/tests/unit/test_psbt_builder.py b/tests/unit/test_psbt_builder.py index 184cbea..3012ae3 100644 --- a/tests/unit/test_psbt_builder.py +++ b/tests/unit/test_psbt_builder.py @@ -3,8 +3,8 @@ from embit import script from embit.bip32 import HDKey from embit.transaction import Transaction -from app.wallet.plm_network import PLM_MAINNET -from app.wallet.psbt_builder import ( +from plm_engine.network import PLM_MAINNET +from plm_engine.psbt_builder import ( MAX_PAYOUT_TX_INPUTS, MAX_TX_INPUTS, InsufficientFundsError, @@ -33,7 +33,7 @@ def test_select_utxos_picks_largest_first(): def test_select_utxos_ignores_dust(): # B-75 (DEP-01) - from app.wallet.psbt_builder import DUST_LIMIT_SATS + from plm_engine.psbt_builder import DUST_LIMIT_SATS utxos = [Utxo("a" * 64, 0, DUST_LIMIT_SATS - 1), Utxo("b" * 64, 0, DUST_LIMIT_SATS)] selected, total = select_utxos(utxos, target_sats=DUST_LIMIT_SATS) @@ -129,7 +129,7 @@ def test_build_signed_transaction_refuses_an_amount_that_would_leave_no_change() no change to shrink, and adding inputs is no answer either since this spends every UTXO the sender has. The bet is a fixed price, so it is refused rather than quietly reduced.""" - from app.wallet.psbt_builder import DUST_LIMIT_SATS + from plm_engine.psbt_builder import DUST_LIMIT_SATS signer = _key(3) from_script = script.p2wpkh(signer.to_public()) @@ -157,7 +157,7 @@ def test_build_signed_transaction_can_reduce_the_amount_to_keep_change(): # B-6 fee-bumpable. The caller records the reduced amount as what was actually sent.""" from embit.transaction import Transaction - from app.wallet.psbt_builder import DUST_LIMIT_SATS + from plm_engine.psbt_builder import DUST_LIMIT_SATS signer = _key(3) from_script = script.p2wpkh(signer.to_public()) @@ -210,7 +210,7 @@ def test_a_below_dust_change_output_is_never_created(): (the change is topped up to the dust limit by moving slightly less, instead of being folded into the fee and leaving an unbumpable single-output tx) but not this rule: an output below DUST_LIMIT_SATS is never produced.""" - from app.wallet.psbt_builder import DUST_LIMIT_SATS + from plm_engine.psbt_builder import DUST_LIMIT_SATS signer = _key(1) from_script = script.p2wpkh(signer.to_public()) @@ -241,7 +241,7 @@ def test_a_below_dust_change_output_is_never_created(): def test_change_at_the_dust_limit_is_still_paid_back(): - from app.wallet.psbt_builder import DUST_LIMIT_SATS + from plm_engine.psbt_builder import DUST_LIMIT_SATS signer = _key(1) from_script = script.p2wpkh(signer.to_public()) @@ -317,7 +317,7 @@ def test_a_withdrawal_uses_the_second_coin_instead_of_being_reduced(): def test_with_no_coin_to_spare_the_old_outcome_stands(): """BET-24: a lone coin equal to the bet is still refused / the withdrawal still reduced.""" - from app.wallet.psbt_builder import DUST_LIMIT_SATS + from plm_engine.psbt_builder import DUST_LIMIT_SATS utxos = [Utxo("aa" * 32, 0, 1_000_000_000)] with pytest.raises(InsufficientFundsError) as excinfo: diff --git a/tests/unit/test_rbf_dust.py b/tests/unit/test_rbf_dust.py index 629cd64..f217c44 100644 --- a/tests/unit/test_rbf_dust.py +++ b/tests/unit/test_rbf_dust.py @@ -19,8 +19,8 @@ from sqlalchemy import select from app.db.models import AuditLog, PendingTransaction, Round, RoundConfig, User from app.tx.broadcast import RbfBumper, RbfError, bump_fee -from app.wallet.plm_network import PLM_MAINNET -from app.wallet.psbt_builder import ( +from plm_engine.network import PLM_MAINNET +from plm_engine.psbt_builder import ( DUST_LIMIT_SATS, MAX_FEE_RATE_SAT_VB, RBF_SEQUENCE, diff --git a/tests/unit/test_reconcile_proof.py b/tests/unit/test_reconcile_proof.py index 4976ba7..96a0dd8 100644 --- a/tests/unit/test_reconcile_proof.py +++ b/tests/unit/test_reconcile_proof.py @@ -362,7 +362,7 @@ async def test_a_failed_row_is_watched_for_fourteen_days_and_no_longer(session_f async def test_a_refused_withdrawal_starts_its_watch_too(session_factory): """DAT-36: `_release_failed_withdrawal` stamps failed_at like `_abandon`.""" - from app.electrum.client import ElectrumRpcError + from plm_engine.electrum.client import ElectrumRpcError from app.withdrawals.service import WithdrawalError, request_withdrawal from tests.unit.fake_network import FakeNetwork from app.wallet.hd import derive_user_address @@ -416,7 +416,7 @@ class _Server: return self._txs[txid] async def broadcast(self, raw): - from app.electrum.client import ElectrumError, ElectrumRpcError + from plm_engine.electrum.client import ElectrumError, ElectrumRpcError self.broadcasted.append(raw) if self._broadcast is None: @@ -430,7 +430,7 @@ class _Server: def _make_listener(session_factory, active: _Server | None, others: dict[str, _Server]): - from app.electrum.client import ElectrumEndpoint + from plm_engine.electrum.client import ElectrumEndpoint from app.electrum.listener import ElectrumListener endpoints = [ElectrumEndpoint("active.example", 50002, True)] + [ElectrumEndpoint(h, 50002, True) for h in others] diff --git a/tests/unit/test_restore_gap.py b/tests/unit/test_restore_gap.py index 762f66a..7545c7b 100644 --- a/tests/unit/test_restore_gap.py +++ b/tests/unit/test_restore_gap.py @@ -8,7 +8,7 @@ from sqlalchemy import select from app.db.models import AuditLog, RoundConfig, User from app.electrum.listener import ElectrumListener -from app.electrum.scripthash import address_to_scripthash +from plm_engine.electrum.scripthash import address_to_scripthash from app.wallet.hd import derive_user_address from tests.unit.test_electrum_listener import _ENDPOINTS, session_factory # noqa: F401 (fixture) diff --git a/tests/unit/test_round_pool_address.py b/tests/unit/test_round_pool_address.py index c793e18..945139a 100644 --- a/tests/unit/test_round_pool_address.py +++ b/tests/unit/test_round_pool_address.py @@ -25,12 +25,12 @@ from app.bets.service import place_bet from app.config import settings from app.db.base import Base from app.db.models import AuditLog, PendingTransaction, Round, RoundConfig, User, UtxoEvent, Withdrawal -from app.electrum.scripthash import address_to_scripthash +from plm_engine.electrum.scripthash import address_to_scripthash from app.rounds.scheduler import RoundScheduler from app.rounds.service import open_new_round_if_needed from app.wallet import hd from app.wallet.hd import derive_pool_address, derive_pool_key, derive_round_pool_key, derive_user_address -from app.wallet.plm_network import PLM_MAINNET +from plm_engine.network import PLM_MAINNET from app.withdrawals.service import WithdrawalError, request_withdrawal from tests.unit.test_scheduler import ( # noqa: F401 (fixture + helpers shared with the payout tests) _FEE_ADDRESS, diff --git a/tests/unit/test_round_snapshot.py b/tests/unit/test_round_snapshot.py index d2f763b..ad9eab0 100644 --- a/tests/unit/test_round_snapshot.py +++ b/tests/unit/test_round_snapshot.py @@ -18,7 +18,7 @@ from app.bets.service import BetError, place_bet from app.db.models import AuditLog, PendingTransaction, Round, RoundConfig, RoundParticipant, User from app.rounds.scheduler import RoundScheduler from app.rounds.service import open_new_round_if_needed -from app.wallet.plm_network import PLM_MAINNET +from plm_engine.network import PLM_MAINNET from tests.unit.test_bets import FakeElectrumClient, _make_funded_user, session_factory # noqa: F401 (fixture) from tests.unit.test_migrations import _alembic, _index_sql from tests.unit.test_scheduler import FakePayoutClient, FakePayoutListener, _FEE_ADDRESS as _SEEDED_FEE_ADDRESS diff --git a/tests/unit/test_rounds_service.py b/tests/unit/test_rounds_service.py index 1f04982..96f8168 100644 --- a/tests/unit/test_rounds_service.py +++ b/tests/unit/test_rounds_service.py @@ -252,7 +252,7 @@ def test_payout_config_problem_at_both_extremes(): as the spec: net = bet - fee(50 inputs, 2 outputs) at the rate, checked for 1 participant and for MAX_PARTICIPANTS_PER_ROUND.""" from app.rounds.service import payout_config_problem, winner_share - from app.wallet.psbt_builder import ( + from plm_engine.psbt_builder import ( DUST_LIMIT_SATS, MAX_PARTICIPANTS_PER_ROUND, MAX_TX_INPUTS, diff --git a/tests/unit/test_scheduler.py b/tests/unit/test_scheduler.py index 49ad767..35cc794 100644 --- a/tests/unit/test_scheduler.py +++ b/tests/unit/test_scheduler.py @@ -11,7 +11,7 @@ from tests.unit.fake_network import FakeNetwork from app.db.models import AuditLog, PendingTransaction, Round, RoundConfig, RoundParticipant, User from app.rounds.scheduler import RoundScheduler, _reserved_payout_outpoints from app.wallet.hd import derive_pool_address -from app.wallet.psbt_builder import MAX_TX_INPUTS +from plm_engine.psbt_builder import MAX_TX_INPUTS class FakeListener: @@ -195,7 +195,7 @@ async def test_trigger_payout_always_carries_a_bump_reserve_to_the_reserve_addre and the payout spends them all, yet the transaction has three outputs — winner, fee address, reserve at m/84'/746'/0'/1/0 — and the round records the reserve before the broadcast. Nothing is created or lost to the satoshi.""" - from app.wallet.psbt_builder import estimate_vsize, payout_bump_reserve + from plm_engine.psbt_builder import estimate_vsize, payout_bump_reserve await _seed_paying_out_round(payout_session_factory) entries = [{"tx_hash": "34" * 32, "tx_pos": 0, "height": 10, "value": _POOL_AMOUNT_SATS}] # no excess @@ -208,7 +208,7 @@ async def test_trigger_payout_always_carries_a_bump_reserve_to_the_reserve_addre round_ = await session.get(Round, 1) pending = (await session.scalars(select(PendingTransaction))).one() tx = Transaction.parse(bytes.fromhex(pending.raw_tx_hex)) - from app.wallet.plm_network import PLM_MAINNET + from plm_engine.network import PLM_MAINNET addresses = [o.script_pubkey.address(network=PLM_MAINNET) for o in tx.vout] assert addresses == [_WINNER_ADDRESS, _FEE_ADDRESS, derive_pool_address()] # reserve = 1/0 @@ -649,7 +649,7 @@ async def test_a_round_without_participants_closes_and_reveals_its_secret(sessio round_ = await session.get(Round, round_id) assert round_.status == "closed" assert round_.server_seed is not None - from app.rounds.draw import server_seed_commitment + from plm_engine.draw import server_seed_commitment assert server_seed_commitment(round_.server_seed) == round_.server_seed_hash diff --git a/tests/unit/test_scripthash.py b/tests/unit/test_scripthash.py index d09d3bd..8423610 100644 --- a/tests/unit/test_scripthash.py +++ b/tests/unit/test_scripthash.py @@ -1,4 +1,4 @@ -from app.electrum.scripthash import address_to_scripthash +from plm_engine.electrum.scripthash import address_to_scripthash def test_matches_known_mainnet_vector(): diff --git a/tests/unit/test_sqlite_transactions.py b/tests/unit/test_sqlite_transactions.py index 8ca2a86..cec8ac7 100644 --- a/tests/unit/test_sqlite_transactions.py +++ b/tests/unit/test_sqlite_transactions.py @@ -833,7 +833,7 @@ async def test_bump_fee_persists_under_the_lock(session_factory, funded): from app.tx.broadcast import bump_fee from app.wallet.hd import derive_user_key - from app.wallet.psbt_builder import Utxo, build_signed_transaction + from plm_engine.psbt_builder import Utxo, build_signed_transaction signer = derive_user_key(0) built = build_signed_transaction( diff --git a/tests/unit/test_tx_versions.py b/tests/unit/test_tx_versions.py index ff8a8a9..6f34625 100644 --- a/tests/unit/test_tx_versions.py +++ b/tests/unit/test_tx_versions.py @@ -34,8 +34,8 @@ from app.tx.broadcast import RbfError, bump_fee from app.tx.confirmation import poll_once from app.tx.reconcile import reconcile_once from app.wallet.hd import derive_pool_address, derive_user_address, derive_user_key -from app.wallet.plm_network import PLM_MAINNET -from app.wallet.psbt_builder import Utxo, build_signed_transaction +from plm_engine.network import PLM_MAINNET +from plm_engine.psbt_builder import Utxo, build_signed_transaction from app.withdrawals.service import request_withdrawal from tests.unit.fake_network import FakeNetwork, ScriptedNetwork, rpc_error from tests.unit.test_bets import _make_funded_user @@ -358,7 +358,7 @@ async def test_an_explicitly_refused_replacement_leaves_the_row_alone(session_fa async def test_an_uncertain_replacement_is_adopted_and_an_accepted_one_is_fanned_out(session_factory): - from app.electrum.client import ElectrumError + from plm_engine.electrum.client import ElectrumError seeded = await _seed_pending_bet(session_factory) network = FakeNetwork(known=False) diff --git a/tests/unit/test_withdrawals.py b/tests/unit/test_withdrawals.py index 1282b74..0b9d69f 100644 --- a/tests/unit/test_withdrawals.py +++ b/tests/unit/test_withdrawals.py @@ -243,7 +243,7 @@ async def test_full_balance_withdrawal_keeps_a_bumpable_change_output(session_fa already spends every UTXO the user has. So a dust limit stays behind instead.""" from embit.transaction import Transaction - from app.wallet.psbt_builder import DUST_LIMIT_SATS + from plm_engine.psbt_builder import DUST_LIMIT_SATS balance = 2_000_000_000 user_id = await _make_funded_user(session_factory, 40, balance) @@ -272,7 +272,7 @@ async def test_a_bet_from_a_balance_equal_to_the_bet_is_refused(session_factory) a documented invariant of the PLAY phase; this is where it's enforced, with an error that says how much more is needed rather than a bare "insufficient".""" from app.bets.service import BetError - from app.wallet.psbt_builder import DUST_LIMIT_SATS + from plm_engine.psbt_builder import DUST_LIMIT_SATS user_id = await _make_funded_user(session_factory, 41, BET_AMOUNT_SATS) # exactly the bet client = FakeElectrumClient() @@ -292,7 +292,7 @@ async def test_a_bet_from_a_balance_equal_to_the_bet_is_refused(session_factory) async def test_a_bet_with_a_dust_limit_of_headroom_is_accepted(session_factory): - from app.wallet.psbt_builder import DUST_LIMIT_SATS + from plm_engine.psbt_builder import DUST_LIMIT_SATS user_id = await _make_funded_user(session_factory, 42, BET_AMOUNT_SATS + DUST_LIMIT_SATS) client = FakeElectrumClient()