B2: network profile for mainnet and regtest, explicit confirmation for mainnet (ADR-58, ELC-30)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
davideandClaude Sonnet 5.5 committed 2026-11-16 15:38:29 +01:00
1 parent 3ee60a23da
commit 9c832fd3d2
16 files changed
+261 -36

No files matched your search

+4
View File
@@ -65,6 +65,10 @@ START_PAUSED=false
# At least 50 characters; the web process refuses to start otherwise. Generate one with:
# python -c "import secrets; print(secrets.token_urlsafe(64))"
DJANGO_SECRET_KEY=
# The network profile (ADR-58): regtest (default, the alpha) or mainnet. Mainnet is forbidden until the checks of
# phase C are closed and also needs PLM_MAINNET_CONFIRMED=yes; the simulated ledger can never run on it.
PLM_NETWORK=regtest
PLM_MAINNET_CONFIRMED=
# Optional extras when serving a domain; SITE_ADDRESS itself is always allowed.
DJANGO_ALLOWED_HOSTS=
DJANGO_CSRF_TRUSTED_ORIGINS=
+1 -1
View File
@@ -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 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).
The migration from FastAPI to Django is in progress on branch `django-migration` (plan: [roadmap.md](roadmap.md), steps A1–A10, B1–B2 done). The suite has 1181 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.
+1 -1
View File
@@ -62,7 +62,7 @@ python -m pytest # all tests
python -m pytest tests/unit/test_hd.py # one file
```
1168 unit tests cover HD derivation, PSBT building, the Electrum client, bets,
1181 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
+6
View File
@@ -1,6 +1,7 @@
"""The address under which a participant appears in the public draw list (RND-14, DAT-65)."""
from django.conf import settings
from plm_engine.address import is_valid_address as _is_valid
from .simulation import simulated_address
@@ -9,3 +10,8 @@ def participant_address(user) -> str:
if settings.LEDGER_BACKEND == "simulated":
return simulated_address(user)
raise NotImplementedError("HD addresses arrive with phase B (roadmap B4)")
def is_valid_address(address: str) -> bool:
"""A destination on the configured network: its hrp is the profile's (ADR-58, ADR-05)."""
return _is_valid(address, settings.PLM_PROFILE)
+6
View File
@@ -8,6 +8,7 @@ import os
from pathlib import Path
from django.core.exceptions import ImproperlyConfigured
from plm_engine.network import get_profile as network_profile
BASE_DIR = Path(__file__).resolve().parent.parent
@@ -159,6 +160,11 @@ if LEDGER_BACKEND not in ("simulated", "chain"):
raise ImproperlyConfigured(f"LEDGER_BACKEND must be 'simulated' or 'chain', not {LEDGER_BACKEND!r}")
if LEDGER_BACKEND == "simulated" and PLM_NETWORK == "mainnet":
raise ImproperlyConfigured("the simulated ledger cannot run on mainnet (ADR-59)")
# ADR-58: mainnet is forbidden until the checks of phase C are closed; starting on it takes an explicit,
# separate confirmation, so a copied or mistyped PLM_NETWORK alone can never put real funds at stake.
if PLM_NETWORK == "mainnet" and os.environ.get("PLM_MAINNET_CONFIRMED", "") != "yes":
raise ImproperlyConfigured("PLM_NETWORK=mainnet needs PLM_MAINNET_CONFIRMED=yes (ADR-58): real funds are at stake")
PLM_PROFILE = network_profile(PLM_NETWORK)
# The simulated chain (ADR-59): a block every N seconds and a confirmation after M, so a whole round
# runs in a few minutes on localhost. Real chains ignore both.
@@ -34,4 +34,7 @@ resta vietato finché le verifiche della Fase C non sono chiuse: l'avvio con
- I test di integrazione automatici possono usare il regtest locale.
- Requisiti: `ELC` e `REG` da aggiornare con l'implementazione.
*Codice:* da implementare · *Test:* da implementare
*Codice:* `plm_engine/network.py:Profile`, `MAINNET`, `REGTEST`, `plm_engine/address.py:is_valid_address`, `plm_engine/hd.py`, `config/settings.py` (`PLM_NETWORK`, `PLM_MAINNET_CONFIRMED`, `PLM_PROFILE`) ·
*Test:* `tests/django/test_network_profile.py`
*Stato (B2):* il profilo esiste e governa indirizzi, derivazione, genesis dell'handshake e soglia di lavoro; `mainnet` si avvia solo con `PLM_MAINNET_CONFIRMED=yes` e mai con il ledger simulato. Il nodo regtest vero arriva con B3.
+7 -3
View File
@@ -69,9 +69,13 @@ Le difese sono cinque.
supererebbe ogni controllo sugli header di [ELC-11]; solo il genesis lo
distingue. Un genesis diverso o assente, o un errore alla richiesta, fa
fallire la connessione come un server irraggiungibile ([ELC-02]); vale anche
per le connessioni del quorum ([ELC-14]).
*Codice:* `plm_engine/electrum/client.py:ElectrumClient._check_genesis`, `plm_engine/network.py:GENESIS_HASH` ·
*Test:* `tests/unit/test_electrum_client.py`
per le connessioni del quorum ([ELC-14]). Il genesis atteso è quello del
**profilo di rete** ([ADR-58](adr/ADR-58-alfa-su-regtest-profilo-di-rete-configurabile.md)):
`000000000019d668…ce26f` per `mainnet`, `0f9188f1…2206` per `regtest`
(`ElectrumClient(genesis_hash=…)`); il profilo fissa anche hrp, prefissi,
`powLimit` e coin type, e l'hrp è quello con cui si validano gli indirizzi.
*Codice:* `plm_engine/electrum/client.py:ElectrumClient._check_genesis`, `plm_engine/network.py:MAINNET`, `REGTEST` (profili) ·
*Test:* `tests/unit/test_electrum_client.py`, `tests/django/test_network_profile.py::test_the_handshake_expects_the_genesis_of_its_profile`
## 2. Richieste con limite di tempo
+2 -2
View File
@@ -4,7 +4,7 @@
## Project status (old stack)
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.
All 10 stages of the original build order are code-complete and unit-tested — 1181 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 1168 tests
python -m pytest # all 1181 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
```
+10 -5
View File
@@ -12,16 +12,21 @@ tells the user (bech32 `plm1q...` only).
from embit import script
from embit.base import EmbitError
from plm_engine.network import PLM_MAINNET
_BECH32_PREFIX = PLM_MAINNET["bech32"] + "1"
from plm_engine.network import MAINNET, Profile
def is_valid_plm_address(address: str) -> bool:
if not address.startswith(_BECH32_PREFIX):
def is_valid_address(address: str, profile: Profile) -> bool:
"""A well-formed segwit address on this profile's chain: its hrp is the profile's (ADR-58), so a mainnet
`plm1…` is refused on regtest and the other way round."""
if not address.startswith(profile.hrp + "1"):
return False
try:
script.Script.from_address(address)
except EmbitError:
return False
return True
def is_valid_plm_address(address: str) -> bool:
"""Mainnet only: what the old stack has always checked."""
return is_valid_address(address, MAINNET)
+5 -2
View File
@@ -158,11 +158,14 @@ class ElectrumClient:
notification queues nobody will ever fill again.
"""
def __init__(self, host: str, port: int, use_ssl: bool = True, pin: str | None = None):
def __init__(
self, host: str, port: int, use_ssl: bool = True, pin: str | None = None, genesis_hash: str = GENESIS_HASH
):
self.host = host
self.port = port
self.use_ssl = use_ssl
self.pin = pin.lower() if pin else None
self.genesis_hash = genesis_hash # the profile's (ADR-58, ELC-30)
self._reader: asyncio.StreamReader | None = None
self._writer: asyncio.StreamWriter | None = None
self._id_counter = itertools.count(1)
@@ -206,7 +209,7 @@ class ElectrumClient:
Bitcoin's genesis and powLimit, so only `server.features` tells them apart (B-99, ELC-30)."""
features = await self.request("server.features")
genesis = features.get("genesis_hash") if isinstance(features, dict) else None
if genesis != GENESIS_HASH:
if genesis != self.genesis_hash:
raise ElectrumError(f"{self.host}:{self.port} is not on the PLM chain (genesis {genesis!r})")
def _check_pin(self) -> None:
+16 -11
View File
@@ -9,24 +9,29 @@ from embit import script
from embit.bip32 import HDKey
from embit.ec import PrivateKey
from .network import PLM_MAINNET
from .network import MAINNET, Profile
def account_key(master: HDKey, profile: Profile = MAINNET) -> HDKey:
"""The account key of the profile's chain: `m/84'/<coin type>'/0'` under the master key."""
return master.derive(profile.account_path)
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 address_of(key: HDKey, profile: Profile = MAINNET) -> str:
return script.p2wpkh(key.to_public()).address(network=profile.embit)
def user_address(account: HDKey, derivation_index: int) -> str:
return address_of(user_key(account, derivation_index))
def user_address(account: HDKey, derivation_index: int, profile: Profile = MAINNET) -> str:
return address_of(user_key(account, derivation_index), profile)
def user_wif(account: HDKey, derivation_index: int) -> str:
def user_wif(account: HDKey, derivation_index: int, profile: Profile = MAINNET) -> str:
key = user_key(account, derivation_index)
return PrivateKey(key.secret, compressed=True, network=PLM_MAINNET).wif(network=PLM_MAINNET)
return PrivateKey(key.secret, compressed=True, network=profile.embit).wif(network=profile.embit)
def pool_key(account: HDKey, round_id: int | None = None) -> HDKey:
@@ -38,15 +43,15 @@ def pool_key(account: HDKey, round_id: int | None = None) -> HDKey:
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 pool_address(account: HDKey, round_id: int | None = None, profile: Profile = MAINNET) -> str:
return address_of(pool_key(account, round_id), profile)
def round_pool_key(account: HDKey, round_id: int, stored_address: str) -> HDKey:
def round_pool_key(account: HDKey, round_id: int, stored_address: str, profile: Profile = MAINNET) -> 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:
if address_of(key, profile) == stored_address:
return key
raise ValueError(f"round {round_id}: no pool key controls the stored address {stored_address!r}")
+4 -2
View File
@@ -58,7 +58,7 @@ def _target_from_bits(bits: int) -> int:
return mantissa << (8 * (exponent - 3))
def header_meets_its_own_target(header_hex: str) -> bool:
def header_meets_its_own_target(header_hex: str, pow_limit: int | None = None) -> bool:
"""Whether this header's hash satisfies the difficulty target *it claims for
itself* (the `bits` field), and that target is no easier than the chain's powLimit
(B-74, ELC-11 — without that, a fabricated header just claims `bits = 0x207fffff`). Rejects a header that was never actually mined —
@@ -73,13 +73,15 @@ def header_meets_its_own_target(header_hex: str) -> bool:
the configured servers at a fixed height before using it as the seed (see
ElectrumListener.agreed_block_hash and rounds/scheduler.py:_wait_for_draw_block)
rather than relying on this check alone.
`pow_limit` is the profile's floor (ADR-58); without it the module default (mainnet) applies.
"""
header_bytes = bytes.fromhex(header_hex)
if len(header_bytes) != _HEADER_LENGTH_BYTES:
return False
bits = int.from_bytes(header_bytes[_BITS_OFFSET : _BITS_OFFSET + _BITS_LENGTH], "little")
target = _target_from_bits(bits)
if target <= 0 or target > POW_LIMIT: # B-74: not easier than the chain's powLimit
if target <= 0 or target > (POW_LIMIT if pow_limit is None else pow_limit): # B-74: not easier than the chain's powLimit
return False
digest = hashlib.sha256(hashlib.sha256(header_bytes).digest()).digest()
# The hash as the integer comparable against `target`: this is the same digest
+62 -4
View File
@@ -1,10 +1,14 @@
"""PLM mainnet params for embit, verified against PalladiumWallet/src/Core/Chain/ChainProfiles.cs.
"""Network profiles (ADR-58): everything that differs between PLM mainnet and the regtest of the alpha.
Threaded explicitly through every embit call via `network=PLM_MAINNET` rather than
registered globally, since this is a long-lived async server (embit has no
concept of "current network" beyond what you pass in).
A `Profile` fixes the bech32 hrp, the base58 and extended-key prefixes, the genesis hash the Electrum
handshake expects (ELC-30), the proof-of-work floor and the BIP44 coin type. The values come from
`palladiumcore/src/chainparams.cpp` (mainnet and `CRegTestParams`) and the PalladiumWallet chain profiles.
The profile is threaded explicitly through every call (`network=profile.embit`), never registered globally:
this is a long-lived server and embit has no notion of a current network beyond what it is passed.
"""
from dataclasses import dataclass
PLM_MAINNET = {
"name": "PLM Mainnet",
"wif": bytes([0x80]),
@@ -30,3 +34,57 @@ ACCOUNT_PATH = f"m/84h/{BIP44_COIN_TYPE}h/0h"
# PLM shares Bitcoin's genesis block (palladiumcore chainparams.cpp) and its powLimit, so a
# Bitcoin Electrum server would pass every header check; the handshake asks for this instead.
GENESIS_HASH = "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"
MAINNET_POW_LIMIT = int("00000000" + "ff" * 28, 16)
REGTEST_POW_LIMIT = int("7f" + "ff" * 31, 16)
# Bitcoin's testnet SLIP-132 variants, which Palladium's testnet and regtest share.
PLM_REGTEST = {
"name": "PLM Regtest",
"wif": bytes([0xFF]),
"p2pkh": bytes([127]),
"p2sh": bytes([115]),
"bech32": "rplm",
"xprv": bytes.fromhex("04358394"),
"xpub": bytes.fromhex("043587cf"),
"yprv": bytes.fromhex("044a4e28"),
"ypub": bytes.fromhex("044a5262"),
"zprv": bytes.fromhex("045f18bc"),
"zpub": bytes.fromhex("045f1cf6"),
"Yprv": bytes.fromhex("024285b5"),
"Ypub": bytes.fromhex("024289ef"),
"Zprv": bytes.fromhex("02575048"),
"Zpub": bytes.fromhex("02575483"),
"bip32": 1,
}
@dataclass(frozen=True)
class Profile:
name: str # the value of PLM_NETWORK
embit: dict # what embit takes as `network=`
genesis_hash: str
pow_limit: int
coin_type: int
@property
def hrp(self) -> str:
return self.embit["bech32"]
@property
def account_path(self) -> str:
return f"m/84h/{self.coin_type}h/0h"
MAINNET = Profile("mainnet", PLM_MAINNET, GENESIS_HASH, MAINNET_POW_LIMIT, BIP44_COIN_TYPE)
REGTEST = Profile(
"regtest", PLM_REGTEST, "0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206", REGTEST_POW_LIMIT, 1
)
PROFILES = {profile.name: profile for profile in (MAINNET, REGTEST)}
def get_profile(name: str) -> Profile:
try:
return PROFILES[name]
except KeyError:
raise ValueError(f"unknown network {name!r}: expected one of {sorted(PROFILES)}") from None
+1 -1
View File
@@ -40,7 +40,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.
- [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.
- [x] **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.
- [ ] **B5 · Listener e depositi reali.** Listener Electrum sull'ORM con rotazione, header validati, quorum e soglie di conferma al posto del deposito simulato. *Requisiti:* DEP, ELC. *Test:* unit con server finto + integrazione su regtest.
+3 -3
View File
@@ -404,10 +404,10 @@ def _run_settings(**env):
def test_the_simulated_ledger_cannot_run_on_mainnet():
"""ADR-59."""
result = _run_settings(PLM_NETWORK="mainnet")
"""ADR-59; a real ledger on mainnet also needs the explicit confirmation (ADR-58, B2)."""
result = _run_settings(PLM_NETWORK="mainnet", PLM_MAINNET_CONFIRMED="yes")
assert result.returncode != 0 and "simulated ledger" in result.stderr
assert _run_settings(PLM_NETWORK="mainnet", LEDGER_BACKEND="chain").returncode == 0
assert _run_settings(PLM_NETWORK="mainnet", LEDGER_BACKEND="chain", PLM_MAINNET_CONFIRMED="yes").returncode == 0
assert _run_settings().returncode == 0 # the default: regtest + simulated
+129
View File
@@ -0,0 +1,129 @@
"""B2 — the network profile: ADR-58, ELC-30, ADR-05. Everything that differs between mainnet and regtest
(hrp, prefixes, genesis, powLimit, coin type) comes from one `Profile`."""
import os
import subprocess
import sys
from pathlib import Path
import pytest
from embit import script
from embit.bip32 import HDKey
from plm_engine import hd
from plm_engine.address import is_valid_address, is_valid_plm_address
from plm_engine.electrum.client import ElectrumClient, ElectrumError
from plm_engine.headers import header_meets_its_own_target
from plm_engine.network import MAINNET, PROFILES, REGTEST, get_profile
ROOT = Path(__file__).resolve().parents[2]
MASTER = HDKey.from_seed(bytes(range(32)), version=MAINNET.embit["xprv"])
def settings_import(**env) -> subprocess.CompletedProcess:
clean = {"PATH": os.environ["PATH"], "PYTHONPATH": str(ROOT), "DJANGO_SECRET_KEY": "k" * 60, **env}
return subprocess.run([sys.executable, "-c", "import config.settings as s; print(s.PLM_PROFILE.name)"],
cwd=ROOT, env=clean, capture_output=True, text=True)
def test_each_profile_has_its_own_chain_parameters():
"""The values are palladiumcore's chainparams.cpp (mainnet, CRegTestParams)."""
assert (MAINNET.hrp, MAINNET.coin_type, MAINNET.genesis_hash) == (
"plm", 746, "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f")
assert (REGTEST.hrp, REGTEST.coin_type, REGTEST.genesis_hash) == (
"rplm", 1, "0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206")
assert MAINNET.pow_limit == int("00000000" + "ff" * 28, 16)
assert REGTEST.pow_limit == int("7f" + "ff" * 31, 16)
assert (REGTEST.embit["p2pkh"], REGTEST.embit["p2sh"], REGTEST.embit["wif"]) == (bytes([127]), bytes([115]), bytes([255]))
assert REGTEST.account_path == "m/84h/1h/0h" and MAINNET.account_path == "m/84h/746h/0h"
def test_profiles_are_looked_up_by_the_value_of_plm_network():
assert get_profile("mainnet") is MAINNET and get_profile("regtest") is REGTEST and set(PROFILES) == {"mainnet", "regtest"}
with pytest.raises(ValueError):
get_profile("testnet")
def test_the_same_account_derives_a_different_address_on_each_profile():
on_main = hd.user_address(hd.account_key(MASTER, MAINNET), 0, MAINNET)
on_regtest = hd.user_address(hd.account_key(MASTER, REGTEST), 0, REGTEST)
assert on_main.startswith("plm1") and on_regtest.startswith("rplm1") and on_main != on_regtest
assert hd.pool_address(hd.account_key(MASTER, REGTEST), 3, REGTEST).startswith("rplm1")
def test_an_address_is_valid_only_on_the_chain_of_its_hrp():
main = hd.user_address(hd.account_key(MASTER, MAINNET), 5, MAINNET)
regtest = hd.user_address(hd.account_key(MASTER, REGTEST), 5, REGTEST)
assert is_valid_address(main, MAINNET) and not is_valid_address(main, REGTEST)
assert is_valid_address(regtest, REGTEST) and not is_valid_address(regtest, MAINNET)
bitcoin = script.p2wpkh(hd.user_key(hd.account_key(MASTER, MAINNET), 5).to_public()).address()
assert bitcoin.startswith("bc1") and not is_valid_address(bitcoin, MAINNET) and not is_valid_address(bitcoin, REGTEST)
assert not is_valid_address(regtest[:-1] + ("q" if regtest[-1] != "q" else "p"), REGTEST) # bad checksum
def test_the_old_check_is_still_mainnet_only():
assert is_valid_plm_address(hd.user_address(hd.account_key(MASTER, MAINNET), 1, MAINNET))
assert not is_valid_plm_address(hd.user_address(hd.account_key(MASTER, REGTEST), 1, REGTEST))
def test_the_site_validates_addresses_with_the_configured_profile(settings):
from apps.lottery.addresses import is_valid_address as site_valid
regtest = hd.user_address(hd.account_key(MASTER, REGTEST), 2, REGTEST)
mainnet = hd.user_address(hd.account_key(MASTER, MAINNET), 2, MAINNET)
assert settings.PLM_PROFILE is REGTEST # the test settings run on regtest
assert site_valid(regtest) and not site_valid(mainnet)
def test_the_pow_floor_follows_the_profile():
"""A header mined at the regtest target passes the regtest floor and not the mainnet one."""
import struct
def build(nonce):
return (struct.pack("<I", 1) + bytes(32) + bytes(32) + struct.pack("<II", 0, 0x207FFFFF) + struct.pack("<I", nonce)).hex()
header = next(h for h in map(build, range(1000)) if header_meets_its_own_target(h, REGTEST.pow_limit))
assert header_meets_its_own_target(header, REGTEST.pow_limit) is True
assert header_meets_its_own_target(header, MAINNET.pow_limit) is False
@pytest.mark.parametrize("profile", [MAINNET, REGTEST], ids=lambda p: p.name)
@pytest.mark.asyncio
async def test_the_handshake_expects_the_genesis_of_its_profile(profile):
other = REGTEST if profile is MAINNET else MAINNET
def client_for(genesis):
client = ElectrumClient("h", 1, genesis_hash=profile.genesis_hash)
async def request(method, *params):
return {"genesis_hash": genesis}
client.request = request
return client
await client_for(profile.genesis_hash)._check_genesis()
with pytest.raises(ElectrumError):
await client_for(other.genesis_hash)._check_genesis()
def test_regtest_is_the_default_and_the_profile_is_exposed():
done = settings_import()
assert done.returncode == 0 and done.stdout.strip() == "regtest"
def test_mainnet_needs_an_explicit_confirmation():
refused = settings_import(PLM_NETWORK="mainnet", LEDGER_BACKEND="chain")
assert refused.returncode != 0 and "PLM_MAINNET_CONFIRMED" in refused.stderr
wrong = settings_import(PLM_NETWORK="mainnet", LEDGER_BACKEND="chain", PLM_MAINNET_CONFIRMED="true")
assert wrong.returncode != 0
confirmed = settings_import(PLM_NETWORK="mainnet", LEDGER_BACKEND="chain", PLM_MAINNET_CONFIRMED="yes")
assert confirmed.returncode == 0 and confirmed.stdout.strip() == "mainnet"
def test_the_simulated_ledger_still_cannot_run_on_mainnet():
refused = settings_import(PLM_NETWORK="mainnet", PLM_MAINNET_CONFIRMED="yes")
assert refused.returncode != 0 and "simulated ledger" in refused.stderr
def test_an_unknown_network_is_refused():
assert settings_import(PLM_NETWORK="testnet").returncode != 0