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 <noreply@anthropic.com>
This commit is contained in:
davideandClaude Sonnet 5.5 committed 2026-11-16 15:31:47 +01:00
1 parent c9784efa07
commit 3ee60a23da
87 files changed
+290 -260

No files matched your search

+1 -1
View File
@@ -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
+3 -3
View File
@@ -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))
+1 -1
View File
@@ -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(
+1 -1
View File
@@ -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(
+1 -1
View File
@@ -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
+4 -4
View File
@@ -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)
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+3 -3
View File
@@ -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
+1 -1
View File
@@ -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},
+12 -12
View File
@@ -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
+1 -1
View File
@@ -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))
+14 -14
View File
@@ -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=<sha256>` and `host:port:<mode>:pin=<sha256>`,
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"]))
+5 -5
View File
@@ -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
+1 -1
View File
@@ -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():
+1 -1
View File
@@ -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
+2 -2
View File
@@ -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"
+2 -2
View File
@@ -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,
+4 -4
View File
@@ -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,
+8 -8
View File
@@ -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:
+2 -2
View File
@@ -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,
+3 -3
View File
@@ -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]
+1 -1
View File
@@ -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)
+2 -2
View File
@@ -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,
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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,
+4 -4
View File
@@ -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
+1 -1
View File
@@ -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():
+1 -1
View File
@@ -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(
+3 -3
View File
@@ -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)
+3 -3
View File
@@ -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()