Files
plm-lottery/tests/django/test_chain_reconcile.py
T

167 lines
6.9 KiB
Python

"""B7 — reconciliation: TX-33, TX-15..TX-17, TX-23, TX-26."""
from datetime import timedelta
import pytest
from django.utils import timezone
from apps.lottery import bets, reconcile, reservation
from apps.lottery.balances import balance_of
from apps.lottery.electrum_chain import Outcome, Verdict
from apps.lottery.models import AuditEntry, ChainTransaction, LotteryConfig, Movement, Participation, Utxo
from tests.django.test_chain_bets import BET, ScriptedChain, bet, make_round, placed_and_signed, player, world # noqa: F401
pytestmark = pytest.mark.django_db
class Net:
"""The network as the reconciler asks about it."""
def __init__(self, known=(), complete=True, verdict=None, confirmed=None):
self.known, self.complete, self.verdict, self.confirmed = set(known), complete, verdict, confirmed or {}
self.sent = []
async def versions_known(self, address, txids):
return {t for t in txids if t in self.known}, self.complete
async def broadcast(self, raw, txid):
self.sent.append(txid)
return self.verdict or Verdict(Outcome.UNCERTAIN, "no answer")
async def observe_confirmations(self, wanted):
return {row: self.confirmed[row] for row, _a, _t in wanted if row in self.confirmed}
def old(tx, *, building_for=300, pending_for=None):
stamp = timezone.now() - timedelta(seconds=building_for)
ChainTransaction.objects.filter(pk=tx.pk).update(created_at=stamp)
if pending_for:
ChainTransaction.objects.filter(pk=tx.pk).update(broadcast_at=timezone.now() - timedelta(seconds=pending_for))
def building(world):
user, round_, tx = placed_and_signed(world)
old(tx)
return user, round_, tx
MISSING = "bad-txns-inputs-missingorspent"
# --- presence -----------------------------------------------------------------------------------------------------
def test_a_row_the_network_knows_is_promoted_to_pending(world):
user, round_, tx = building(world)
assert reconcile.reconcile_once(Net(known={tx.current_txid}))["recovered"] == 1
tx.refresh_from_db()
assert tx.status == "pending" and tx.broadcast_at
assert AuditEntry.objects.filter(action="pending_tx_recovered").count() == 1
def test_a_known_non_current_version_also_means_alive(world):
"""TX-15: any version known to any server is enough, not only the current one."""
from apps.lottery.chain import register_version
user, round_, tx = building(world)
earlier = tx.current_txid
register_version(tx, "ee" * 32, "00aa") # the row now follows a replacement the network has not seen
assert reconcile.reconcile_once(Net(known={earlier}))["recovered"] == 1
assert ChainTransaction.objects.get().status == "pending"
def test_a_fresh_building_row_is_not_examined_yet(world):
user, round_, tx = placed_and_signed(world) # created just now: inside the 120 s grace
net = Net(known=set())
assert reconcile.reconcile_once(net) == {"recovered": 0, "abandoned": 0, "resurrected": 0} and net.sent == []
def test_a_pending_row_is_examined_only_after_six_hours(world):
user, round_, tx = building(world)
reconcile._promote(tx.pk, timezone.now(), tx.current_txid)
old(tx, pending_for=5 * 3600)
net = Net()
reconcile.reconcile_once(net)
assert net.sent == []
old(tx, pending_for=7 * 3600)
reconcile.reconcile_once(net)
assert net.sent # absent and complete: the newest version is sent again
# --- abandonment only with proof ---------------------------------------------------------------------------------
def test_missing_inputs_with_no_server_knowing_it_abandons_and_frees_the_coins(world):
user, round_, tx = building(world)
net = Net(verdict=Verdict(Outcome.REFUSED, MISSING))
assert reconcile.reconcile_once(net)["abandoned"] == 1
tx.refresh_from_db()
assert tx.status == "failed" and MISSING in tx.failure_reason and tx.failed_at
assert Participation.objects.get().status == "rejected" and Movement.objects.get(kind="bet").status == "failed"
assert reservation.spendable(user).count() == 1 and balance_of(user).spendable_sats == 3 * BET
entry = AuditEntry.objects.get(action="tx_abandoned")
assert entry.payload["coins_freed"] == 1
@pytest.mark.parametrize("verdict", [
Verdict(Outcome.REFUSED, "insufficient fee, rejecting replacement"), # a refusal for the fee is not a proof
Verdict(Outcome.UNCERTAIN, "timeout"),
])
def test_anything_but_missing_inputs_abandons_nothing(world, verdict):
user, round_, tx = building(world)
reconcile.reconcile_once(Net(verdict=verdict))
tx.refresh_from_db()
assert tx.status in ("building", "pending") and tx.reserved_utxos.count() == 1 and not reservation.spendable(user).exists()
def test_an_accepted_resend_means_it_is_alive(world):
user, round_, tx = building(world)
assert reconcile.reconcile_once(Net(verdict=Verdict(Outcome.ACCEPTED, "")))["recovered"] == 1
def test_a_network_that_did_not_answer_enough_proves_nothing(world):
user, round_, tx = building(world)
net = Net(complete=False, verdict=Verdict(Outcome.REFUSED, MISSING))
assert reconcile.reconcile_once(net) == {"recovered": 0, "abandoned": 0, "resurrected": 0} and net.sent == []
assert ChainTransaction.objects.get().status == "building"
@pytest.mark.parametrize("reason,expected", [
("bad-txns-inputs-missingorspent", True), ("missing-inputs", True), ("the transaction was rejected\n\nmissing inputs", True),
("insufficient fee", False), ("mempool min fee not met", False), ("", False),
])
def test_only_missing_or_spent_inputs_count_as_proof(reason, expected):
assert reconcile.is_missing_inputs(reason) is expected
def test_a_row_that_changed_meanwhile_is_not_overwritten(world):
user, round_, tx = building(world)
ChainTransaction.objects.filter(pk=tx.pk).update(status="pending") # promoted by someone else
assert reconcile._promote(tx.pk, timezone.now(), tx.current_txid) is False
# --- failed rows stay watched (TX-23) -----------------------------------------------------------------------------
def failed(world):
user, round_, tx = building(world)
reconcile.reconcile_once(Net(verdict=Verdict(Outcome.REFUSED, MISSING)))
tx.refresh_from_db()
return tx
def test_a_failed_row_that_confirms_is_reported_once_and_pauses_new_bets(world):
tx = failed(world)
net = Net(confirmed={tx.pk: (tx.current_txid, 200)})
assert reconcile.reconcile_once(net)["resurrected"] == 1
assert reconcile.reconcile_once(net)["resurrected"] == 0 # once
assert AuditEntry.objects.filter(action="tx_resurrected").count() == 1
assert LotteryConfig.get().new_bets_suspended
assert ChainTransaction.objects.get().status == "failed" # the reconciler does not fix the linked rows itself
def test_a_failed_row_is_watched_for_fourteen_days_only(world):
tx = failed(world)
ChainTransaction.objects.filter(pk=tx.pk).update(failed_at=timezone.now() - timedelta(days=15))
assert reconcile.reconcile_once(Net(confirmed={tx.pk: (tx.current_txid, 200)}))["resurrected"] == 0