Debian Codegraph @

tests/test_submarine_swaps.py

raw symbols SCIP
1 import asyncio
2 import os
3 from typing import Optional, Sequence
4 from unittest import mock
5
6 from electrum_ecc import ECPrivkey
7
8 from electrum import util, bitcoin
9 from electrum.address_synchronizer import TX_HEIGHT_LOCAL
10 from electrum.bitcoin import COIN, DUST_LIMIT_P2WSH
11 from electrum.util import bfh, now, wait_for2
12 from electrum.crypto import sha256
13 from electrum.interface import PaddedRSTransport
14 from electrum.lnonion import OnionRoutingFailure
15 from electrum.simple_config import SimpleConfig
16 from electrum.submarine_swaps import (
17 SwapManager, SwapData, SwapServerTransport, LOCKTIME_DELTA_REFUND,
18 MIN_LOCKTIME_DELTA_FOR_CLAIM, SPENDER_FINALITY_DELAY, _construct_swap_scriptcode)
19 from electrum.transaction import (
20 PartialTransaction, PartialTxOutput, Transaction, TxOutput, TxOutpoint)
21 from electrum.txbatcher import TxBatcher
22 from electrum.wallet import Abstract_Wallet, Standard_Wallet, Wallet
23
24 from . import ElectrumTestCase, restore_wallet_from_text__for_unittest
25 from .toyserver.toynetwork import ToyNetwork
26 from .toyserver.toyserver import ToyServer
27
28
29 def random_address() -> str:
30 """an address that does not belong to any wallet of the test"""
31 return bitcoin.pubkey_to_address('p2wpkh', ECPrivkey(os.urandom(32)).get_public_key_hex(compressed=True))
32
33
34 class MockSwapServerTransport(SwapServerTransport):
35 def __init__(self, *, config: SimpleConfig, sm: SwapManager):
36 super().__init__(config=config, sm=sm)
37 self.requests = [] # type: list[tuple[str, Optional[dict]]]
38 self.is_connected.set()
39
40 async def send_request_to_server(self, method: str, request_data: Optional[dict]) -> dict:
41 self.requests.append((method, request_data))
42 return {}
43
44
45 class SwapTestWallet(Standard_Wallet):
46 def _start_network_lightning(self):
47 # start only the lightning parts the swap manager needs
48 self.lnworker.lnwatcher.start_network(self.network)
49 self.lnworker.swap_manager.start_network(self.network)
50
51
52 class SwapTestWalletFactory(Wallet):
53 @staticmethod
54 def wallet_class(wallet_type):
55 return SwapTestWallet
56
57
58 class TestSwapClaim(ElectrumTestCase):
59 """The counterparty ("the server") is simulated: we keep its privkey and the preimage in the
60 test, and build its claim tx with the same code the server would use.
61 """
62 REGTEST = True
63 TIME_STEP = 0.01
64
65 def setUp(self):
66 super().setUp()
67 self.config = SimpleConfig({'electrum_path': self.electrum_path})
68 self.config.NETWORK_SKIPMERKLECHECK = True
69 self.config.FEE_POLICY = 'feerate:5000'
70 self.config.FEE_POLICY_SWAPS = 'feerate:5000'
71 self._orig_wait_for_buffer_growth = PaddedRSTransport.WAIT_FOR_BUFFER_GROWTH_SECONDS
72 PaddedRSTransport.WAIT_FOR_BUFFER_GROWTH_SECONDS *= self.TIME_STEP
73
74 def tearDown(self):
75 PaddedRSTransport.WAIT_FOR_BUFFER_GROWTH_SECONDS = self._orig_wait_for_buffer_growth
76 super().tearDown()
77
78 async def asyncSetUp(self):
79 await super().asyncSetUp()
80 self.server = ToyServer()
81 await self.server.start()
82 self.network = ToyNetwork(config=self.config)
83 for _ in range(10):
84 await self.server.mine_block()
85 await self.server.set_up_faucet(config=self.config)
86 await self.network.connect(self.server)
87 self.wallet = restore_wallet_from_text__for_unittest(
88 "9dk", passphrase="alice", path=None, config=self.config,
89 wallet_factory=SwapTestWalletFactory)['wallet'] # type: Abstract_Wallet
90 self.wallet.start_network(self.network)
91 self.sm = self.wallet.lnworker.swap_manager
92 self.adb = self.wallet.adb
93 self.wallet.txbatcher.SLEEP_INTERVAL *= self.TIME_STEP
94 await self.pay_to_address(self.wallet.get_receiving_address(), 1 * COIN)
95 await self.mine_blocks(1)
96
97 async def asyncTearDown(self):
98 await self.wallet.stop()
99 await self.network.stop()
100 await self.server.stop()
101 await super().asyncTearDown()
102
103 # --- chain and wallet helpers ---
104
105 async def wait_until(self, predicate, *, timeout: int = 10) -> None:
106 async with util.async_timeout(timeout):
107 while not predicate():
108 await asyncio.sleep(self.TIME_STEP)
109
110 async def sync(self) -> None:
111 """wait until the wallet has caught up with the server"""
112 await self.wait_until(
113 lambda: self.adb.get_local_height() == self.server.cur_height
114 and self.adb.is_up_to_date()
115 and self.wallet.is_up_to_date())
116
117 async def broadcast(self, tx: Transaction) -> Transaction:
118 await self.network.broadcast_transaction(tx)
119 await self.wait_until(lambda: self.adb.get_transaction(tx.txid()) is not None)
120 await self.sync()
121 return tx
122
123 async def pay_to_address(self, address: str, value: int) -> Transaction:
124 """a third party (the faucet) sends coins to address, leaving the tx in the mempool"""
125 tx = await self.server.ask_faucet([TxOutput.from_address_and_value(address, value)])
126 await self.wait_until(lambda: self.adb.get_transaction(tx.txid()) is not None)
127 await self.sync()
128 return tx
129
130 async def mine_blocks(self, count: int, *, include_mempool: bool = True) -> None:
131 for _ in range(count):
132 await self.server.mine_block(include_mempool=include_mempool)
133 await self.sync()
134
135 async def mine_until_swap_expires(self, swap: SwapData) -> None:
136 await self.mine_blocks(swap.locktime - self.network.get_local_height())
137
138 async def reorg_replace_tip_tx(self, tx: Transaction, replacement: Transaction) -> None:
139 """The block at the tip is reorged out and mined again at the same height, but now
140 it contains replacement, which conflicts with tx. tx is evicted along the way.
141 """
142 self.assertEqual(self.server.cur_height, self.server.block_height_from_txid(tx.txid()))
143 await self.server.unmine_block()
144 await self.server.mempool_rm_tx(tx)
145 await self.server.mempool_add_tx(replacement)
146 await self.server.mine_block()
147 await self.wait_until(
148 lambda: self.adb.get_tx_height(replacement.txid()).conf > 0)
149 await self.sync()
150
151 async def restart_txbatcher(self) -> None:
152 """Restart the txbatcher, the way a wallet restart would: TxBatcher.__init__ rebuilds
153 its batches from the wallet db, which persists only the txids and the prevout of the
154 current batch tx. The sweep info is not persisted, so whoever added a sweep input has
155 to add it again, otherwise add_sweep_info_to_tx() cannot sign a replacement of the
156 tx we already broadcast.
157 """
158 await self.wallet.txbatcher.taskgroup.cancel_remaining()
159 self.wallet.txbatcher = TxBatcher(self.wallet)
160 self.wallet.txbatcher.SLEEP_INTERVAL *= self.TIME_STEP
161 await self.wallet.taskgroup.spawn(self.wallet.txbatcher.run())
162
163 def utxos_at_lockup_address(self, swap: SwapData) -> Sequence[TxOutpoint]:
164 return list(self.adb.get_addr_outputs(swap.lockup_address).keys())
165
166 def spender_of(self, prevout: TxOutpoint) -> Optional[str]:
167 """txid of the tx spending prevout, as seen by the server"""
168 return self.server.txo_to_spender_txid[prevout]
169
170 async def wait_for_spender_of(self, prevout: TxOutpoint) -> Transaction:
171 """wait for the txbatcher to broadcast a tx spending prevout"""
172 await self.wait_until(lambda: self.spender_of(prevout) is not None)
173 return Transaction(self.server.txs[self.spender_of(prevout)])
174
175 async def spender_of_within(self, prevout: TxOutpoint, *, timeout: float = 2) -> Optional[Transaction]:
176 """like wait_for_spender_of, but returns None if we did not broadcast anything"""
177 try:
178 return await wait_for2(self.wait_for_spender_of(prevout), timeout)
179 except asyncio.TimeoutError:
180 return None
181
182 # --- swap helpers ---
183
184 def create_forward_swap(self, *, onchain_amount: int = 100_000) -> SwapData:
185 """Client side of a forward swap: we send on-chain, we receive on lightning.
186 Same as request_normal_swap() would create after an honest server response.
187 """
188 self.preimage = os.urandom(32)
189 self.server_privkey = os.urandom(32)
190 server_pubkey = ECPrivkey(self.server_privkey).get_public_key_bytes(compressed=True)
191 refund_privkey = os.urandom(32)
192 refund_pubkey = ECPrivkey(refund_privkey).get_public_key_bytes(compressed=True)
193 payment_hash = sha256(self.preimage)
194 locktime = self.network.get_local_height() + LOCKTIME_DELTA_REFUND
195 redeem_script = _construct_swap_scriptcode(
196 payment_hash=payment_hash,
197 locktime=locktime,
198 refund_pubkey=refund_pubkey,
199 claim_pubkey=server_pubkey,
200 )
201 swap, invoice, _prepay = self.sm.add_normal_swap(
202 redeem_script=redeem_script,
203 locktime=locktime,
204 onchain_amount_sat=onchain_amount,
205 lightning_amount_sat=onchain_amount + 1000,
206 payment_hash=payment_hash,
207 our_privkey=refund_privkey,
208 prepay=False,
209 )
210 self.invoice = invoice # the hold invoice we hand to the server
211 # the client holds the incoming htlcs until it learns the preimage from the claim tx
212 self.sm.lnworker.register_hold_invoice(payment_hash, self.sm.hold_invoice_callback)
213 return swap
214
215 def create_reverse_swap(
216 self, *,
217 onchain_amount: int = 100_000,
218 claim_to_output: Optional[TxOutput] = None,
219 ) -> SwapData:
220 """Client side of a reverse swap: we send on lightning, we receive on-chain.
221 With claim_to_output set this is a submarine payment: we claim to a third party.
222 """
223 self.preimage = os.urandom(32)
224 self.server_privkey = os.urandom(32)
225 server_pubkey = ECPrivkey(self.server_privkey).get_public_key_bytes(compressed=True)
226 claim_privkey = os.urandom(32)
227 claim_pubkey = ECPrivkey(claim_privkey).get_public_key_bytes(compressed=True)
228 payment_hash = sha256(self.preimage)
229 locktime = self.network.get_local_height() + LOCKTIME_DELTA_REFUND
230 redeem_script = _construct_swap_scriptcode(
231 payment_hash=payment_hash,
232 locktime=locktime,
233 refund_pubkey=server_pubkey,
234 claim_pubkey=claim_pubkey,
235 )
236 return self.sm.add_reverse_swap(
237 redeem_script=redeem_script,
238 locktime=locktime,
239 privkey=claim_privkey,
240 preimage=self.preimage,
241 payment_hash=payment_hash,
242 onchain_amount_sat=onchain_amount,
243 lightning_amount_sat=onchain_amount + 1000,
244 claim_to_output=claim_to_output,
245 )
246
247 async def client_funds_swap(self, swap: SwapData) -> Transaction:
248 """what the client does when the server's htlcs arrive (see wait_for_htlcs_and_broadcast)"""
249 tx = self.sm.create_funding_tx(swap, None, password=None)
250 await self.broadcast(tx)
251 swap.funding_txid = tx.txid()
252 return tx
253
254 async def server_claims_utxo(self, swap: SwapData, prevout: TxOutpoint) -> Transaction:
255 """the server spends a lockup utxo, revealing the preimage in the witness"""
256 return await self.broadcast(self.server_claim_tx(swap, prevout))
257
258 def server_claim_tx(self, swap: SwapData, prevout: TxOutpoint) -> Transaction:
259 """the tx with which the server spends a lockup utxo, revealing the preimage"""
260 server_swap = SwapData(
261 is_reverse=True, # the server's point of view of our forward swap
262 locktime=swap.locktime,
263 onchain_amount=swap.onchain_amount,
264 lightning_amount=swap.lightning_amount,
265 redeem_script=swap.redeem_script,
266 preimage=self.preimage,
267 prepay_hash=None,
268 privkey=self.server_privkey,
269 lockup_address=swap.lockup_address,
270 claim_to_output=None,
271 funding_txid=prevout.txid.hex(),
272 spending_txid=None,
273 is_redeemed=False,
274 )
275 txin = self.adb.get_addr_outputs(swap.lockup_address)[prevout]
276 txin, _locktime = SwapManager.create_claim_txin(txin=txin, swap=server_swap)
277 tx = PartialTransaction.from_io(
278 [txin],
279 [PartialTxOutput.from_address_and_value(random_address(), txin.value_sats() - 1000)],
280 version=2,
281 )
282 txin.witness = txin.make_witness(tx.sign_txin(0, server_swap.privkey))
283 assert tx.is_complete(), tx
284 return tx
285
286 def server_refund_tx(self, swap: SwapData, prevout: TxOutpoint, *, fee: int) -> Transaction:
287 """the server takes back the utxo it locked up for us, using the timeout branch.
288 This is only valid in a block of height > swap.locktime.
289 """
290 server_swap = SwapData(
291 is_reverse=False, # the server's point of view of our reverse swap
292 locktime=swap.locktime,
293 onchain_amount=swap.onchain_amount,
294 lightning_amount=swap.lightning_amount,
295 redeem_script=swap.redeem_script,
296 preimage=None, # not known by the server
297 prepay_hash=None,
298 privkey=self.server_privkey,
299 lockup_address=swap.lockup_address,
300 claim_to_output=None,
301 funding_txid=prevout.txid.hex(),
302 spending_txid=None,
303 is_redeemed=False,
304 )
305 txin = self.adb.get_addr_outputs(swap.lockup_address)[prevout]
306 txin, locktime = SwapManager.create_claim_txin(txin=txin, swap=server_swap)
307 self.assertEqual(swap.locktime, locktime)
308 tx = PartialTransaction.from_io(
309 [txin],
310 [PartialTxOutput.from_address_and_value(random_address(), txin.value_sats() - fee)],
311 locktime=locktime,
312 version=2,
313 )
314 txin.witness = txin.make_witness(tx.sign_txin(0, server_swap.privkey))
315 assert tx.is_complete(), tx
316 return tx
317
318 async def server_wins_race_for_lockup_utxo(self, swap: SwapData, claim_tx: Transaction) -> Transaction:
319 """The server saw our claim tx (and the preimage in it) in the mempool. Since the
320 locktime has passed, its refund tx is final, so it can simply outbid our claim tx.
321 """
322 self.assertLessEqual(swap.locktime, self.network.get_local_height())
323 self.assertEqual(self.preimage, SwapManager.extract_preimage(swap, claim_tx))
324 claim_fee = self.server._get_fee_sat_paid_by_tx(claim_tx)
325 refund_tx = self.server_refund_tx(swap, swap._funding_prevout, fee=claim_fee + 10_000)
326 await self.broadcast(refund_tx)
327 await self.mine_blocks(1)
328 return refund_tx
329
330 # --- tests ---
331
332 async def test_forward_swap_ignores_undervalued_lockup_utxos(self):
333 """A malicious server knows the lockup address before we fund it. If it pays dust
334 into it, we must not mistake those utxos for our funding utxo: the preimage can
335 only ever be extracted from the utxo that pays the full swap amount.
336 """
337 swap = self.create_forward_swap(onchain_amount=100_000)
338 self.assertIn(swap.lockup_address, self.wallet.lnworker.lnwatcher.callbacks)
339 for _ in range(3):
340 await self.pay_to_address(swap.lockup_address, DUST_LIMIT_P2WSH)
341 await self.mine_blocks(1)
342 # the decoys are in our history, but the swap is not funded
343 self.assertEqual(3, len(self.utxos_at_lockup_address(swap)))
344 await self.sm._claim_swap(swap)
345 self.assertIsNone(swap.funding_txid)
346 self.assertFalse(swap.is_funded())
347 self.assertFalse(self.wallet.txbatcher.tx_batches)
348
349 async def test_forward_swap_fails_swap_when_only_undervalued_utxos_at_expiry(self):
350 """Nothing was locked up for us, so the held htlcs must be failed at expiry
351 instead of being stuck waiting for a preimage we can never learn.
352 """
353 swap = self.create_forward_swap(onchain_amount=100_000)
354 payment_hash = swap.payment_hash
355 await self.pay_to_address(swap.lockup_address, swap.onchain_amount - 1)
356 with self.assertLogs(self.sm.logger.name, level='INFO') as logs:
357 await self.mine_until_swap_expires(swap)
358 await self.sm._claim_swap(swap)
359 self.assertIn(f'failing swap {payment_hash.hex()}: expired: remaining_time=0 blocks', [record.getMessage() for record in logs.records])
360 self.assertNotIn(payment_hash, self.wallet.lnworker.hold_invoice_callbacks)
361 self.assertNotIn(payment_hash.hex(), self.wallet.db.get_dict('submarine_swaps'))
362 self.assertNotIn(swap.lockup_address, self.wallet.lnworker.lnwatcher.callbacks)
363
364 async def test_forward_swap_extracts_preimage_from_funding_utxo(self):
365 """The preimage must be extracted from the utxo we funded, even if the lockup
366 address also holds decoy utxos of the malicious server.
367 """
368 swap = self.create_forward_swap(onchain_amount=100_000)
369 for i in range(1, 4):
370 await self.pay_to_address(swap.lockup_address, DUST_LIMIT_P2WSH)
371 funding_tx = await self.client_funds_swap(swap)
372 await self.mine_blocks(1)
373 await self.sm._claim_swap(swap)
374 # the funding utxo was selected, not one of the decoys
375 self.assertEqual(funding_tx.txid(), swap._funding_prevout.txid.hex())
376 self.assertEqual(funding_tx.txid(), swap.funding_txid)
377 self.assertIsNone(swap.preimage)
378 # the server claims our funding utxo, revealing the preimage
379 claim_tx = await self.server_claims_utxo(swap, swap._funding_prevout)
380 await self.mine_blocks(1)
381 await self.sm._claim_swap(swap)
382 self.assertEqual(self.preimage, swap.preimage)
383 self.assertEqual(self.preimage, self.wallet.lnworker.get_preimage(swap.payment_hash))
384 self.assertEqual(claim_tx.txid(), swap.spending_txid)
385
386 async def test_forward_swap_funds_lockup_address_when_htlcs_arrive(self):
387 """The server's htlcs arrived, so we must lock up exactly the swap amount. From
388 then on the swap must not be cancellable anymore: the funding output is queued,
389 and cancelling would fail the htlcs while we still pay on-chain.
390 """
391 swap = self.create_forward_swap(onchain_amount=100_000)
392 self.assertFalse(swap.is_funded())
393 await self.sm.hold_invoice_callback(swap.payment_hash)
394 self.assertTrue(swap.is_funded())
395 with self.assertLogs(self.sm.logger.name, level='INFO') as logs:
396 self.sm.cancel_normal_swap(swap)
397 self.assertIn(
398 f'cannot cancel swap {swap.payment_hash.hex()}: already funded',
399 [record.getMessage() for record in logs.records])
400 self.assertIn(swap.payment_hash.hex(), self.wallet.db.get_dict('submarine_swaps'))
401 self.assertIn(swap.payment_hash, self.wallet.lnworker.hold_invoice_callbacks)
402 # the txbatcher pays the lockup address
403 await self.wait_until(lambda: len(self.utxos_at_lockup_address(swap)) == 1)
404 await self.mine_blocks(1)
405 await self.sm._claim_swap(swap)
406 txin = self.adb.get_addr_outputs(swap.lockup_address)[swap._funding_prevout]
407 self.assertEqual(swap.onchain_amount, txin.value_sats())
408 self.assertEqual(swap.funding_txid, swap._funding_prevout.txid.hex())
409
410 async def test_forward_swap_stops_watching_after_claim_tx_is_deeply_confirmed(self):
411 """Once the server's claim tx is confirmed deeply, the swap is done: we stop watching the
412 lockup address and release the hold invoice, instead of watching it forever.
413 """
414 swap = self.create_forward_swap(onchain_amount=100_000)
415 await self.client_funds_swap(swap)
416 await self.mine_blocks(1)
417 await self.sm._claim_swap(swap)
418 await self.server_claims_utxo(swap, swap._funding_prevout)
419 await self.mine_blocks(1)
420 await self.sm._claim_swap(swap)
421 self.assertEqual(self.preimage, swap.preimage)
422 self.assertFalse(swap.is_redeemed)
423 self.assertIn(swap.lockup_address, self.wallet.lnworker.lnwatcher.callbacks)
424 # one block short of finality we keep watching
425 await self.mine_blocks(SPENDER_FINALITY_DELAY - 1)
426 await self.sm._claim_swap(swap)
427 self.assertFalse(swap.is_redeemed)
428 self.assertIn(swap.lockup_address, self.wallet.lnworker.lnwatcher.callbacks)
429 # now the claim tx can no longer be reorged out
430 await self.mine_blocks(1)
431 await self.sm._claim_swap(swap)
432 self.assertTrue(swap.is_redeemed)
433 self.assertNotIn(swap.lockup_address, self.wallet.lnworker.lnwatcher.callbacks)
434 self.assertNotIn(swap.payment_hash, self.wallet.lnworker.hold_invoice_callbacks)
435
436 async def test_forward_swap_does_not_refund_after_learning_the_preimage(self):
437 """The server's claim tx revealed the preimage but then fell out of the mempool.
438 We must not try to refund: we can settle the htlcs, so the coins are the server's.
439 """
440 swap = self.create_forward_swap(onchain_amount=100_000)
441 await self.client_funds_swap(swap)
442 await self.mine_blocks(1)
443 await self.sm._claim_swap(swap)
444 claim_tx = await self.server_claims_utxo(swap, swap._funding_prevout)
445 await self.sm._claim_swap(swap)
446 self.assertEqual(self.preimage, swap.preimage)
447 # the claim tx is evicted, so the lockup utxo looks unspent again
448 await self.server.mempool_rm_tx(claim_tx)
449 await self.wait_until(
450 lambda: self.adb.get_tx_height(claim_tx.txid()).height() == TX_HEIGHT_LOCAL)
451 await self.mine_until_swap_expires(swap)
452 await self.sm._claim_swap(swap)
453 self.assertFalse(self.wallet.txbatcher.tx_batches)
454 self.assertIsNone(self.spender_of(swap._funding_prevout))
455
456 async def test_forward_swap_refunds_funding_utxo_after_expiry(self):
457 """If the server never claims, we refund our funding utxo. A decoy utxo must not
458 take its place: it would be dropped as dust and we would refund nothing.
459 """
460 swap = self.create_forward_swap(onchain_amount=100_000)
461 decoy_tx = await self.pay_to_address(swap.lockup_address, DUST_LIMIT_P2WSH)
462 funding_tx = await self.client_funds_swap(swap)
463 await self.mine_until_swap_expires(swap)
464 await self.sm._claim_swap(swap)
465 self.assertEqual(funding_tx.txid(), swap._funding_prevout.txid.hex())
466 refund_tx = await self.wait_for_spender_of(swap._funding_prevout)
467 self.assertIsNone(SwapManager.extract_preimage(swap, refund_tx))
468 self.assertTrue(self.wallet.adb.is_mine(refund_tx.outputs()[0].address))
469 self.assertIsNone(self.spender_of(TxOutpoint(bfh(decoy_tx.txid()), 0)))
470
471 async def test_forward_swap_keeps_htlcs_until_refund_tx_is_deeply_confirmed(self):
472 """A refund tx with a single confirmation can still be reorged out and replaced by
473 the server's claim tx. Failing the held htlcs is irreversible, so until the refund
474 is confirmed deeply we must keep holding them: otherwise we give the ln payment back while
475 the server can still take our on-chain coins.
476 """
477 swap = self.create_forward_swap(onchain_amount=100_000)
478 payment_hash = swap.payment_hash
479 await self.client_funds_swap(swap)
480 await self.mine_until_swap_expires(swap)
481 await self.sm._claim_swap(swap)
482 refund_tx = await self.wait_for_spender_of(swap._funding_prevout)
483 await self.mine_blocks(1)
484 await self.sm._claim_swap(swap)
485 self.assertEqual(refund_tx.txid(), swap.spending_txid)
486 self.assertIn(payment_hash, self.wallet.lnworker.hold_invoice_callbacks)
487 self.assertIn(swap.lockup_address, self.wallet.lnworker.lnwatcher.callbacks)
488
489 # the reorg replaces our refund tx with the claim tx of the server
490 claim_tx = self.server_claim_tx(swap, swap._funding_prevout)
491 await self.reorg_replace_tip_tx(refund_tx, claim_tx)
492 await self.sm._claim_swap(swap)
493 # we still hold the htlcs, so the preimage is worth something to us
494 self.assertEqual(claim_tx.txid(), swap.spending_txid)
495 self.assertEqual(self.preimage, swap.preimage)
496 self.assertEqual(self.preimage, self.wallet.lnworker.get_preimage(payment_hash))
497 self.assertIn(payment_hash, self.wallet.lnworker.hold_invoice_callbacks)
498
499 async def test_forward_swap_fails_swap_when_refund_tx_confirms(self):
500 """Once our refund is confirmed deeply we can never learn the preimage, so the held htlcs
501 must be failed. Otherwise they stay pending until the server force-closes on us.
502 """
503 swap = self.create_forward_swap(onchain_amount=100_000)
504 payment_hash = swap.payment_hash
505 await self.client_funds_swap(swap)
506 await self.mine_until_swap_expires(swap)
507 await self.sm._claim_swap(swap)
508 refund_tx = await self.wait_for_spender_of(swap._funding_prevout)
509 # one block short of finality we must still hold the htlcs
510 await self.mine_blocks(SPENDER_FINALITY_DELAY)
511 await self.sm._claim_swap(swap)
512 self.assertIn(payment_hash, self.wallet.lnworker.hold_invoice_callbacks)
513 # now the refund tx can no longer be reorged out
514 await self.mine_blocks(1)
515 with self.assertLogs(self.sm.logger.name, level='INFO') as logs:
516 await self.sm._claim_swap(swap)
517 self.assertIn(
518 f'failing swap {payment_hash.hex()}: refund tx confirmed',
519 [record.getMessage() for record in logs.records])
520 self.assertEqual(refund_tx.txid(), swap.spending_txid)
521 self.assertNotIn(payment_hash, self.wallet.lnworker.hold_invoice_callbacks)
522 self.assertNotIn(swap.lockup_address, self.wallet.lnworker.lnwatcher.callbacks)
523 # the swap was funded, so we keep it: the history groups funding and refund tx
524 self.assertIn(payment_hash.hex(), self.wallet.db.get_dict('submarine_swaps'))
525
526 async def test_forward_swap_fails_swap_when_htlcs_never_arrive(self):
527 """The server took our hold invoice and never paid it. When the invoice expires the
528 swap must be failed, so that no caller can go on to broadcast the funding tx anyway.
529 """
530 swap = self.create_forward_swap(onchain_amount=100_000)
531 payment_hash = swap.payment_hash
532 tx = self.sm.create_funding_tx(swap, None, password=None)
533 transport = MockSwapServerTransport(config=self.config, sm=self.sm)
534 # the hold invoice is created with a 300s expiry, so this is one second past it
535 expired_clock = now() + 301
536 with mock.patch('electrum.submarine_swaps.now', lambda: expired_clock):
537 funding_txid = await self.sm.wait_for_htlcs_and_broadcast(
538 transport=transport, swap=swap, invoice=self.invoice, tx=tx)
539 # we sent the request to the server
540 self.assertEqual(['addswapinvoice'], [method for method, _data in transport.requests])
541 self.assertIsNone(funding_txid)
542 self.assertIsNone(swap.funding_txid)
543 # nothing was locked up
544 self.assertNotIn(tx.txid(), self.server.txs)
545 # the swap is gone
546 self.assertNotIn(payment_hash, self.wallet.lnworker.hold_invoice_callbacks)
547 self.assertNotIn(payment_hash.hex(), self.wallet.db.get_dict('submarine_swaps'))
548 self.assertNotIn(swap.lockup_address, self.wallet.lnworker.lnwatcher.callbacks)
549
550 async def test_forward_swap_cancel_does_not_race_dispatched_hold_invoice_callback(self):
551 """lnpeer dispatches the hold-invoice callback as an independent task, so a cancel
552 can land after the callback is scheduled but before it runs. The callback must then
553 not broadcast the funding tx, and must fail the htlcs rather than leave them hanging.
554 """
555 swap = self.create_forward_swap(onchain_amount=100_000)
556 payment_hash = swap.payment_hash
557 tx = self.sm.create_funding_tx(swap, None, password=None)
558 transport = MockSwapServerTransport(config=self.config, sm=self.sm)
559 fut = asyncio.create_task(self.sm.wait_for_htlcs_and_broadcast(
560 transport=transport, swap=swap, invoice=self.invoice, tx=tx))
561 # the callback is registered just before the invoice is sent to the server
562 await self.wait_until(lambda: bool(transport.requests))
563 # the server's htlcs arrived: lnpeer looked up the callback and scheduled it,
564 # but the user cancels before it gets to run
565 callback = self.wallet.lnworker.hold_invoice_callbacks[payment_hash]
566 self.assertTrue(self.sm.cancel_normal_swap(swap))
567 with self.assertRaises(OnionRoutingFailure):
568 await callback(payment_hash)
569 self.assertIsNone(await fut)
570 self.assertIsNone(swap.funding_txid)
571 # nothing was locked up, and the swap is gone
572 self.assertNotIn(tx.txid(), self.server.txs)
573 self.assertNotIn(payment_hash, self.wallet.lnworker.hold_invoice_callbacks)
574 self.assertNotIn(payment_hash.hex(), self.wallet.db.get_dict('submarine_swaps'))
575 self.assertNotIn(swap.lockup_address, self.wallet.lnworker.lnwatcher.callbacks)
576
577 async def test_forward_swap_cannot_be_cancelled_once_funding_is_broadcast(self):
578 """Once the callback has claimed the swap the cancel must be refused, and it must
579 leave the refund key and the lnwatcher callback intact.
580 """
581 swap = self.create_forward_swap(onchain_amount=100_000)
582 payment_hash = swap.payment_hash
583 tx = self.sm.create_funding_tx(swap, None, password=None)
584 transport = MockSwapServerTransport(config=self.config, sm=self.sm)
585 fut = asyncio.create_task(self.sm.wait_for_htlcs_and_broadcast(
586 transport=transport, swap=swap, invoice=self.invoice, tx=tx))
587 await self.wait_until(lambda: bool(transport.requests))
588 # the htlcs arrived and the callback ran: we are committed to the swap
589 await self.wallet.lnworker.hold_invoice_callbacks[payment_hash](payment_hash)
590 self.assertEqual(tx.txid(), await fut)
591 self.assertFalse(self.sm.cancel_normal_swap(swap))
592 self.assertIn(tx.txid(), self.server.txs)
593 self.assertIn(payment_hash.hex(), self.wallet.db.get_dict('submarine_swaps'))
594 self.assertIn(swap.lockup_address, self.wallet.lnworker.lnwatcher.callbacks)
595
596 async def test_reverse_swap_does_not_claim_underpaid_lockup_utxo(self):
597 """As the client of a reverse swap we know the preimage, and we must
598 not reveal it on-chain unless the lockup utxo pays us the full swap amount.
599 """
600 swap = self.create_reverse_swap(onchain_amount=100_000)
601 underpaid_tx = await self.pay_to_address(swap.lockup_address, swap.onchain_amount - 1)
602 await self.mine_blocks(2)
603 await self.sm._claim_swap(swap)
604 self.assertFalse(self.wallet.txbatcher.tx_batches)
605 self.assertIsNone(self.spender_of(TxOutpoint(bfh(underpaid_tx.txid()), 0)))
606 self.assertIsNone(swap.funding_txid)
607 # now the server funds the swap properly
608 funding_tx = await self.pay_to_address(swap.lockup_address, swap.onchain_amount)
609 await self.mine_blocks(1)
610 await self.sm._claim_swap(swap)
611 self.assertEqual(funding_tx.txid(), swap.funding_txid)
612 claim_tx = await self.wait_for_spender_of(swap._funding_prevout)
613 self.assertEqual(self.preimage, SwapManager.extract_preimage(swap, claim_tx))
614
615 async def test_reverse_swap_does_not_reveal_preimage_when_funding_confirms_at_locktime(self):
616 """A malicious server can withhold the funding tx until the tip has almost reached the
617 locktime. We must not reveal the preimage then: in the next
618 block the server's refund tx is final too. So the server can replace our claim tx,
619 read the preimage from it, and settle the ln htlc.
620 Not claiming at all is strictly better for us: then the server
621 never learns the preimage and our ln payment is refunded when the htlc expires.
622 """
623 swap = self.create_reverse_swap(onchain_amount=100_000)
624 # the server funds only once the tip is one block below the locktime
625 await self.mine_blocks(swap.locktime - 1 - self.network.get_local_height())
626 await self.pay_to_address(swap.lockup_address, swap.onchain_amount)
627 await self.mine_blocks(1)
628 # the funding tx got its first confirmation in the block at swap.locktime
629 self.assertEqual(swap.locktime, self.network.get_local_height())
630 self.assertEqual(swap.locktime, self.adb.get_tx_height(swap.funding_txid or '').height())
631
632 await self.sm._claim_swap(swap)
633 claim_tx = await self.spender_of_within(swap._funding_prevout, timeout=2)
634 self.assertIsNone(claim_tx, 'preimage revealed while the server can already refund')
635
636 async def test_reverse_swap_does_not_reveal_preimage_when_funding_confirms_late(self):
637 """Same hazard as above, but the server funds early with a tx that does not get mined.
638 We queue the claim while it is still safe, and the txbatcher holds it back until the
639 funding tx has a confirmation. By the time that happens the locktime may have passed,
640 so whether we reveal the preimage is decided by the txbatcher, not by _claim_swap.
641 """
642 swap = self.create_reverse_swap(onchain_amount=100_000)
643 await self.pay_to_address(swap.lockup_address, swap.onchain_amount)
644 await self.sm._claim_swap(swap)
645 # the funding tx is unconfirmed, so nothing can be claimed yet
646 self.assertIsNone(await self.spender_of_within(swap._funding_prevout, timeout=1))
647 # blocks go by without the funding tx being mined
648 await self.mine_blocks(swap.locktime - self.network.get_local_height(), include_mempool=False)
649 await self.sm._claim_swap(swap)
650 # now it confirms, and the server's refund tx is final from the next block on
651 await self.mine_blocks(1)
652 self.assertLess(swap.locktime, self.network.get_local_height())
653 self.assertEqual(1, self.adb.get_tx_height(swap.funding_txid).conf)
654
655 claim_tx = await self.spender_of_within(swap._funding_prevout, timeout=2)
656 self.assertIsNone(claim_tx, 'preimage revealed while the server can already refund')
657
658 async def test_reverse_swap_keeps_claiming_after_the_preimage_became_public(self):
659 """Our claim tx is in the mempool, so the server can read the preimage from it and
660 settle the ln htlc whenever it wants. Dropping the claim now would leave it with
661 both the ln payment and its coins, so once the preimage is out we must keep the
662 claim alive, even past the point where we would not have started claiming anymore.
663 """
664 swap = self.create_reverse_swap(onchain_amount=100_000)
665 await self.pay_to_address(swap.lockup_address, swap.onchain_amount)
666 await self.mine_blocks(1)
667 await self.sm._claim_swap(swap)
668 claim_tx = await self.wait_for_spender_of(swap._funding_prevout)
669 self.assertEqual(self.preimage, SwapManager.extract_preimage(swap, claim_tx))
670
671 # the claim tx does not get mined, until we are past the expiry of the sweep
672 expiry_height = swap.locktime - MIN_LOCKTIME_DELTA_FOR_CLAIM
673 await self.mine_blocks(expiry_height - self.network.get_local_height(), include_mempool=False)
674 self.assertEqual(expiry_height, self.network.get_local_height())
675 self.assertEqual(claim_tx.txid(), self.spender_of(swap._funding_prevout))
676
677 await self.restart_txbatcher()
678 await self.sm._claim_swap(swap)
679 batch = self.wallet.txbatcher.tx_batches['swaps']
680 self.assertIn(swap._funding_prevout, batch.batch_inputs)
681
682 # with the sweep info back, the claim tx can still be replaced, e.g. to bump its fee
683 self.config.FEE_POLICY_SWAPS = 'feerate:20000'
684 await self.wait_until(lambda: self.spender_of(swap._funding_prevout) != claim_tx.txid())
685 replacement_tx = Transaction(self.server.txs[self.spender_of(swap._funding_prevout)])
686 self.assertEqual(self.preimage, SwapManager.extract_preimage(swap, replacement_tx))
687
688 async def test_reverse_swap_does_not_claim_against_an_unconfirmed_refund_tx(self):
689 """Companion of the test above: the lockup utxo is spent, but by the server's
690 refund tx, which reveals no preimage. Ours is still secret, so revealing it now
691 would only let the server settle the ln htlc while it outbids our claim tx.
692 """
693 swap = self.create_reverse_swap(onchain_amount=100_000)
694 await self.mine_until_swap_expires(swap)
695 await self.pay_to_address(swap.lockup_address, swap.onchain_amount)
696 await self.mine_blocks(1)
697 prevout = self.utxos_at_lockup_address(swap)[0]
698 refund_tx = await self.broadcast(self.server_refund_tx(swap, prevout, fee=1000))
699
700 await self.sm._claim_swap(swap)
701 self.assertFalse(self.wallet.txbatcher.tx_batches)
702 self.assertEqual(refund_tx.txid(), self.spender_of(prevout))
703
704 async def test_reverse_swap_claims_to_external_output(self):
705 """Submarine payment: the claim tx pays the payee directly, so it must pay exactly
706 the amount we promised them, and only once the funding tx cannot be double spent.
707 """
708 payee_address = random_address()
709 swap = self.create_reverse_swap(
710 onchain_amount=100_000,
711 claim_to_output=TxOutput.from_address_and_value(payee_address, 99_000))
712 funding_tx = await self.pay_to_address(swap.lockup_address, swap.onchain_amount)
713 await self.sm._claim_swap(swap)
714 # the funding tx is unconfirmed, so the claim tx is only kept as a future tx
715 await self.wait_until(lambda: bool(self.adb.future_tx))
716 self.assertIsNone(self.spender_of(swap._funding_prevout))
717 self.assertEqual(funding_tx.txid(), swap.funding_txid)
718 await self.mine_blocks(1)
719 await self.sm._claim_swap(swap)
720 claim_tx = await self.wait_for_spender_of(swap._funding_prevout)
721 self.assertEqual(self.preimage, SwapManager.extract_preimage(swap, claim_tx))
722 self.assertEqual(1, len(claim_tx.outputs()))
723 self.assertEqual(payee_address, claim_tx.outputs()[0].address)
724 self.assertEqual(99_000, claim_tx.outputs()[0].value)