refactor: backports

This commit is contained in:
tecnovert
2026-04-04 21:42:39 +02:00
parent 3c76454e68
commit 360d356cbf
11 changed files with 103 additions and 47 deletions
+40 -12
View File
@@ -3964,6 +3964,13 @@ class BasicSwap(BaseApp, BSXNetwork, UIApp):
except Exception as e:
raise ValueError(f"Invalid message networks: {e}")
def isValidSwapDest(self, ci, dest: bytes):
ensure(isinstance(dest, bytes), "Swap destination must be bytes")
if ci.coin_type() in (Coins.PART_BLIND,):
return ci.isValidPubkey(dest)
# TODO: allow p2wsh
return ci.isValidAddressHash(dest)
def ensureWalletCanSend(
self, ci, swap_type, ensure_balance: int, estimated_fee: int, for_offer=True
) -> None:
@@ -5365,12 +5372,13 @@ class BasicSwap(BaseApp, BSXNetwork, UIApp):
self.loadBidTxns(bid, cursor)
return bid, xmr_swap
def getXmrBid(self, bid_id: bytes):
def getXmrBid(self, bid_id: bytes, cursor=None):
try:
cursor = self.openDB()
return self.getXmrBidFromSession(cursor, bid_id)
use_cursor = self.openDB(cursor)
return self.getXmrBidFromSession(use_cursor, bid_id)
finally:
self.closeDB(cursor, commit=False)
if cursor is None:
self.closeDB(use_cursor, commit=False)
def getXmrOfferFromSession(self, cursor, offer_id: bytes):
offer = self.queryOne(Offer, cursor, {"offer_id": offer_id})
@@ -5875,7 +5883,7 @@ class BasicSwap(BaseApp, BSXNetwork, UIApp):
)
if bid.bid_id and bid_msg_id != bid.bid_id:
self.log.warning(
f"sendBidMessage: Mismatched bid ids: {bid.bid_id.hex()}, {bid_msg_id.hex()}."
f"sendBidMessage: Mismatched bid ids: {self.log.id(bid.bid_id)}, {self.log.id(bid_msg_id)}."
)
return bid_msg_id
@@ -7771,7 +7779,12 @@ class BasicSwap(BaseApp, BSXNetwork, UIApp):
len(xmr_swap.al_lock_refund_tx_sig) > 0
and len(xmr_swap.af_lock_refund_tx_sig) > 0
):
try:
if bid.xmr_b_lock_tx is None and self.haveDebugInd(
bid.bid_id, DebugTypes.WAIT_FOR_COIN_B_LOCK_BEFORE_PREREFUND
):
raise TemporaryError("Debug: Waiting for Coin B Lock Tx")
txid = ci_from.publishTx(xmr_swap.a_lock_refund_tx)
# BCH txids change
@@ -7821,6 +7834,10 @@ class BasicSwap(BaseApp, BSXNetwork, UIApp):
self.saveBidInSession(bid_id, bid, cursor, xmr_swap)
self.commitDB()
return rv
else:
self.log.warning(
f"Trying to publish coin a lock refund tx: {ex}"
)
state = BidStates(bid.state)
if state == BidStates.SWAP_COMPLETED:
@@ -8067,6 +8084,15 @@ class BasicSwap(BaseApp, BSXNetwork, UIApp):
self.log.warning(
f"Not releasing ads script coin lock tx for bid {self.log.id(bid_id)}: Chain A lock refund tx already exists."
)
elif (
bid.debug_ind == DebugTypes.DONT_RELEASE_COIN_A_LOCK
):
self.logBidEvent(
bid_id,
EventLogTypes.DEBUG_TWEAK_APPLIED,
f"ind {DebugTypes.DONT_RELEASE_COIN_A_LOCK}",
None,
)
else:
delay = self.get_delay_event_seconds()
self.log.info(
@@ -8513,9 +8539,8 @@ class BasicSwap(BaseApp, BSXNetwork, UIApp):
)
watched = self.coin_clients[coin_type]["watched_transactions"]
for wo in watched:
if wo.bid_id == bid_id and wo.txid_hex == txid_hex:
for wt in watched:
if wt.bid_id == bid_id and wt.txid_hex == txid_hex:
self.log.debug("Transaction already being watched.")
return
@@ -8953,7 +8978,7 @@ class BasicSwap(BaseApp, BSXNetwork, UIApp):
else:
self.log.info(
f"Coin a lock refund spent by unknown tx, bid {self.log.id(bid_id)}."
f"Coin a lock refund spent by unknown tx, bid {self.log.id(bid_id)}, txid {self.logIDT(spending_txid)}."
)
mercy_keyshare = None
@@ -8980,6 +9005,7 @@ class BasicSwap(BaseApp, BSXNetwork, UIApp):
bid.setState(BidStates.XMR_SWAP_FAILED_SWIPED)
else:
delay = self.get_delay_event_seconds()
self.log.info("Found mercy output.")
self.log.info(
f"Redeeming coin b lock tx for bid {self.log.id(bid_id)} in {delay} seconds."
)
@@ -9298,6 +9324,7 @@ class BasicSwap(BaseApp, BSXNetwork, UIApp):
self.processFoundTransaction(
t, block_hash, block["height"], chain_blocks
)
for s in c["watched_scripts"]:
for i, txo in enumerate(tx["vout"]):
if "scriptPubKey" in txo and "hex" in txo["scriptPubKey"]:
@@ -12174,7 +12201,9 @@ class BasicSwap(BaseApp, BSXNetwork, UIApp):
xmr_swap.af_lock_refund_spend_tx_sig = ci_from.decryptOtVES(
kbsl, xmr_swap.af_lock_refund_spend_tx_esig
)
prevout_amount = ci_from.getLockRefundTxSwapOutputValue(bid, xmr_swap)
prevout_amount: int = ci_from.getLockRefundTxSwapOutputValue(
bid, xmr_swap
)
al_lock_refund_spend_tx_sig = ci_from.signTx(
kal,
xmr_swap.a_lock_refund_spend_tx,
@@ -12601,8 +12630,7 @@ class BasicSwap(BaseApp, BSXNetwork, UIApp):
ci_from.verifyPubkey(msg_data.pkaf), "Invalid chain A follower public key"
)
ensure(
ci_from.isValidAddressHash(msg_data.dest_af)
or ci_from.isValidPubkey(msg_data.dest_af),
self.isValidSwapDest(ci_from, msg_data.dest_af),
"Invalid destination address",
)
if ci_to.curve_type() == Curves.ed25519:
+3
View File
@@ -240,8 +240,11 @@ class DebugTypes(IntEnum):
OFFER_LOCK_2_VALUE_INC = auto()
BID_STOP_AFTER_COIN_B_LOCK = auto()
BID_DONT_SPEND_COIN_B_LOCK = auto()
WAIT_FOR_COIN_B_LOCK_BEFORE_PREREFUND = auto()
WAIT_FOR_COIN_B_LOCK_BEFORE_REFUND = auto()
BID_DONT_SPEND_COIN_A_LOCK = auto()
DONT_SEND_COIN_B_LOCK = auto()
DONT_RELEASE_COIN_A_LOCK = auto()
class NotificationTypes(IntEnum):
+1 -1
View File
@@ -566,7 +566,7 @@ def getCoinIdFromTicker(ticker: str) -> str:
raise ValueError(f"Unknown coin {ticker}")
def getCoinIdFromName(name: str) -> str:
def getCoinIdFromName(name: str) -> Coins:
try:
return name_map[name.lower()]
except Exception:
-1
View File
@@ -1229,7 +1229,6 @@ class DBMethods:
values = {}
constraint_values = {}
set_columns = []
for mc in inspect.getmembers(obj.__class__):
mc_name, mc_obj = mc
if not hasattr(mc_obj, "__sqlite3_column__"):
+15 -4
View File
@@ -7,6 +7,7 @@
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
import base64
import copy
import hashlib
import json
import logging
@@ -530,6 +531,16 @@ class BTCInterface(Secp256k1Interface):
)
return self.rpc("getblockheader", [block_hash])
def getPrevBlockInChain(self, block_header_in):
block_header = copy.deeocopy(block_header_in)
while True:
previousblockhash = block_header.get("previousblockhash", None)
if previousblockhash is None:
raise RuntimeError("previousblockhash not in block_header")
if block_header["confirmations"] > 0:
return block_header
block_header = self.rpc("getblockheader", [previousblockhash])
def getBlockHeaderAt(self, time_target: int, block_after=False):
blockchaininfo = self.rpc("getblockchaininfo")
last_block_header = self.rpc(
@@ -1310,7 +1321,7 @@ class BTCInterface(Secp256k1Interface):
vkbv=None,
kbsf=None,
):
# lock refund swipe tx
# Lock refund swipe tx
# Sends the coinA locked coin to the follower
tx_lock_refund = self.loadTx(tx_lock_refund_bytes)
@@ -1584,7 +1595,7 @@ class BTCInterface(Secp256k1Interface):
)
if not self.compareFeeRates(fee_rate_paid, feerate):
raise ValueError("Bad fee rate, expected: {}".format(feerate))
raise ValueError(f"Bad fee rate, expected: {feerate}")
return txid, locked_coin, locked_n
@@ -1647,7 +1658,7 @@ class BTCInterface(Secp256k1Interface):
)
if not self.compareFeeRates(fee_rate_paid, feerate):
raise ValueError("Bad fee rate, expected: {}".format(feerate))
raise ValueError(f"Bad fee rate, expected: {feerate}")
return True
@@ -1706,7 +1717,7 @@ class BTCInterface(Secp256k1Interface):
)
if not self.compareFeeRates(fee_rate_paid, feerate):
raise ValueError("Bad fee rate, expected: {}".format(feerate))
raise ValueError(f"Bad fee rate, expected: {feerate}")
return True
+3 -3
View File
@@ -1403,7 +1403,7 @@ class DCRInterface(Secp256k1Interface):
)
if not self.compareFeeRates(fee_rate_paid, feerate):
raise ValueError("Bad fee rate, expected: {}".format(feerate))
raise ValueError(f"Bad fee rate, expected: {feerate}")
return True
@@ -1472,7 +1472,7 @@ class DCRInterface(Secp256k1Interface):
)
if not self.compareFeeRates(fee_rate_paid, feerate):
raise ValueError("Bad fee rate, expected: {}".format(feerate))
raise ValueError(f"Bad fee rate, expected: {feerate}")
return txid, locked_coin, locked_n
@@ -1533,7 +1533,7 @@ class DCRInterface(Secp256k1Interface):
)
if not self.compareFeeRates(fee_rate_paid, feerate):
raise ValueError("Bad fee rate, expected: {}".format(feerate))
raise ValueError(f"Bad fee rate, expected: {feerate}")
return True
+3 -3
View File
@@ -658,7 +658,7 @@ class PARTInterfaceBlind(PARTInterface):
ensure(
self.compareFeeRates(fee_rate_paid, feerate),
"Bad fee rate, expected: {}".format(feerate),
f"Bad fee rate, expected: {feerate}",
)
return (
@@ -734,7 +734,7 @@ class PARTInterfaceBlind(PARTInterface):
fee_rate_paid = fee_paid * 1000 // vsize
ensure(
self.compareFeeRates(fee_rate_paid, feerate),
"Bad fee rate, expected: {}".format(feerate),
f"Bad fee rate, expected: {feerate}",
)
return True
@@ -958,7 +958,7 @@ class PARTInterfaceBlind(PARTInterface):
fee_rate_paid = fee_paid * 1000 // vsize
self._log.info("vsize, feerate: %ld, %ld", vsize, fee_rate_paid)
if not self.compareFeeRates(fee_rate_paid, feerate):
raise ValueError("Bad fee rate, expected: {}".format(feerate))
raise ValueError(f"Bad fee rate, expected: {feerate}")
return True
+18
View File
@@ -45,3 +45,21 @@ class BSXLogger(logging.Logger):
def info_s(self, msg, *args, **kwargs):
if self.safe_logs is False:
self.info(msg, *args, **kwargs)
class BSXLogAdapter(logging.LoggerAdapter):
def __init__(self, logger, prefix):
super().__init__(logger, {})
self.prefix = prefix
def process(self, msg, kwargs):
return f"{self.prefix} {msg}", kwargs
def addr(self, addr: str) -> str:
return self.logger.addr(addr)
def id(self, concept_id: bytes, prefix: str = "") -> str:
return self.logger.id(concept_id, prefix)
def info_s(self, msg, *args, **kwargs):
return self.logger.info_s(msg, *args, **kwargs)