Debian Codegraph @

tests/test_txbatcher.py

raw symbols SCIP
1 import logging
2 from unittest import mock
3 import asyncio
4 import dataclasses
5
6 from aiorpcx import timeout_after
7
8 import electrum.fee_policy
9 from electrum import keystore, wallet, lnutil
10 from electrum import SimpleConfig
11 from electrum import util
12 from electrum.address_synchronizer import TX_HEIGHT_UNCONFIRMED
13 from electrum.transaction import Transaction, PartialTxInput, PartialTxOutput, TxOutpoint
14 from electrum.logging import console_stderr_handler, Logger
15 from electrum.submarine_swaps import SwapManager, SwapData
16 from electrum.lnsweep import SweepInfo, sweep_ctx_anchor
17 from electrum.fee_policy import FeeTimeEstimates
18
19 from . import ElectrumTestCase
20 from .test_wallet_vertical import WalletIntegrityHelper, read_test_vector
21
22 WALLET_DATA = read_test_vector('cause_carbon_wallet.json')
23
24 class MockNetwork(Logger):
25
26 def __init__(self, config):
27 Logger.__init__(self)
28 self.config = config
29 self.fee_estimates = FeeTimeEstimates()
30 self.asyncio_loop = util.get_asyncio_loop()
31 self.interface = None
32 self.relay_fee = 1000
33 self.wallets = []
34 self._tx_queue = asyncio.Queue()
35 self.local_height = 42
36
37 def get_local_height(self):
38 return self.local_height
39
40 def blockchain(self):
41 class BlockchainMock:
42 def is_tip_stale(self):
43 return True
44 return BlockchainMock()
45
46 async def try_broadcasting(self, tx, name):
47 for w in self.wallets:
48 w.adb.receive_tx_callback(tx, tx_height=TX_HEIGHT_UNCONFIRMED)
49 self._tx_queue.put_nowait(tx)
50 return tx.txid()
51
52 async def next_tx(self):
53 tx = await util.wait_for2(self._tx_queue.get(), timeout=10)
54 return tx
55
56 def is_connected(self):
57 return True
58
59
60 SWAP_FUNDING_TX = "01000000000101500e9d67647481864edfb020b5c45e1c40d90f06b0130f9faed1a5149c6d26450000000000ffffffff0226080300000000002200205059c44bf57534303ab8f090f06b7bde58f5d2522440247a1ff6b41bdca9348df312c20100000000160014021d4f3b17921d790e1c022367a5bb078ce4deb402483045022100d41331089a2031396a1db8e4dec6dda9cacefe1288644b92f8e08a23325aa19b02204159230691601f7d726e4e6e0b7124d3377620f400d699a01095f0b0a09ee26a012102d60315c72c0cefd41c6d07883c20b88be3fc37aac7912f0052722a95de0de71600000000"
61 SWAP_CLAIM_TX = "02000000000101f9db8580febd5c0f85b6f1576c83f7739109e3a2d772743e3217e9537fea7e89000000000001000000017005030000000000160014b113a47f3718da3fd161339a6681c150fef2cfe30347304402204c6d40103589b1a8177a37a824f0c66a3a7b22bc570b14c9e07965b56f6ace8f02203a35cffe0ab10de00f3e15ecf5aafdd2c7f6c62da11edd9054a1bce7a9e1455c0120f1939b5723155713855d7ebea6e174f77d41d669269e7f138856c3de190e7a366a8201208763a914d7a62ef0270960fe23f0f351b28caadab62c21838821030bfd61153816df786036ea293edce851d3a4b9f4a1c66bdc1a17f00ffef3d6b167750334ef24b1752102fc8128f17f9e666ea281c702171ab16c1dd2a4337b71f08970f5aa10c608a93268ac00000000"
62
63 SWAPDATA = SwapData(
64 is_reverse=True,
65 locktime=2420532,
66 onchain_amount=198694,
67 lightning_amount=200000,
68 redeem_script=bytes.fromhex('8201208763a914d7a62ef0270960fe23f0f351b28caadab62c21838821030bfd61153816df786036ea293edce851d3a4b9f4a1c66bdc1a17f00ffef3d6b167750334ef24b1752102fc8128f17f9e666ea281c702171ab16c1dd2a4337b71f08970f5aa10c608a93268ac'),
69 preimage=bytes.fromhex('f1939b5723155713855d7ebea6e174f77d41d669269e7f138856c3de190e7a36'),
70 prepay_hash=None,
71 privkey=bytes.fromhex('58fd0018a9a2737d1d6b81d380df96bf0c858473a9592015508a270a7c9b1d8d'),
72 lockup_address='tb1q2pvugjl4w56rqw4c7zg0q6mmmev0t5jjy3qzg7sl766phh9fxjxsrtl77t',
73 claim_to_output=None,
74 funding_txid='897eea7f53e917323e7472d7a2e3099173f7836c57f1b6850f5cbdfe8085dbf9',
75 spending_txid=None,
76 is_redeemed=False,
77 )
78
79 txin = PartialTxInput(
80 prevout=TxOutpoint(txid=bytes.fromhex(SWAPDATA.funding_txid), out_idx=0),
81 )
82 txin._trusted_value_sats = SWAPDATA.onchain_amount
83 txin, locktime = SwapManager.create_claim_txin(txin=txin, swap=SWAPDATA)
84 SWAP_SWEEP_INFO = SweepInfo(
85 txin=txin,
86 cltv_abs=locktime,
87 txout=None,
88 name='swap claim',
89 can_be_batched=True,
90 dust_override=False,
91 )
92 anchor_chan_ctx = Transaction(
93 "02000000000101d24af3b7adefff5a068f736d64842c18da7087b41ba43ab5b999c545c5f1606501000000008d0d5d8"
94 "0024a010000000000002200207b95cb2555b3f8fc246d26ac38023ec8edf423d70b41dfe17efc89baa6e0cc72740003"
95 "000000000022002075f8af76a5b5c4b25e4aee3a4f96a190a168bde5d9761de8d45d3e49cd6f1d82040047304402200"
96 "6524eb2f467bf1eacd2116ea79a80c182eb95e18d0fa24fc5c600581ec4aa5f02206f50bdfc3577ca3bc9892eade7d8"
97 "1a9b06b9a8803296fad689af9fee9375191d0147304402202112d08ffa79010b1d698ca9fb0790119a42f7b70e183a2"
98 "a05dbf79c32806d3b022001cd3e3aec8c1142c8689e9e679c684ea82dcde8c86cf8e55466c743b3647b1f0147522103"
99 "0551e6017a0e9dbffd468c2a08ecf8446b532f0a6d5db291eb77026f2ef3deb421034f986fd43561d52a96b19fbdd0c"
100 "296f0442034d3f3f63fc394320a95750d42a852ae08572d20"
101 )
102 chan_multisig_key = lnutil.Keypair(
103 privkey="4c8b2c19d6528f54a4c900d87b3d8dbf746314925d126e0abf8e2ed965a9302f",
104 pubkey="034f986fd43561d52a96b19fbdd0c296f0442034d3f3f63fc394320a95750d42a8",
105 )
106 anchor_txin = sweep_ctx_anchor(ctx=anchor_chan_ctx, multisig_key=chan_multisig_key)
107 ANCHOR_SWEEP_INFO = SweepInfo(
108 name='local_anchor',
109 cltv_abs=None,
110 txin=anchor_txin,
111 txout=None,
112 can_be_batched=True,
113 dust_override=True,
114 )
115
116
117 class TestTxBatcher(ElectrumTestCase):
118
119 TESTNET = True
120
121 @classmethod
122 def setUpClass(cls):
123 super().setUpClass()
124 console_stderr_handler.setLevel(logging.DEBUG)
125
126 def setUp(self):
127 super().setUp()
128 self.config = SimpleConfig({'electrum_path': self.electrum_path})
129 self.config.FEE_POLICY = 'feerate:5000'
130
131 async def asyncSetUp(self):
132 await super().asyncSetUp()
133 self.network = MockNetwork(self.config)
134
135 def create_standard_wallet_from_seed(self, seed_words, *, config=None, gap_limit=2):
136 if config is None:
137 config = self.config
138 ks = keystore.from_seed(seed_words, passphrase='', for_multisig=False)
139 return WalletIntegrityHelper.create_standard_wallet(ks, gap_limit=gap_limit, config=config)
140
141 def _create_wallet(self):
142 wallet = self.create_standard_wallet_from_seed(WALLET_DATA["seed"])
143 wallet.start_network(self.network)
144 wallet.txbatcher.SLEEP_INTERVAL = 0.01
145 self.network.wallets.append(wallet)
146 return wallet
147
148 @mock.patch.object(wallet.Abstract_Wallet, 'save_db')
149 async def test_batch_payments(self, mock_save_db):
150 # output 1: tx1(o1) ---------------
151 # \
152 # output 2: tx1'(o1,o2) ----> tx2(tx1|o2)
153 #
154 # tx1 is broadcast, and replaced by tx1'
155 # tx1 gets mined
156 # txbatcher creates a new transaction tx2, child of tx1
157 #
158 OUTGOING_ADDRESS = 'tb1q7rl9cxr85962ztnsze089zs8ycv52hk43f3m9n'
159 wallet = self._create_wallet()
160 # fund wallet
161 funding_tx = Transaction(WALLET_DATA["funding_tx"])
162 await self.network.try_broadcasting(funding_tx, 'funding')
163 await self.network.next_tx()
164 assert wallet.adb.get_transaction(funding_tx.txid()) is not None
165 self.logger.info(f'wallet balance {wallet.get_balance()}')
166 # payment 1 -> tx1(output1)
167 output1 = PartialTxOutput.from_address_and_value(OUTGOING_ADDRESS, 10_000)
168 wallet.txbatcher.add_payment_output('default', output1)
169 tx1 = await self.network.next_tx()
170 assert output1 in tx1.outputs()
171 # payment 2 -> tx2(output1, output2)
172 output2 = PartialTxOutput.from_address_and_value(OUTGOING_ADDRESS, 20_000)
173 wallet.txbatcher.add_payment_output('default', output2)
174 tx1_prime = await self.network.next_tx()
175 assert wallet.adb.get_transaction(tx1_prime.txid()) is not None
176 assert len(tx1_prime.outputs()) == 3
177 assert output1 in tx1_prime.outputs()
178 assert output2 in tx1_prime.outputs()
179 # tx1 gets confirmed, tx2 gets removed
180 wallet.adb.receive_tx_callback(tx1, tx_height=1)
181 tx_mined_status = wallet.adb.get_tx_height(tx1.txid())
182 wallet.adb.add_verified_tx(tx1.txid(), dataclasses.replace(tx_mined_status, conf=1))
183 assert wallet.adb.get_transaction(tx1.txid()) is not None
184 assert wallet.adb.get_transaction(tx1_prime.txid()) is None
185 # txbatcher creates tx2
186 tx2 = await self.network.next_tx()
187 assert output1 in tx1.outputs()
188 assert output2 in tx2.outputs()
189 # check that tx2 is child of tx1
190 assert len(tx2.inputs()) == 1
191 assert tx2.inputs()[0].prevout.txid.hex() == tx1.txid()
192
193
194 @mock.patch.object(wallet.Abstract_Wallet, 'save_db')
195 async def test_rbf_batching__cannot_batch_as_would_need_to_use_ismine_outputs_of_basetx(self, mock_save_db):
196 """Wallet history contains unconf tx1 that spends all its coins to two ismine outputs,
197 one 'recv' address (20k sats) and one 'change' (80k sats).
198 The user tries to create tx2, that pays an invoice for 90k sats.
199 The tx batcher fails to batch, and should create a child transaction
200 """
201 wallet = self._create_wallet()
202 # fund wallet
203 funding_tx = Transaction(WALLET_DATA['funding_tx'])
204 await self.network.try_broadcasting(funding_tx, 'funding')
205 await self.network.next_tx()
206 assert wallet.adb.get_transaction(funding_tx.txid()) is not None
207 self.logger.info(f'wallet balance1 {wallet.get_balance()}')
208
209 # to_self_payment tx1
210 output1 = PartialTxOutput.from_address_and_value("tb1qyfnv3y866ufedugxxxfksyratv4pz3h78g9dad", 20_000)
211 wallet.txbatcher.add_payment_output('default', output1)
212 tx1 = await self.network.next_tx()
213 assert len(tx1.outputs()) == 2
214 assert output1 in tx1.outputs()
215
216 # outgoing payment tx2
217 output2 = PartialTxOutput.from_address_and_value("tb1qkfn0fude7z789uys2u7sf80kd4805zpvs3na0h", 90_000)
218 wallet.txbatcher.add_payment_output('default', output2)
219 # before tx1 gets confirmed, txbatch.create_transaction will raise notenoughfunds
220 await asyncio.sleep(wallet.txbatcher.SLEEP_INTERVAL)
221
222 # tx1 gets confirmed
223 wallet.adb.receive_tx_callback(tx1, tx_height=1)
224 tx_mined_status = wallet.adb.get_tx_height(tx1.txid())
225 wallet.adb.add_verified_tx(tx1.txid(), dataclasses.replace(tx_mined_status, conf=1))
226
227 tx2 = await self.network.next_tx()
228 assert len(tx2.outputs()) == 2
229 assert output2 in tx2.outputs()
230
231
232 @mock.patch.object(wallet.Abstract_Wallet, 'save_db')
233 async def test_sweep_from_submarine_swap(self, mock_save_db):
234 self.maxDiff = None
235 # create wallet
236 wallet = self._create_wallet()
237 wallet.adb.db.transactions[SWAPDATA.funding_txid] = tx = Transaction(SWAP_FUNDING_TX)
238 wallet.adb.receive_tx_callback(tx, tx_height=1)
239 tx_mined_status = wallet.adb.get_tx_height(tx.txid())
240 wallet.adb.add_verified_tx(tx.txid(), dataclasses.replace(tx_mined_status, conf=1))
241 wallet.txbatcher.add_sweep_input('default', SWAP_SWEEP_INFO)
242 tx = await self.network.next_tx()
243 txid = tx.txid()
244 self.assertEqual(SWAP_CLAIM_TX, str(tx))
245 # add a new payment, reusing the same input
246 # this tests that txin.make_witness() can be called more than once
247 output1 = PartialTxOutput.from_address_and_value("tb1qyfnv3y866ufedugxxxfksyratv4pz3h78g9dad", 20_000)
248 wallet.txbatcher.add_payment_output('default', output1)
249 new_tx = await self.network.next_tx()
250 # check that we batched with previous tx
251 assert new_tx.inputs()[0].prevout == tx.inputs()[0].prevout == txin.prevout
252 assert output1 in new_tx.outputs()
253
254 async def test_to_sweep_after_anchor_sweep_conditions(self):
255 # create wallet
256 wallet = self._create_wallet()
257 wallet.txbatcher.add_sweep_input('lnwatcher', ANCHOR_SWEEP_INFO)
258 anchor_batch = wallet.txbatcher.tx_batches['lnwatcher']
259
260 # does not return sweep info if prev_tx is not in db
261 to_sweep_no_tx = anchor_batch._to_sweep_after(tx=None)
262 self.assertFalse(to_sweep_no_tx)
263
264 # returns sweep input if anchor_chan_ctx conf < 1
265 wallet.adb.db.transactions[anchor_chan_ctx.txid()] = anchor_chan_ctx
266 to_sweep_no_conf = anchor_batch._to_sweep_after(tx=None)
267 self.assertEqual(to_sweep_no_conf[anchor_txin.prevout], ANCHOR_SWEEP_INFO)
268 self.assertEqual(len(to_sweep_no_conf), 1)
269
270 # does not return sweep input if ctx fee is already higher than target fee
271 with mock.patch.object(wallet.adb, 'get_tx_fee', return_value=2000), \
272 mock.patch.object(electrum.fee_policy.FeePolicy, 'estimate_fee', return_value=1000):
273 to_sweep_high_fee = anchor_batch._to_sweep_after(tx=None)
274 self.assertFalse(to_sweep_high_fee)
275
276 # after the ctx is confirmed the anchor claim shouldn't be broadcast anymore
277 wallet.adb.receive_tx_callback(anchor_chan_ctx, tx_height=1)
278 tx_mined_status = wallet.adb.get_tx_height(anchor_chan_ctx.txid())
279 wallet.adb.add_verified_tx(anchor_chan_ctx.txid(), dataclasses.replace(tx_mined_status, conf=1))
280 self.assertIn(anchor_txin.prevout, anchor_batch.batch_inputs)
281 to_sweep_ctx_conf = anchor_batch._to_sweep_after(tx=None)
282 self.assertFalse(to_sweep_ctx_conf)
283 self.assertFalse(anchor_batch.batch_inputs)
284 self.assertEqual(wallet.txbatcher.tx_batches['lnwatcher'], anchor_batch)
285
286 async def test_add_sweep_input_ignores_expired_sweep_info(self):
287 wallet = self._create_wallet()
288 wallet.adb.db.transactions[SWAPDATA.funding_txid] = Transaction(SWAP_FUNDING_TX)
289 sweep_info = SWAP_SWEEP_INFO._replace(expiry_height=self.network.local_height)
290 wallet.txbatcher.add_sweep_input('default', sweep_info)
291 self.assertFalse(wallet.txbatcher.tx_batches['default'].batch_inputs)
292
293 async def test_to_sweep_after_drops_expired_input(self):
294 wallet = self._create_wallet()
295 wallet.adb.db.transactions[SWAPDATA.funding_txid] = Transaction(SWAP_FUNDING_TX)
296 sweep_info = SWAP_SWEEP_INFO._replace(expiry_height=self.network.local_height + 1)
297 wallet.txbatcher.add_sweep_input('default', sweep_info)
298 batch = wallet.txbatcher.tx_batches['default']
299
300 # one block before the expiry height we still want to sweep
301 to_sweep = batch._to_sweep_after(tx=None)
302 self.assertEqual({sweep_info.txin.prevout: sweep_info}, to_sweep)
303
304 # at the expiry height we give up on the input
305 self.network.local_height = sweep_info.expiry_height
306 self.assertFalse(batch._to_sweep_after(tx=None))
307 self.assertFalse(batch.batch_inputs)
308
309 async def test_to_sweep_after_drops_expired_input_whose_prev_tx_is_missing(self):
310 """Giving up on an expired input must not depend on having its prev tx in the db,
311 otherwise the input lingers in batch_inputs forever."""
312 wallet = self._create_wallet()
313 sweep_info = SWAP_SWEEP_INFO._replace(expiry_height=self.network.local_height + 1)
314 wallet.txbatcher.add_sweep_input('default', sweep_info)
315 batch = wallet.txbatcher.tx_batches['default']
316 self.assertIn(sweep_info.txin.prevout, batch.batch_inputs)
317
318 self.network.local_height = sweep_info.expiry_height
319 self.assertFalse(batch._to_sweep_after(tx=None))
320 self.assertFalse(batch.batch_inputs)
321
322 async def test_add_sweep_input_works_again_after_expired_input_was_dropped(self):
323 """After we gave up on an expired input, the same prevout can be added to the
324 batch again, e.g. by _claim_swap re-adding a swap claim without expiry because
325 the preimage became public."""
326 wallet = self._create_wallet()
327 wallet.adb.db.transactions[SWAPDATA.funding_txid] = Transaction(SWAP_FUNDING_TX)
328 sweep_info = SWAP_SWEEP_INFO._replace(expiry_height=self.network.local_height + 1)
329 wallet.txbatcher.add_sweep_input('default', sweep_info)
330 batch = wallet.txbatcher.tx_batches['default']
331
332 # the input expires and is dropped
333 self.network.local_height = sweep_info.expiry_height
334 self.assertFalse(batch._to_sweep_after(tx=None))
335 self.assertFalse(batch.batch_inputs)
336
337 # the same prevout is added again, this time without expiry
338 wallet.txbatcher.add_sweep_input('default', SWAP_SWEEP_INFO)
339 self.assertIn(SWAP_SWEEP_INFO.txin.prevout, batch.batch_inputs)
340
341 @mock.patch.object(wallet.Abstract_Wallet, 'save_db')
342 async def test_to_sweep_after_keeps_expired_input_of_current_batch_tx(self, mock_save_db):
343 """We don't drop an expired sweep if the current batch tx already spends it"""
344 wallet = self._create_wallet()
345 wallet.adb.db.transactions[SWAPDATA.funding_txid] = tx = Transaction(SWAP_FUNDING_TX)
346 wallet.adb.receive_tx_callback(tx, tx_height=1)
347 tx_mined_status = wallet.adb.get_tx_height(tx.txid())
348 wallet.adb.add_verified_tx(tx.txid(), dataclasses.replace(tx_mined_status, conf=1))
349 sweep_info = SWAP_SWEEP_INFO._replace(expiry_height=self.network.local_height + 1)
350 wallet.txbatcher.add_sweep_input('default', sweep_info)
351 batch = wallet.txbatcher.tx_batches['default']
352 claim_tx = await self.network.next_tx()
353 self.assertEqual(sweep_info.txin.prevout, claim_tx.inputs()[0].prevout)
354
355 # the expiry height is reached while our tx is still unconfirmed
356 self.network.local_height = sweep_info.expiry_height
357 self.assertFalse(batch._to_sweep_after(claim_tx))
358 self.assertIn(sweep_info.txin.prevout, batch.batch_inputs)
359
360 # we can still create and sign a replacement of the tx that spends the input
361 output = PartialTxOutput.from_address_and_value("tb1qyfnv3y866ufedugxxxfksyratv4pz3h78g9dad", 20_000)
362 wallet.txbatcher.add_payment_output('default', output)
363 new_tx = await self.network.next_tx()
364 self.assertEqual(sweep_info.txin.prevout, new_tx.inputs()[0].prevout)
365 self.assertIn(output, new_tx.outputs())
366
367 async def _wait_for_base_tx(self, txbatch, should_be_none=False):
368 async with timeout_after(10):
369 while True:
370 base_tx = txbatch._base_tx
371 if (base_tx is not None) ^ should_be_none:
372 return base_tx
373 await asyncio.sleep(0.1)