B6: atomic UTXO reservation, bet signed by the worker and saved before broadcast, broadcast verdicts (BET-30..33)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
davideandClaude Sonnet 5.5 committed 2026-11-16 16:18:34 +01:00
1 parent 2acd4ccd1c
commit feff993584
25 files changed
+995 -53

No files matched your search

+86 -1
View File
@@ -12,7 +12,10 @@ import logging
from collections.abc import Awaitable, Callable
from embit.transaction import Transaction
from plm_engine.electrum.client import ElectrumClient, ElectrumEndpoint
from enum import Enum
from typing import NamedTuple
from plm_engine.electrum.client import ElectrumClient, ElectrumEndpoint, ElectrumRpcError
from plm_engine.electrum.merkle import proof_matches_header
from plm_engine.electrum.scripthash import address_to_scripthash
from plm_engine.headers import header_meets_its_own_target
@@ -27,6 +30,23 @@ CONNECT_TIMEOUT = 10.0
ANSWER_TIMEOUT = 10.0
class Outcome(Enum):
ACCEPTED = "accepted"
REFUSED = "refused"
UNCERTAIN = "uncertain"
class Verdict(NamedTuple):
outcome: Outcome
reason: str
# Wordings by which a node says it already has the transaction. Recognising one skips the verification; not
# recognising one never releases anything, it only costs one more round of questions (BET-32, TX-04).
_ALREADY_KNOWN = ("already known", "already in mempool", "already in the mempool", "txn-already-known",
"txn-already-in-mempool", "already in block chain", "already in blockchain")
def _seen(raw: dict) -> Seen | None:
try:
return Seen(txid=str(raw["tx_hash"]), vout=int(raw["tx_pos"]), value=int(raw["value"]), height=int(raw["height"]))
@@ -177,6 +197,71 @@ class ElectrumChain:
return self.majority(await self._ask_others(lacks_it))
# -- broadcast (BET-32) -----------------------------------------------------------------------------------
async def transaction_known(self, active: ElectrumClient, txid: str) -> bool | None:
"""True if any server returns the transaction; False only if the active server and the quorum of the
others all say they do not know it; None if there were not enough answers to say."""
not_found = ("no such mempool", "no such blockchain", "not found", "unknown transaction")
async def ask(client: ElectrumClient):
try:
await asyncio.wait_for(client.get_transaction(txid), ANSWER_TIMEOUT)
return True
except ElectrumRpcError as error: # the server answered: it does not know it
return False if any(m in error.message.lower() for m in not_found) else None
except Exception:
return None
mine = await ask(active)
others = await self._ask_others(ask)
if mine is True or any(a is True for a in others):
return True
if mine is False and self.majority([a is False if a is not None else None for a in others]):
return False
return None
async def broadcast(self, raw_tx_hex: str, txid: str) -> Verdict:
"""Send `raw_tx_hex` through the active server and say what happened (BET-32). Only a proven refusal frees coins."""
active = await self._connect_active()
if active is None:
return Verdict(Outcome.UNCERTAIN, "no Electrum server is reachable")
try:
try:
await asyncio.wait_for(active.broadcast(raw_tx_hex), ANSWER_TIMEOUT)
except ElectrumRpcError as error:
reason = error.message
known = True if any(m in reason.lower() for m in _ALREADY_KNOWN) else await self.transaction_known(active, txid)
if known is True:
await self._fan_out(raw_tx_hex)
return Verdict(Outcome.ACCEPTED, reason)
if known is False:
return Verdict(Outcome.REFUSED, reason)
logger.warning("broadcast of %s was refused (%s) but the refusal could not be verified", txid, reason)
return Verdict(Outcome.UNCERTAIN, reason)
except Exception as error: # timeout, dropped connection: the server may have relayed it
logger.warning("broadcast of %s ended without an answer (%r): uncertain", txid, error)
return Verdict(Outcome.UNCERTAIN, str(error) or type(error).__name__)
await self._fan_out(raw_tx_hex)
return Verdict(Outcome.ACCEPTED, "")
finally:
await active.close()
async def _fan_out(self, raw_tx_hex: str) -> None:
"""TX-21: after the active server accepted, tell the others too (best effort)."""
async def send(client: ElectrumClient):
try:
await client.broadcast(raw_tx_hex)
except ElectrumRpcError:
pass # "already known" and the like: that is what we wanted
return True
try:
await self._ask_others(send)
except Exception:
logger.exception("fan-out of an accepted transaction failed")
# -- the scan ----------------------------------------------------------------------------------------
async def observe(self, policy: Policy) -> ScanResult: