"""B6 — a real bet on the local regtest: deposit, reservation, signature by the worker, broadcast to the node, the change coming back, and the verdict of a refused transaction (BET-30..BET-33, DEP-22, TX-04).""" import asyncio import time from datetime import timedelta from uuid import uuid4 import pytest from django.contrib.auth import get_user_model from django.utils import timezone from embit.transaction import Transaction from plm_engine.electrum.client import ElectrumEndpoint from plm_engine.network import REGTEST from apps.lottery import bets, chain, deposits, keys from apps.lottery.balances import balance_of from apps.lottery.electrum_chain import ElectrumChain, Outcome from apps.lottery.ledger import ChainLedger from apps.lottery.models import ChainTransaction, Deposit, Movement, Participation, Round, Utxo pytestmark = pytest.mark.django_db PLM = 100_000_000 BET = 10 * PLM @pytest.fixture def network(electrum_endpoint): host, port = electrum_endpoint return ElectrumChain([ElectrumEndpoint(host, port, False)], REGTEST, allow_no_quorum=True) @pytest.fixture def funded_player(settings, tmp_path, regtest_node, electrum_endpoint, network): """A player whose 30 PLM deposit has been through 6 confirmations and the scan.""" settings.LEDGER_BACKEND = "chain" settings.PLM_ACCOUNT_XPUB = keys.generate_keys(tmp_path / "keys", settings.PLM_PROFILE) settings.PLM_MASTER_KEY_FILE = str(tmp_path / "keys" / "master.key") settings.PLM_KEY_ENCRYPTION_KEY_FILE = str(tmp_path / "keys" / "master.encryption.key") settings.PROCESS_ROLE = "worker" user = get_user_model().objects.create_user("giocatore", password="x" * 12) address = chain.assign_deposit_address(user).address regtest_node.fund(address, 30) regtest_node.mine(5) for _ in range(80): deposits.scan_deposits(network) if balance_of(user).spendable_sats: break time.sleep(0.25) assert balance_of(user).spendable_sats == 30 * PLM return user, address def open_round(): round_ = Round.objects.create(opened_at=timezone.now() - timedelta(seconds=30), bet_amount_sats=BET) round_.pool_address = chain.derive_pool_address(round_.pk) round_.save(update_fields=["pool_address"]) return round_ def test_a_real_bet_goes_from_the_web_to_the_node(regtest_node, network, funded_player): user, address = funded_player round_ = open_round() ChainLedger().place_bet(user, round_.pk, request_id=uuid4()) # the web: admits and reserves, signs nothing tx = ChainTransaction.objects.get() assert tx.status == "building" and tx.current_txid is None done = bets.process_bets(network) # the worker: signs, saves, sends assert (done["signed"], done["accepted"]) == (1, 1) tx.refresh_from_db() assert tx.status == "pending" entry = regtest_node.rpc("getmempoolentry", tx.current_txid) # the node really has it assert entry["vsize"] > 0 raw = regtest_node.rpc("getrawtransaction", tx.current_txid) pool_out, change_out = Transaction.parse(bytes.fromhex(raw)).vout participation = Participation.objects.get() assert pool_out.value == participation.bet_amount_sats and pool_out.value < BET script_pubkey = regtest_node.rpc("getrawtransaction", tx.current_txid, True)["vout"][0]["scriptPubKey"] assert (script_pubkey.get("address") or script_pubkey["addresses"][0]) == round_.pool_address # the node's own reading assert change_out.value == 20 * PLM # sending the same transaction again is "already known": still accepted, never a refusal verdict = asyncio.run(network.broadcast(tx.raw_hex, tx.current_txid)) assert verdict.outcome is Outcome.ACCEPTED regtest_node.mine(1) for _ in range(80): # the change comes back to the player's address: spendable money, not a deposit deposits.scan_deposits(network) if Utxo.objects.filter(txid=tx.current_txid).exists(): break time.sleep(0.25) change = Utxo.objects.get(txid=tx.current_txid) assert change.amount_sats == 20 * PLM and not Deposit.objects.filter(utxo=change).exists() assert Movement.objects.filter(kind="deposit").count() == 1 # still the one real deposit assert balance_of(user).spendable_sats == 20 * PLM def test_a_transaction_the_chain_cannot_accept_is_refused_with_proof(network): # one input that does not exist, one output: the node refuses and no server knows the txid raw = "01000000" + "01" + "11" * 32 + "00000000" + "00" + "ffffffff" + "01" + "00ca9a3b00000000" + "00" + "00000000" txid = Transaction.parse(bytes.fromhex(raw)).txid().hex() verdict = asyncio.run(network.broadcast(raw, txid)) assert verdict.outcome is Outcome.REFUSED and verdict.reason