177 lines
7.2 KiB
Python
177 lines
7.2 KiB
Python
"""B7 — confirmations: TX-30, TX-31, TX-26, TX-08."""
|
|
|
|
import struct
|
|
from datetime import timedelta
|
|
|
|
import pytest
|
|
from django.utils import timezone
|
|
from embit.transaction import Transaction
|
|
from plm_engine.electrum.client import ElectrumEndpoint
|
|
from plm_engine.headers import header_meets_its_own_target
|
|
from plm_engine.network import REGTEST
|
|
|
|
from apps.lottery import bets, chain, confirmation
|
|
from apps.lottery.electrum_chain import ElectrumChain
|
|
from apps.lottery.models import AuditEntry, ChainTransaction, Movement, Participation, Utxo
|
|
from tests.django.test_chain_bets import ScriptedChain, bet, make_round, placed_and_signed, player, world # noqa: F401
|
|
|
|
pytestmark = pytest.mark.django_db
|
|
|
|
|
|
def pending(world):
|
|
user, round_, tx = placed_and_signed(world)
|
|
bets.broadcast_pending(ScriptedChain())
|
|
tx.refresh_from_db()
|
|
return user, round_, tx
|
|
|
|
|
|
# --- the write phase ------------------------------------------------------------------------------------------
|
|
|
|
|
|
def test_a_bet_is_confirmed_and_enters_the_draw(world):
|
|
user, round_, tx = pending(world)
|
|
assert confirmation.apply_confirmations({tx.pk: (tx.current_txid, 120)}) == 1
|
|
tx.refresh_from_db()
|
|
bet_row = Participation.objects.get()
|
|
assert tx.status == "confirmed" and tx.confirmed_at
|
|
assert (bet_row.status, bet_row.bet_txid) == ("confirmed", tx.current_txid) and bet_row.confirmed_at
|
|
assert Movement.objects.get(kind="bet").status == "confirmed"
|
|
assert set(Utxo.objects.filter(reserved_by=tx).values_list("spent_txid", flat=True)) == {tx.current_txid}
|
|
entry = AuditEntry.objects.get(action="tx_confirmed")
|
|
assert entry.payload["height"] == 120 and entry.payload["adopted"] is False
|
|
|
|
|
|
def test_an_earlier_version_that_confirms_is_adopted(world):
|
|
"""TX-31: the original won while a replacement was in flight."""
|
|
user, round_, tx = pending(world)
|
|
original = tx.current_txid
|
|
replacement = "ee" * 32
|
|
chain.register_version(tx, replacement, "00aa") # the row follows the replacement...
|
|
Participation.objects.update(bet_txid=replacement)
|
|
assert confirmation.apply_confirmations({tx.pk: (original, 130)}) == 1 # ...but the original is what the chain mined
|
|
tx.refresh_from_db()
|
|
assert tx.current_txid == original and tx.raw_hex and tx.raw_hex != "00aa"
|
|
assert Participation.objects.get().bet_txid == original
|
|
assert Utxo.objects.get(reserved_by=tx).spent_txid == original
|
|
assert AuditEntry.objects.get(action="tx_confirmed").payload["adopted"] is True
|
|
|
|
|
|
def test_a_row_that_is_no_longer_pending_is_left_alone(world):
|
|
user, round_, tx = pending(world)
|
|
ChainTransaction.objects.filter(pk=tx.pk).update(status="failed", failed_at=timezone.now(), failure_reason="x")
|
|
assert confirmation.apply_confirmations({tx.pk: (tx.current_txid, 120)}) == 0
|
|
assert Participation.objects.get().status == "pending"
|
|
|
|
|
|
def test_confirming_twice_changes_nothing_the_second_time(world):
|
|
user, round_, tx = pending(world)
|
|
confirmation.apply_confirmations({tx.pk: (tx.current_txid, 120)})
|
|
assert confirmation.apply_confirmations({tx.pk: (tx.current_txid, 120)}) == 0
|
|
assert AuditEntry.objects.filter(action="tx_confirmed").count() == 1
|
|
|
|
|
|
def test_the_plan_lists_pending_rows_with_every_version(world):
|
|
user, round_, tx = pending(world)
|
|
chain.register_version(tx, "ee" * 32, "00aa")
|
|
(row,) = confirmation.plan()
|
|
assert row[0] == tx.pk and row[1] == chain.assign_deposit_address(user).address and len(row[2]) == 2
|
|
|
|
|
|
def test_a_building_row_is_not_polled(world):
|
|
user, round_, tx = placed_and_signed(world) # signed, never accepted: still building
|
|
assert confirmation.plan() == []
|
|
|
|
|
|
# --- the network phase --------------------------------------------------------------------------------------------
|
|
|
|
|
|
def mined(root: bytes) -> str:
|
|
for nonce in range(10_000):
|
|
header = (struct.pack("<I", 1) + bytes(32) + root + struct.pack("<II", 0, 0x207FFFFF) + struct.pack("<I", nonce)).hex()
|
|
if header_meets_its_own_target(header, REGTEST.pow_limit):
|
|
return header
|
|
raise AssertionError
|
|
|
|
|
|
class Node:
|
|
def __init__(self, name, history, header, proof_ok=True, unreadable=()):
|
|
self.name, self.history, self.header, self.proof_ok, self.unreadable = name, history, header, proof_ok, set(unreadable)
|
|
|
|
|
|
class Client:
|
|
def __init__(self, node):
|
|
self.n = node
|
|
|
|
async def connect(self): pass
|
|
async def close(self): pass
|
|
|
|
async def get_history(self, scripthash):
|
|
if scripthash in self.n.unreadable:
|
|
raise OSError("timeout")
|
|
return self.n.history.get(scripthash, [])
|
|
|
|
async def get_block_header(self, height):
|
|
return self.n.header
|
|
|
|
async def get_merkle(self, txid, height):
|
|
return {"block_height": height, "merkle": [], "pos": 0} if self.n.proof_ok else {"block_height": height, "merkle": ["00" * 32], "pos": 0}
|
|
|
|
|
|
def network(nodes):
|
|
by = {ElectrumEndpoint(n.name, 1, False): n for n in nodes}
|
|
return ElectrumChain(list(by), REGTEST, False, lambda e: Client(by[e]))
|
|
|
|
|
|
TXID = "ab" * 32
|
|
HEADER = mined(bytes.fromhex(TXID)[::-1])
|
|
ADDRESS = "rplm1qz3r3xc0dxx470c9dhv78dmvlr0cd34vw3vvmsx"
|
|
|
|
|
|
def scripthash():
|
|
from plm_engine.electrum.scripthash import address_to_scripthash
|
|
|
|
return address_to_scripthash(ADDRESS)
|
|
|
|
|
|
def nodes(history, **kw):
|
|
return [Node(n, {scripthash(): history}, HEADER, **kw) for n in "abc"]
|
|
|
|
|
|
async def test_a_version_in_a_block_with_a_proof_is_confirmed():
|
|
wanted = [(7, ADDRESS, frozenset({TXID}))]
|
|
assert await network(nodes([{"tx_hash": TXID, "height": 150}])).observe_confirmations(wanted) == {7: (TXID, 150)}
|
|
|
|
|
|
async def test_a_non_current_version_is_found_too():
|
|
wanted = [(7, ADDRESS, frozenset({"cd" * 32, TXID}))] # the row follows the other one
|
|
assert (await network(nodes([{"tx_hash": TXID, "height": 150}])).observe_confirmations(wanted))[7][0] == TXID
|
|
|
|
|
|
@pytest.mark.parametrize("entry", [{"tx_hash": TXID, "height": 0}, {"tx_hash": TXID, "height": -1}, {"tx_hash": "11" * 32, "height": 150}])
|
|
async def test_the_mempool_and_other_transactions_are_not_confirmations(entry):
|
|
assert await network(nodes([entry])).observe_confirmations([(7, ADDRESS, frozenset({TXID}))]) == {}
|
|
|
|
|
|
async def test_without_a_proof_the_others_agree_on_nothing_is_confirmed():
|
|
assert await network(nodes([{"tx_hash": TXID, "height": 150}], proof_ok=False)).observe_confirmations(
|
|
[(7, ADDRESS, frozenset({TXID}))]) == {}
|
|
|
|
|
|
async def test_an_address_that_cannot_be_read_does_not_block_the_others():
|
|
other = "rplm1q3k3umjv83hhd7rvfafwfavs92na265gmude8xu"
|
|
from plm_engine.electrum.scripthash import address_to_scripthash
|
|
|
|
bad = address_to_scripthash(other)
|
|
servers = [Node(n, {scripthash(): [{"tx_hash": TXID, "height": 150}]}, HEADER, unreadable=[bad]) for n in "abc"]
|
|
wanted = [(1, other, frozenset({"cd" * 32})), (2, ADDRESS, frozenset({TXID}))]
|
|
assert await network(servers).observe_confirmations(wanted) == {2: (TXID, 150)}
|
|
|
|
|
|
async def test_with_no_server_nothing_is_confirmed():
|
|
class Down(Client):
|
|
async def connect(self):
|
|
raise OSError("down")
|
|
|
|
chain_ = ElectrumChain([ElectrumEndpoint("a", 1, False)], REGTEST, False, lambda e: Down(None))
|
|
assert await chain_.observe_confirmations([(1, ADDRESS, frozenset({TXID}))]) == {}
|