Debian Codegraph @

tests/test_invoices.py

raw symbols SCIP
1 import os
2 import time
3
4 from electrum import util
5 from electrum.simple_config import SimpleConfig
6 from electrum.wallet import Standard_Wallet, Abstract_Wallet
7 from electrum.invoices import PR_UNPAID, PR_PAID, PR_UNCONFIRMED, PR_BROADCASTING, BaseInvoice, Invoice, LN_EXPIRY_NEVER
8 from electrum.address_synchronizer import TX_HEIGHT_UNCONFIRMED
9 from electrum.transaction import Transaction, PartialTxOutput
10 from electrum.util import TxMinedInfo, InvoiceError
11 from electrum.fee_policy import FixedFeePolicy
12
13 from . import ElectrumTestCase
14 from . import restore_wallet_from_text__for_unittest
15
16
17 class TestWalletPaymentRequests(ElectrumTestCase):
18 """test 'incoming' invoices"""
19 TESTNET = True
20
21 def setUp(self):
22 super().setUp()
23 self.config = SimpleConfig({'electrum_path': self.electrum_path})
24 self.wallet1_path = os.path.join(self.electrum_path, "somewallet1")
25 self.wallet2_path = os.path.join(self.electrum_path, "somewallet2")
26 self._orig_get_cur_time = BaseInvoice._get_cur_time
27
28 def tearDown(self):
29 super().tearDown()
30 BaseInvoice._get_cur_time = staticmethod(self._orig_get_cur_time)
31
32 def create_wallet2(self) -> Standard_Wallet:
33 text = 'cross end slow expose giraffe fuel track awake turtle capital ranch pulp'
34 d = restore_wallet_from_text__for_unittest(text, path=self.wallet2_path, config=self.config)
35 wallet2 = d['wallet'] # type: Standard_Wallet
36 # bootstrap wallet
37 funding_tx = Transaction('0200000000010132515e6aade1b79ec7dd3bac0896d8b32c56195d23d07d48e21659cef24301560100000000fdffffff0112841e000000000016001477fe6d2a27e8860c278d4d2cd90bad716bb9521a02473044022041ed68ef7ef122813ac6a5e996b8284f645c53fbe6823b8e430604a8915a867802203233f5f4d347a687eb19b2aa570829ab12aeeb29a24cc6d6d20b8b3d79e971ae012102bee0ee043817e50ac1bb31132770f7c41e35946ccdcb771750fb9696bdd1b307ad951d00')
38 funding_txid = funding_tx.txid()
39 assert 'db949963c3787c90a40fb689ffdc3146c27a9874a970d1fd20921afbe79a7aa9' == funding_txid
40 wallet2.adb.receive_tx_callback(funding_tx, tx_height=TX_HEIGHT_UNCONFIRMED)
41 return wallet2
42
43 async def test_wallet_with_ln_creates_payreq_and_gets_paid_on_ln(self):
44 text = 'bitter grass shiver impose acquire brush forget axis eager alone wine silver'
45 d = restore_wallet_from_text__for_unittest(text, path=self.wallet1_path, config=self.config)
46 wallet1 = d['wallet'] # type: Standard_Wallet
47 self.assertIsNotNone(wallet1.lnworker)
48 self.assertTrue(wallet1.has_lightning())
49 # create payreq
50 addr = wallet1.get_unused_address()
51 pr_key = wallet1.create_request(amount_sat=10000, message="msg", address=None, exp_delay=86400)
52 pr = wallet1.get_request(pr_key)
53 self.assertIsNotNone(pr)
54 self.assertTrue(pr.is_lightning())
55 self.assertEqual(PR_UNPAID, wallet1.get_invoice_status(pr))
56 # get paid on LN
57 wallet1.lnworker.set_request_status(bytes.fromhex(pr.rhash), PR_PAID)
58 self.assertEqual(PR_PAID, wallet1.get_invoice_status(pr))
59
60 async def test_wallet_with_ln_creates_payreq_and_gets_paid_onchain(self):
61 text = 'bitter grass shiver impose acquire brush forget axis eager alone wine silver'
62 d = restore_wallet_from_text__for_unittest(text, path=self.wallet1_path, config=self.config)
63 wallet1 = d['wallet'] # type: Standard_Wallet
64 wallet1.db.put('stored_height', 1000)
65 self.assertIsNotNone(wallet1.lnworker)
66 self.assertTrue(wallet1.has_lightning())
67 # create payreq
68 addr = wallet1.get_unused_address()
69 pr_key = wallet1.create_request(amount_sat=10000, message="msg", address=addr, exp_delay=86400)
70 pr = wallet1.get_request(pr_key)
71 self.assertIsNotNone(pr)
72 self.assertTrue(not pr.is_lightning())
73 self.assertEqual(PR_UNPAID, wallet1.get_invoice_status(pr))
74 self.assertEqual(1000, pr.height)
75 # get paid onchain
76 wallet2 = self.create_wallet2() # type: Standard_Wallet
77 outputs = [PartialTxOutput.from_address_and_value(pr.get_address(), pr.get_amount_sat())]
78 tx = wallet2.make_unsigned_transaction(outputs=outputs, fee_policy=FixedFeePolicy(5000))
79 wallet2.sign_transaction(tx, password=None)
80 wallet1.adb.receive_tx_callback(tx, tx_height=TX_HEIGHT_UNCONFIRMED)
81 self.assertEqual(PR_UNCONFIRMED, wallet1.get_invoice_status(pr))
82 # tx gets mined
83 wallet1.db.put('stored_height', 1010)
84 tx_info = TxMinedInfo(_height=1001,
85 timestamp=pr.get_time() + 100,
86 txpos=1,
87 header_hash="01"*32)
88 wallet1.adb.add_verified_tx(tx.txid(), tx_info)
89 self.assertEqual(PR_PAID, wallet1.get_invoice_status(pr))
90
91 async def test_wallet_without_ln_creates_payreq_and_gets_paid_onchain(self):
92 text = 'cycle rocket west magnet parrot shuffle foot correct salt library feed song'
93 d = restore_wallet_from_text__for_unittest(text, path=self.wallet1_path, config=self.config)
94 wallet1 = d['wallet'] # type: Standard_Wallet
95 wallet1.db.put('stored_height', 1000)
96 self.assertIsNone(wallet1.lnworker)
97 self.assertFalse(wallet1.has_lightning())
98 # create payreq
99 addr = wallet1.get_unused_address()
100 pr_key = wallet1.create_request(amount_sat=10000, message="msg", address=addr, exp_delay=86400)
101 pr = wallet1.get_request(pr_key)
102 self.assertIsNotNone(pr)
103 self.assertFalse(pr.is_lightning())
104 self.assertEqual(PR_UNPAID, wallet1.get_invoice_status(pr))
105 self.assertEqual(1000, pr.height)
106 # get paid onchain
107 wallet2 = self.create_wallet2() # type: Standard_Wallet
108 outputs = [PartialTxOutput.from_address_and_value(pr.get_address(), pr.get_amount_sat())]
109 tx = wallet2.make_unsigned_transaction(outputs=outputs, fee_policy=FixedFeePolicy(5000))
110 wallet2.sign_transaction(tx, password=None)
111 wallet1.adb.receive_tx_callback(tx, tx_height=TX_HEIGHT_UNCONFIRMED)
112 self.assertEqual(PR_UNCONFIRMED, wallet1.get_invoice_status(pr))
113 # tx gets mined
114 wallet1.db.put('stored_height', 1010)
115 tx_info = TxMinedInfo(_height=1001,
116 timestamp=pr.get_time() + 100,
117 txpos=1,
118 header_hash="01"*32)
119 wallet1.adb.add_verified_tx(tx.txid(), tx_info)
120 self.assertEqual(PR_PAID, wallet1.get_invoice_status(pr))
121
122 async def test_wallet_gets_paid_onchain_in_the_past(self):
123 text = 'bitter grass shiver impose acquire brush forget axis eager alone wine silver'
124 d = restore_wallet_from_text__for_unittest(text, path=self.wallet1_path, config=self.config)
125 wallet1 = d['wallet'] # type: Standard_Wallet
126 wallet1.db.put('stored_height', 1000)
127 self.assertIsNotNone(wallet1.lnworker)
128 self.assertTrue(wallet1.has_lightning())
129 # create payreq
130 addr = wallet1.get_unused_address()
131 pr_key = wallet1.create_request(amount_sat=10000, message="msg", address=addr, exp_delay=86400)
132 pr = wallet1.get_request(pr_key)
133 self.assertIsNotNone(pr)
134 self.assertTrue(not pr.is_lightning())
135 self.assertEqual(PR_UNPAID, wallet1.get_invoice_status(pr))
136 self.assertEqual(1000, pr.height)
137 # get paid onchain
138 wallet2 = self.create_wallet2() # type: Standard_Wallet
139 outputs = [PartialTxOutput.from_address_and_value(pr.get_address(), pr.get_amount_sat())]
140 tx = wallet2.make_unsigned_transaction(outputs=outputs, fee_policy=FixedFeePolicy(5000))
141 wallet2.sign_transaction(tx, password=None)
142 wallet1.adb.receive_tx_callback(tx, tx_height=TX_HEIGHT_UNCONFIRMED)
143 self.assertEqual(PR_UNCONFIRMED, wallet1.get_invoice_status(pr))
144 # tx mined in the past (before invoice creation)
145 tx_info = TxMinedInfo(_height=990,
146 timestamp=pr.get_time() + 100,
147 txpos=1,
148 header_hash="01" * 32)
149 wallet1.adb.add_verified_tx(tx.txid(), tx_info)
150 self.assertEqual(PR_UNPAID, wallet1.get_invoice_status(pr))
151
152 async def test_wallet_reuse_addr_of_expired_request(self):
153 text = 'bitter grass shiver impose acquire brush forget axis eager alone wine silver'
154 d = restore_wallet_from_text__for_unittest(text, path=self.wallet1_path, gap_limit=3, config=self.config)
155 wallet1 = d['wallet'] # type: Standard_Wallet
156 self.assertIsNotNone(wallet1.lnworker)
157 self.assertTrue(wallet1.has_lightning())
158 # create payreq1
159 addr1 = wallet1.get_unused_address()
160 pr1_key = wallet1.create_request(amount_sat=10000, message="msg", address=addr1, exp_delay=86400)
161 pr1 = wallet1.get_request(pr1_key)
162 self.assertTrue(not pr1.is_lightning())
163 self.assertEqual(PR_UNPAID, wallet1.get_invoice_status(pr1))
164 self.assertEqual(addr1, pr1.get_address())
165 self.assertFalse(pr1.has_expired())
166
167 BaseInvoice._get_cur_time = lambda *args: time.time() + 100_000
168 self.assertTrue(pr1.has_expired())
169
170 # create payreq2
171 addr2 = wallet1.get_unused_address()
172 self.assertEqual(addr1, addr2)
173 pr2_key = wallet1.create_request(amount_sat=10000, message="msg", address=addr2, exp_delay=86400)
174 pr2 = wallet1.get_request(pr2_key)
175 self.assertTrue(not pr2.is_lightning())
176 self.assertEqual(PR_UNPAID, wallet1.get_invoice_status(pr2))
177 self.assertEqual(addr2, pr2.get_address())
178 self.assertFalse(pr2.has_expired())
179
180 async def test_wallet_get_request_by_addr(self):
181 text = 'bitter grass shiver impose acquire brush forget axis eager alone wine silver'
182 d = restore_wallet_from_text__for_unittest(text, path=self.wallet1_path, gap_limit=3, config=self.config)
183 wallet1 = d['wallet'] # type: Standard_Wallet
184 self.assertIsNotNone(wallet1.lnworker)
185 self.assertTrue(wallet1.has_lightning())
186 # create payreq1
187 addr1 = wallet1.get_unused_address()
188 pr1_key = wallet1.create_request(amount_sat=10000, message="msg", address=addr1, exp_delay=86400)
189 pr1 = wallet1.get_request(pr1_key)
190 self.assertEqual(PR_UNPAID, wallet1.get_invoice_status(pr1))
191 self.assertFalse(pr1.has_expired())
192 self.assertEqual(pr1, wallet1.get_request_by_addr(addr1))
193
194 BaseInvoice._get_cur_time = lambda *args: time.time() + 100_000
195 self.assertTrue(pr1.has_expired())
196 self.assertEqual(None, wallet1.get_request_by_addr(addr1))
197
198 # create payreq2
199 addr2 = wallet1.get_unused_address()
200 self.assertEqual(addr1, addr2)
201 pr2_key = wallet1.create_request(amount_sat=10000, message="msg", address=addr2, exp_delay=86400)
202 pr2 = wallet1.get_request(pr2_key)
203 self.assertEqual(PR_UNPAID, wallet1.get_invoice_status(pr2))
204 self.assertFalse(pr2.has_expired())
205 self.assertEqual(pr2, wallet1.get_request_by_addr(addr1))
206
207 # pr2 gets paid onchain
208 wallet2 = self.create_wallet2() # type: Standard_Wallet
209 outputs = [PartialTxOutput.from_address_and_value(pr2.get_address(), pr2.get_amount_sat())]
210 tx = wallet2.make_unsigned_transaction(outputs=outputs, fee_policy=FixedFeePolicy(5000))
211 wallet2.sign_transaction(tx, password=None)
212 wallet1.adb.receive_tx_callback(tx, tx_height=TX_HEIGHT_UNCONFIRMED)
213 self.assertEqual(PR_UNCONFIRMED, wallet1.get_invoice_status(pr2))
214 self.assertEqual(pr2, wallet1.get_request_by_addr(addr1))
215
216 # FIXME the expired pr should stay "expired" - this might require storing state for it (see #8061):
217 self.assertEqual(PR_UNCONFIRMED, wallet1.get_invoice_status(pr1))
218
219 # now make both invoices be past their expiration date. pr2 should be unaffected.
220 BaseInvoice._get_cur_time = lambda *args: time.time() + 200_000
221 self.assertEqual(PR_UNCONFIRMED, wallet1.get_invoice_status(pr2))
222 self.assertEqual(pr2, wallet1.get_request_by_addr(addr1))
223
224
225 class TestBaseInvoice(ElectrumTestCase):
226 TESTNET = True
227
228 async def test_arg_validation(self):
229 amount_sat = 10_000
230 outputs = [PartialTxOutput.from_address_and_value("tb1qmjzmg8nd4z56ar4fpngzsr6euktrhnjg9td385", amount_sat)]
231 invoice = Invoice(
232 amount_msat=amount_sat * 1000,
233 message="mymsg",
234 time=1692716965,
235 exp=LN_EXPIRY_NEVER,
236 outputs=outputs,
237 height=0,
238 lightning_invoice=None,
239 )
240 with self.assertRaises(InvoiceError):
241 invoice.amount_msat = 10**20
242 with self.assertRaises(InvoiceError):
243 invoice.set_amount_msat(10**20)
244 with self.assertRaises(InvoiceError):
245 invoice2 = Invoice(
246 amount_msat=10**20,
247 message="mymsg",
248 time=1692716965,
249 exp=LN_EXPIRY_NEVER,
250 outputs=outputs,
251 height=0,
252 lightning_invoice=None,
253 )
254 with self.assertRaises(TypeError):
255 invoice.time = "asd"
256 with self.assertRaises(TypeError):
257 invoice.exp = "asd"
258
259
260 class TestOutgoingInvoicesPaidCache(ElectrumTestCase):
261 """test caching of paid-status for outgoing invoices"""
262 TESTNET = True
263
264 def setUp(self):
265 super().setUp()
266 self.config = SimpleConfig({'electrum_path': self.electrum_path})
267 self.wallet_path = os.path.join(self.electrum_path, "outgoing_inv_wallet")
268
269 def _make_wallet(self):
270 # Seed matches the funding tx output below (see TestWalletPaymentRequests.create_wallet2).
271 text = 'cross end slow expose giraffe fuel track awake turtle capital ranch pulp'
272 d = restore_wallet_from_text__for_unittest(text, path=self.wallet_path, config=self.config)
273 wallet = d['wallet'] # type: Standard_Wallet
274 funding_tx = Transaction('0200000000010132515e6aade1b79ec7dd3bac0896d8b32c56195d23d07d48e21659cef24301560100000000fdffffff0112841e000000000016001477fe6d2a27e8860c278d4d2cd90bad716bb9521a02473044022041ed68ef7ef122813ac6a5e996b8284f645c53fbe6823b8e430604a8915a867802203233f5f4d347a687eb19b2aa570829ab12aeeb29a24cc6d6d20b8b3d79e971ae012102bee0ee043817e50ac1bb31132770f7c41e35946ccdcb771750fb9696bdd1b307ad951d00')
275 wallet.adb.receive_tx_callback(funding_tx, tx_height=TX_HEIGHT_UNCONFIRMED)
276 return wallet
277
278 def _make_outgoing_invoice(self, dest_addr: str, amount_sat: int, *, t: int = 1700000000):
279 outputs = [PartialTxOutput.from_address_and_value(dest_addr, amount_sat)]
280 return Invoice(
281 amount_msat=amount_sat * 1000,
282 message="",
283 time=t,
284 exp=LN_EXPIRY_NEVER,
285 outputs=outputs,
286 height=0,
287 lightning_invoice=None,
288 )
289
290 async def test_paid_keys_empty_for_fresh_unpaid_invoice(self):
291 wallet = self._make_wallet()
292 inv = self._make_outgoing_invoice("tb1qmjzmg8nd4z56ar4fpngzsr6euktrhnjg9td385", 5_000)
293 wallet.save_invoice(inv, write_to_disk=False)
294 self.assertNotIn(inv.get_id(), wallet._paid_invoice_keys_cache)
295 self.assertEqual(PR_UNPAID, wallet.get_invoice_status(inv))
296 self.assertEqual([inv], wallet.get_unpaid_invoices())
297
298 async def test_paid_keys_populated_when_invoice_gets_paid(self):
299 wallet = self._make_wallet()
300 dest = "tb1qmjzmg8nd4z56ar4fpngzsr6euktrhnjg9td385"
301 amount_sat = 5_000
302 inv = self._make_outgoing_invoice(dest, amount_sat)
303 wallet.save_invoice(inv, write_to_disk=False)
304 # Pay the invoice with a confirmed outgoing tx so it becomes PR_PAID.
305 outputs = [PartialTxOutput.from_address_and_value(dest, amount_sat)]
306 tx = wallet.make_unsigned_transaction(outputs=outputs, fee_policy=FixedFeePolicy(1000))
307 wallet.sign_transaction(tx, password=None)
308 wallet.adb.receive_tx_callback(tx, tx_height=TX_HEIGHT_UNCONFIRMED)
309 wallet.db.put('stored_height', 1010)
310 wallet.adb.add_verified_tx(tx.txid(), TxMinedInfo(_height=1001, timestamp=1700000001, txpos=1, header_hash="01"*32))
311 self.assertEqual(PR_PAID, wallet.get_invoice_status(inv))
312 self.assertIn(inv.get_id(), wallet._paid_invoice_keys_cache)
313 self.assertEqual([], wallet.get_unpaid_invoices())
314
315 async def test_paid_keys_removed_on_delete_and_clear(self):
316 wallet = self._make_wallet()
317 inv = self._make_outgoing_invoice("tb1qmjzmg8nd4z56ar4fpngzsr6euktrhnjg9td385", 5_000)
318 wallet.save_invoice(inv, write_to_disk=False)
319 # Force into the cache via the internal hook so we don't depend on the slow path here.
320 wallet._paid_invoice_keys_cache.add(inv.get_id())
321 wallet.delete_invoice(inv.get_id(), write_to_disk=False)
322 self.assertNotIn(inv.get_id(), wallet._paid_invoice_keys_cache)
323 # Re-add and clear all
324 wallet.save_invoice(inv, write_to_disk=False)
325 wallet._paid_invoice_keys_cache.add(inv.get_id())
326 wallet.clear_invoices()
327 self.assertEqual(set(), wallet._paid_invoice_keys_cache)
328
329 async def test_get_invoice_status_short_circuits_on_cache_hit(self):
330 wallet = self._make_wallet()
331 inv = self._make_outgoing_invoice("tb1qmjzmg8nd4z56ar4fpngzsr6euktrhnjg9td385", 5_000)
332 wallet.save_invoice(inv, write_to_disk=False)
333 # Seed the cache and assert the slow path is not taken.
334 wallet._paid_invoice_keys_cache.add(inv.get_id())
335 called = []
336 orig = wallet._is_onchain_invoice_paid
337 def spy(invoice):
338 called.append(invoice.get_id())
339 return orig(invoice)
340 wallet._is_onchain_invoice_paid = spy
341 self.assertEqual(PR_PAID, wallet.get_invoice_status(inv))
342 self.assertEqual([], called, "cache hit must avoid _is_onchain_invoice_paid")
343
344 async def test_set_broadcasting_skips_already_paid_invoices(self):
345 wallet = self._make_wallet()
346 dest = "tb1qmjzmg8nd4z56ar4fpngzsr6euktrhnjg9td385"
347 # Two invoices share the same output scriptpubkey but only one is unpaid.
348 inv_paid = self._make_outgoing_invoice(dest, 5_000, t=1700000000)
349 inv_unpaid = self._make_outgoing_invoice(dest, 5_000, t=1700000005)
350 wallet.save_invoice(inv_paid, write_to_disk=False)
351 wallet.save_invoice(inv_unpaid, write_to_disk=False)
352 wallet._paid_invoice_keys_cache.add(inv_paid.get_id())
353
354 events = []
355 def on_status(w, key, status):
356 events.append((key, status))
357 util.register_callback(on_status, ['invoice_status'])
358 try:
359 # Build a tx whose output matches the shared scriptpubkey.
360 tx = wallet.make_unsigned_transaction(
361 outputs=[PartialTxOutput.from_address_and_value(dest, 5_000)],
362 fee_policy=FixedFeePolicy(1000),
363 )
364 wallet.set_broadcasting(tx, broadcasting_status=PR_BROADCASTING)
365 finally:
366 util.unregister_callback(on_status)
367
368 notified_keys = {key for key, _ in events}
369 self.assertIn(inv_unpaid.get_id(), notified_keys)
370 self.assertNotIn(inv_paid.get_id(), notified_keys,
371 "invoice_status callback should not fire for already-paid invoices")
372
373 async def test_set_broadcasting_does_not_rescan_paid_invoices_with_shared_outputs(self):
374 """Regression for the freeze scenario: many already-paid invoices share an
375 output scriptpubkey, so a new tx paying that scriptpubkey touches all of them.
376 set_broadcasting must not call _is_onchain_invoice_paid for the paid ones."""
377 wallet = self._make_wallet()
378 dest = "tb1qmjzmg8nd4z56ar4fpngzsr6euktrhnjg9td385"
379 # Many paid invoices, all sharing the same destination scriptpubkey.
380 paid_ids = set()
381 for i in range(50):
382 inv = self._make_outgoing_invoice(dest, 1_000 + i, t=1700000000 + i)
383 wallet.save_invoice(inv, write_to_disk=False)
384 paid_ids.add(inv.get_id())
385 wallet._paid_invoice_keys_cache.add(inv.get_id())
386 # One fresh unpaid invoice with the same destination.
387 unpaid = self._make_outgoing_invoice(dest, 9_999, t=1700001000)
388 wallet.save_invoice(unpaid, write_to_disk=False)
389
390 # Spy on the slow path.
391 called = []
392 orig = wallet._is_onchain_invoice_paid
393 def spy(invoice):
394 called.append(invoice.get_id())
395 return orig(invoice)
396 wallet._is_onchain_invoice_paid = spy
397
398 tx = wallet.make_unsigned_transaction(
399 outputs=[PartialTxOutput.from_address_and_value(dest, 1_000)],
400 fee_policy=FixedFeePolicy(1000),
401 )
402 wallet.set_broadcasting(tx, broadcasting_status=PR_BROADCASTING)
403
404 # The slow path may run for the unpaid invoice (via get_invoice_status),
405 # but must NOT run for any of the cached-paid ones.
406 called_set = set(called)
407 self.assertFalse(called_set & paid_ids,
408 f"slow path ran for paid invoices: {called_set & paid_ids}")
409
410 async def test_paid_keys_populated_on_wallet_load(self):
411 """After the initial _prepare_onchain_invoice_paid_detection pass, the cache
412 should reflect what _is_onchain_invoice_paid found, so that subsequent
413 get_invoice_status calls take the fast path."""
414 wallet = self._make_wallet()
415 dest = "tb1qmjzmg8nd4z56ar4fpngzsr6euktrhnjg9td385"
416 amount_sat = 5_000
417 inv = self._make_outgoing_invoice(dest, amount_sat)
418 wallet.save_invoice(inv, write_to_disk=False)
419 # Pay it (confirmed)
420 outputs = [PartialTxOutput.from_address_and_value(dest, amount_sat)]
421 tx = wallet.make_unsigned_transaction(outputs=outputs, fee_policy=FixedFeePolicy(1000))
422 wallet.sign_transaction(tx, password=None)
423 wallet.adb.receive_tx_callback(tx, tx_height=TX_HEIGHT_UNCONFIRMED)
424 wallet.db.put('stored_height', 1010)
425 wallet.adb.add_verified_tx(tx.txid(), TxMinedInfo(_height=1001, timestamp=1700000001, txpos=1, header_hash="01"*32))
426 # Force a rebuild of the cache as would happen at wallet load.
427 wallet._paid_invoice_keys_cache.clear()
428 wallet._prepare_onchain_invoice_paid_detection()
429 self.assertIn(inv.get_id(), wallet._paid_invoice_keys_cache)
430
431 async def test_paid_keys_demoted_on_reorg(self):
432 """A reorg unverifying the paying tx must remove the invoice from the cache,
433 otherwise get_invoice_status would keep returning a stale PR_PAID."""
434 wallet = self._make_wallet()
435 dest = "tb1qmjzmg8nd4z56ar4fpngzsr6euktrhnjg9td385"
436 amount_sat = 5_000
437 inv = self._make_outgoing_invoice(dest, amount_sat)
438 wallet.save_invoice(inv, write_to_disk=False)
439 # Pay and confirm.
440 outputs = [PartialTxOutput.from_address_and_value(dest, amount_sat)]
441 tx = wallet.make_unsigned_transaction(outputs=outputs, fee_policy=FixedFeePolicy(1000))
442 wallet.sign_transaction(tx, password=None)
443 wallet.adb.receive_tx_callback(tx, tx_height=TX_HEIGHT_UNCONFIRMED)
444 wallet.db.put('stored_height', 1010)
445 wallet.adb.add_verified_tx(tx.txid(), TxMinedInfo(_height=1001, timestamp=1700000001, txpos=1, header_hash="01"*32))
446 self.assertEqual(PR_PAID, wallet.get_invoice_status(inv))
447 self.assertIn(inv.get_id(), wallet._paid_invoice_keys_cache)
448 # Simulate reorg: unverify the tx and fire the same event the verifier would.
449 wallet.adb.db.remove_verified_tx(tx.txid())
450 util.trigger_callback('adb_removed_verified_tx', wallet.adb, tx.txid())
451 self.assertNotIn(inv.get_id(), wallet._paid_invoice_keys_cache)
452 self.assertNotEqual(PR_PAID, wallet.get_invoice_status(inv))
453
454 async def test_clear_history_resets_paid_keys(self):
455 """clear_history() wipes _prevouts_by_scripthash; the cache must follow,
456 otherwise get_invoice_status would keep returning a stale PR_PAID."""
457 wallet = self._make_wallet()
458 dest = "tb1qmjzmg8nd4z56ar4fpngzsr6euktrhnjg9td385"
459 amount_sat = 5_000
460 inv = self._make_outgoing_invoice(dest, amount_sat)
461 wallet.save_invoice(inv, write_to_disk=False)
462 # Pay and confirm.
463 outputs = [PartialTxOutput.from_address_and_value(dest, amount_sat)]
464 tx = wallet.make_unsigned_transaction(outputs=outputs, fee_policy=FixedFeePolicy(1000))
465 wallet.sign_transaction(tx, password=None)
466 wallet.adb.receive_tx_callback(tx, tx_height=TX_HEIGHT_UNCONFIRMED)
467 wallet.db.put('stored_height', 1010)
468 wallet.adb.add_verified_tx(tx.txid(), TxMinedInfo(_height=1001, timestamp=1700000001, txpos=1, header_hash="01"*32))
469 self.assertIn(inv.get_id(), wallet._paid_invoice_keys_cache)
470 # Wipe history.
471 wallet.clear_history()
472 self.assertNotIn(inv.get_id(), wallet._paid_invoice_keys_cache)
473 self.assertNotEqual(PR_PAID, wallet.get_invoice_status(inv))