Debian Codegraph @

tests/test_lnpeer.py

raw symbols SCIP
1 import asyncio
2 import dataclasses
3 import shutil
4 import copy
5 import tempfile
6 import os
7 from contextlib import contextmanager
8 from collections import defaultdict
9 import logging
10 import concurrent
11 from concurrent import futures
12 from functools import lru_cache
13 from unittest import mock
14 from typing import Iterable, NamedTuple, Tuple, List, Dict, Sequence, Mapping
15 from types import MappingProxyType
16 import time
17 import statistics
18
19 from aiorpcx import timeout_after, TaskTimeout
20 from electrum_ecc import ECPrivkey
21 import electrum_ecc as ecc
22
23 import electrum
24 import electrum.trampoline
25 from electrum import bitcoin
26 from electrum import util
27 from electrum import constants
28 from electrum import bip32
29 from electrum.network import Network, ProxySettings
30 from electrum import simple_config, lnutil
31 from electrum.bolt11 import encode_bolt11_invoice, BOLT11Addr
32 from electrum.bitcoin import sha256
33 from electrum.transaction import Transaction
34 from electrum.util import NetworkRetryManager, bfh, OldTaskGroup, EventListener, InvoiceError
35 from electrum.lnpeer import Peer
36 from electrum.lntransport import LNPeerAddr
37 from electrum.crypto import privkey_to_pubkey
38 from electrum.lnutil import Keypair, PaymentFailure, LnFeatures, HTLCOwner, PaymentFeeBudget, RECEIVED
39 from electrum.lnchannel import ChannelState, PeerState, Channel
40 from electrum.lnrouter import LNPathFinder, PathEdge, LNPathInconsistent
41 from electrum.channel_db import ChannelDB, InvalidGossipMsg
42 from electrum.lnworker import LNWallet, NoPathFound, SentHtlcInfo, PaySession, LNPeerManager
43 from electrum.lnmsg import encode_msg, decode_msg
44 from electrum import lnmsg
45 from electrum.logging import console_stderr_handler, Logger
46 from electrum.lnonion import OnionFailureCode, OnionRoutingFailure, OnionHopsDataSingle, OnionPacket
47 from electrum.lnutil import LOCAL, REMOTE, UpdateAddHtlc, RecvMPPResolution, RevocationStore
48 from electrum.invoices import PR_PAID, PR_UNPAID, Invoice
49 from electrum.interface import GracefulDisconnect
50 from electrum.fee_policy import FeeTimeEstimates, FEE_ETA_TARGETS
51 from electrum.mpp_split import split_amount_normal
52 from electrum.wallet import Abstract_Wallet, Standard_Wallet
53
54 from .test_bitcoin import needs_test_with_all_chacha20_implementations
55 from . import ElectrumTestCase, restore_wallet_from_text__for_unittest, lnhelpers
56 from .lnhelpers import Graph, MockLNWallet, create_test_channels, low_fee_channel, depleted_channel
57
58
59 class PaymentDone(Exception): pass
60 class PaymentTimeout(Exception): pass
61 class SuccessfulTest(Exception): pass
62
63
64 def inject_chan_into_gossipdb(
65 *,
66 channel_db: ChannelDB,
67 chanAB: Channel,
68 chanBA: Channel,
69 ) -> None:
70 assert chanAB.channel_id == chanBA.channel_id
71 print(f"injecting channel {chanAB.name} into channel_db")
72 chan_ann_raw = chanAB.construct_channel_announcement_without_sigs()[0]
73 chan_ann_dict = decode_msg(chan_ann_raw)[1]
74 channel_db.add_channel_announcements(chan_ann_dict, trusted=True)
75
76 chan_upd1_raw = chanAB.get_outgoing_gossip_channel_update()
77 chan_upd1_dict = decode_msg(chan_upd1_raw)[1]
78 channel_db.add_channel_update(chan_upd1_dict, verify=False)
79
80 chan_upd2_raw = chanBA.get_outgoing_gossip_channel_update()
81 chan_upd2_dict = decode_msg(chan_upd2_raw)[1]
82 channel_db.add_channel_update(chan_upd2_dict, verify=False)
83
84
85 class TestPeer(ElectrumTestCase):
86 TESTNET = True
87
88 @classmethod
89 def setUpClass(cls):
90 super().setUpClass()
91 console_stderr_handler.setLevel(logging.DEBUG)
92
93 def setUp(self):
94 super().setUp()
95 self.GRAPH_DEFINITIONS = copy.deepcopy(lnhelpers._GRAPH_DEFINITIONS)
96
97 async def asyncTearDown(self):
98 electrum.trampoline._TRAMPOLINE_NODES_UNITTESTS = {}
99 await super().asyncTearDown()
100
101 prepare_invoice = staticmethod(lnhelpers.prepare_invoice)
102
103 async def _activate_trampoline(self, w: MockLNWallet):
104 if w.network.channel_db:
105 w.network.channel_db.stop()
106 await w.network.channel_db.stopped_event.wait()
107 w.network.channel_db = None
108
109 def prepare_recipient(self, w2, payment_hash, test_hold_invoice, test_failure):
110 if not test_hold_invoice and not test_failure:
111 return
112 preimage_hex, is_public = w2._preimages.pop(payment_hash.hex())
113 preimage = bytes.fromhex(preimage_hex)
114 if test_hold_invoice:
115 async def cb(payment_hash):
116 if not test_failure:
117 w2.save_preimage(payment_hash, preimage, mark_as_public=is_public)
118 else:
119 raise OnionRoutingFailure(code=OnionFailureCode.INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS, data=b'')
120 w2.register_hold_invoice(payment_hash, cb)
121
122 def prepare_lnwallets(self, graph_definition) -> Mapping[str, MockLNWallet]:
123 return lnhelpers.prepare_lnwallets(self, graph_definition)
124
125 def prepare_chans_and_peers_in_graph(self, *args, **kwargs):
126 return lnhelpers.prepare_chans_and_peers_in_graph(self, *args, **kwargs)
127
128
129 class TestPeerUtils(TestPeer):
130
131 def test_decode_short_ids(self):
132 """
133 Test Peer.decode_short_ids() against some data from
134 https://github.com/lightning/bolts/commit/313c0f290eb87e96dc8195cad0c891418a826c2c
135 """
136 # Test uncompressed encoding with three scids
137 encoded_uncompressed = bytes.fromhex("00" + "0000000000003043" + "00000000000778d6" + "000000000046e1c1")
138 result = Peer.decode_short_ids(encoded_uncompressed)
139 self.assertEqual(len(result), 3)
140 self.assertEqual(result[0], bytes.fromhex("0000000000003043")) # 0x0x12355
141 self.assertEqual(result[1], bytes.fromhex("00000000000778d6")) # 0x7x30934
142 self.assertEqual(result[2], bytes.fromhex("000000000046e1c1")) # 0x70x57793
143
144 # Test empty list
145 encoded_empty = bytes.fromhex("00")
146 result = Peer.decode_short_ids(encoded_empty)
147 self.assertEqual(result, [])
148
149 # Test single scid
150 encoded_single = bytes.fromhex("00" + "000000000000008e") # 0x0x142
151 result = Peer.decode_short_ids(encoded_single)
152 self.assertEqual(len(result), 1)
153 self.assertEqual(result[0], bytes.fromhex("000000000000008e"))
154
155 # test invalid size raises exception
156 encoded_invalid = bytes.fromhex("00" + "00" * 9)
157 with self.assertRaises(Exception) as ctx:
158 Peer.decode_short_ids(encoded_invalid)
159 self.assertIn("invalid size", str(ctx.exception))
160
161 # Test unsupported encoding raises exception (considering it even passes the length check)
162 encoded_unsupported = bytes.fromhex("01" + "00" * 8) # 01 was zlib before removed
163 with self.assertRaises(Exception) as ctx:
164 Peer.decode_short_ids(encoded_unsupported)
165 self.assertIn("unexpected first byte", str(ctx.exception))
166
167 async def test_maybe_save_remote_update(self):
168 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['single_chan'])
169 alice_bob_peer, bob_alice_peer = graph.peers[('alice', 'bob')], graph.peers[('bob', 'alice')]
170 alice_bob_chan, bob_alice_chan = graph.channels[('alice', 'bob')][0], graph.channels[('bob', 'alice')][0]
171
172 # prepare channel update from alice
173 alice_to_bob_chan_update = alice_bob_chan.get_outgoing_gossip_channel_update()
174 raw = alice_to_bob_chan_update
175 payload = decode_msg(alice_to_bob_chan_update)[1]
176 payload['raw'] = raw
177
178 # bob should accept the update and save it
179 self.assertIsNone(bob_alice_chan.storage.get('remote_update'))
180 bob_alice_peer.maybe_save_remote_update(payload)
181 self.assertEqual(bob_alice_chan.storage.get('remote_update'), raw.hex())
182
183 # alice shouldn't save her own channel update as remote update
184 self.assertIsNone(alice_bob_chan.storage.get('remote_update'))
185 alice_bob_peer.maybe_save_remote_update(payload)
186 self.assertIsNone(alice_bob_chan.storage.get('remote_update'))
187
188 ChannelDB.verify_channel_update(payload, start_node=bob_alice_peer.pubkey)
189 # trying to verify the sig against the wrong pubkey should fail obviously
190 with self.assertRaises(InvalidGossipMsg):
191 ChannelDB.verify_channel_update(payload, start_node=alice_bob_peer.pubkey)
192
193 async def test_zeroconf_feature_bit(self):
194 workers = self.prepare_lnwallets(self.GRAPH_DEFINITIONS['single_chan'])
195
196 with self.subTest(msg="zeroconf is disabled in Alice LNWallet, so peers shouldn't signal it either"):
197 graph = self.prepare_chans_and_peers_in_graph(
198 self.GRAPH_DEFINITIONS['single_chan'],
199 workers=workers,
200 )
201 alice, _ = graph.peers.values()
202 self.assertFalse(alice.features.supports(LnFeatures.OPTION_ZEROCONF_OPT))
203
204 # enable zeroconf in alice LNWallet
205 workers['alice'].features |= LnFeatures.OPTION_ZEROCONF_OPT
206
207 with self.subTest(msg="no trusted zeroconf node, zeroconf should be signaled in new peers"):
208 graph = self.prepare_chans_and_peers_in_graph(
209 self.GRAPH_DEFINITIONS['single_chan'],
210 workers=workers,
211 )
212 alice, _ = graph.peers.values() # alice is LSP
213 self.assertTrue(alice.features.supports(LnFeatures.OPTION_ZEROCONF_OPT))
214
215 with self.subTest(msg="trusted node is configured, but it is not bob"):
216 workers['alice'].config.ZEROCONF_TRUSTED_NODE = f"{os.urandom(33).hex()}@1.1.1.1:9735"
217 graph = self.prepare_chans_and_peers_in_graph(
218 self.GRAPH_DEFINITIONS['single_chan'],
219 workers=workers,
220 )
221 alice, _ = graph.peers.values() # alice is client
222 self.assertFalse(alice.features.supports(LnFeatures.OPTION_ZEROCONF_OPT))
223
224 with self.subTest(msg="trusted node is configured, but it is invalid"):
225 workers['alice'].config.ZEROCONF_TRUSTED_NODE = f"{os.urandom(8).hex()}@1.1.1.1:9735"
226 graph = self.prepare_chans_and_peers_in_graph(
227 self.GRAPH_DEFINITIONS['single_chan'],
228 workers=workers,
229 )
230 alice, _ = graph.peers.values() # alice is client
231 self.assertFalse(alice.features.supports(LnFeatures.OPTION_ZEROCONF_OPT))
232
233 with self.subTest(msg="Alice uses Bob as her trusted LSP"):
234 workers['alice'].config.ZEROCONF_TRUSTED_NODE = workers['bob'].node_keypair.pubkey.hex()
235 graph = self.prepare_chans_and_peers_in_graph(
236 self.GRAPH_DEFINITIONS['single_chan'],
237 workers=workers,
238 )
239 alice, _ = graph.peers.values()
240 self.assertTrue(alice.features.supports(LnFeatures.OPTION_ZEROCONF_OPT))
241
242
243 class TestPeerDirect(TestPeer):
244
245 def prepare_peers(
246 self, alice_channel: Channel, bob_channel: Channel,
247 ):
248 graph = self.prepare_chans_and_peers_in_graph(
249 self.GRAPH_DEFINITIONS['single_chan'],
250 channels={('alice', 'bob'): [alice_channel], ('bob', 'alice'): [bob_channel]},
251 )
252 p1, p2 = graph.peers.values()
253 w1, w2 = graph.workers.values()
254 return p1, p2, w1, w2
255
256 async def test_reestablish_happycase(self):
257 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['single_chan'])
258 p1, p2 = graph.peers.values()
259 alice_channel = graph.channels[('alice', 'bob')][0]
260 bob_channel = graph.channels[('bob', 'alice')][0]
261
262 for chan in (alice_channel, bob_channel):
263 chan.peer_state = PeerState.DISCONNECTED
264 async def reestablish():
265 await asyncio.gather(
266 p1.reestablish_channel(alice_channel),
267 p2.reestablish_channel(bob_channel))
268 self.assertEqual(alice_channel.peer_state, PeerState.GOOD)
269 self.assertEqual(bob_channel.peer_state, PeerState.GOOD)
270 self.assertEqual((alice_channel._state, bob_channel._state), (ChannelState.OPEN, ChannelState.OPEN))
271 gath.cancel()
272 gath = asyncio.gather(reestablish(), p1._message_loop(), p2._message_loop(), p1.htlc_switch(), p2.htlc_switch())
273 with self.assertRaises(asyncio.CancelledError):
274 await gath
275
276 async def test_reestablish_with_old_state(self):
277 async def f(alice_slow: bool, bob_slow: bool):
278 random_seed = os.urandom(32)
279 alice_lnwallet, bob_lnwallet = self.prepare_lnwallets(self.GRAPH_DEFINITIONS['single_chan']).values()
280 alice_channel, bob_channel = create_test_channels(random_seed=random_seed, alice_lnwallet=alice_lnwallet, bob_lnwallet=bob_lnwallet)
281 alice_channel_0, bob_channel_0 = create_test_channels(random_seed=random_seed, alice_lnwallet=alice_lnwallet, bob_lnwallet=bob_lnwallet) # these are identical
282 p1, p2, w1, w2 = self.prepare_peers(alice_channel, bob_channel)
283 lnaddr, pay_req = self.prepare_invoice(w2)
284 async def pay():
285 result, log = await w1.pay_invoice(pay_req)
286 self.assertEqual(result, True)
287 gath.cancel()
288 gath = asyncio.gather(pay(), p1._message_loop(), p2._message_loop(), p1.htlc_switch(), p2.htlc_switch())
289 with self.assertRaises(asyncio.CancelledError):
290 await gath
291 p1, p2, w1, w2 = self.prepare_peers(alice_channel_0, bob_channel)
292 for chan in (alice_channel_0, bob_channel):
293 chan.peer_state = PeerState.DISCONNECTED
294
295 async def alice_sends_reest():
296 if alice_slow: await asyncio.sleep(0.05)
297 await p1.reestablish_channel(alice_channel_0)
298 async def bob_sends_reest():
299 if bob_slow: await asyncio.sleep(0.05)
300 await p2.reestablish_channel(bob_channel)
301
302 with self.assertRaises(GracefulDisconnect):
303 async with OldTaskGroup() as group:
304 await group.spawn(p1._message_loop())
305 await group.spawn(p1.htlc_switch())
306 await group.spawn(p2._message_loop())
307 await group.spawn(p2.htlc_switch())
308 await group.spawn(alice_sends_reest)
309 await group.spawn(bob_sends_reest)
310 self.assertEqual(alice_channel_0.peer_state, PeerState.BAD)
311 self.assertEqual(alice_channel_0._state, ChannelState.WE_ARE_TOXIC)
312 self.assertEqual(bob_channel._state, ChannelState.FORCE_CLOSING)
313
314 with self.subTest(msg="both fast"):
315 # FIXME: we want to test the case where both Alice and Bob sends channel-reestablish before
316 # receiving what the other sent. This is not a reliable way to do that...
317 await f(alice_slow=False, bob_slow=False)
318 with self.subTest(msg="alice is slow"):
319 await f(alice_slow=True, bob_slow=False)
320 with self.subTest(msg="bob is slow"):
321 await f(alice_slow=False, bob_slow=True)
322
323 async def test_reestablish_fake_data(self):
324 async def f(
325 alice_slow: bool,
326 bob_slow: bool,
327 *,
328 ctn_delta: int = 0,
329 revnum_delta: int = 0,
330 last_rev_secret: bytes = None,
331 ) -> tuple[Channel, Channel]:
332 alice_lnwallet, bob_lnwallet = self.prepare_lnwallets(self.GRAPH_DEFINITIONS['single_chan']).values()
333 alice_channel, bob_channel = create_test_channels(alice_lnwallet=alice_lnwallet, bob_lnwallet=bob_lnwallet)
334 p1, p2, w1, w2 = self.prepare_peers(alice_channel, bob_channel)
335 # first make some payments, to bump the channel ctns a bit
336 async def pay():
337 for pnum in range(2):
338 lnaddr, pay_req = self.prepare_invoice(w2)
339 result, log = await w1.pay_invoice(pay_req)
340 self.assertEqual(result, True)
341 gath.cancel()
342 gath = asyncio.gather(pay(), p1._message_loop(), p2._message_loop(), p1.htlc_switch(), p2.htlc_switch())
343 with self.assertRaises(asyncio.CancelledError):
344 await gath
345 for chan in (alice_channel, bob_channel):
346 chan.peer_state = PeerState.DISCONNECTED
347
348 # now reestablish the channel
349 async def alice_sends_reest():
350 nonlocal last_rev_secret
351 if alice_slow: await asyncio.sleep(0.05)
352 chan = alice_channel
353 next_local_ctn = chan.get_next_ctn(LOCAL) + ctn_delta
354 assert next_local_ctn >= 0, next_local_ctn
355 oldest_unrevoked_remote_ctn = chan.get_oldest_unrevoked_ctn(REMOTE) + revnum_delta
356 assert oldest_unrevoked_remote_ctn >= 0, oldest_unrevoked_remote_ctn
357 if last_rev_secret is None:
358 revnum_for_secret = oldest_unrevoked_remote_ctn % (2**48)
359 if revnum_delta <= 0:
360 last_rev_secret = chan.revocation_store.retrieve_secret(RevocationStore.START_INDEX - revnum_for_secret + 1)
361 else: # Alice is using *magic* here, i.e. cheating: she uses Bob's channel to learn future unrevealed secrets
362 last_rev_secret, _point = bob_channel.get_secret_and_point(LOCAL, revnum_for_secret - 1)
363 p1.send_message(
364 "channel_reestablish",
365 channel_id=chan.channel_id,
366 next_commitment_number=next_local_ctn,
367 next_revocation_number=oldest_unrevoked_remote_ctn,
368 your_last_per_commitment_secret=last_rev_secret,
369 my_current_per_commitment_point=ecc.GENERATOR.get_public_key_bytes(compressed=True),
370 )
371 async def bob_sends_reest():
372 if bob_slow: await asyncio.sleep(0.05)
373 await p2.reestablish_channel(bob_channel)
374
375 async def exit_after_bob_receives_reest():
376 await p2.channel_reestablish_msg[bob_channel.channel_id]
377
378 with self.assertRaises((GracefulDisconnect, lnutil.RemoteMisbehaving)):
379 async with OldTaskGroup() as group:
380 await group.spawn(p1._message_loop())
381 await group.spawn(p1.htlc_switch())
382 await group.spawn(p2._message_loop())
383 await group.spawn(p2.htlc_switch())
384 await p1.initialized
385 await p2.initialized
386 await group.spawn(alice_sends_reest)
387 await group.spawn(bob_sends_reest)
388 await group.spawn(exit_after_bob_receives_reest)
389 return alice_channel, bob_channel
390
391 cs = ChannelState
392 for (alice_slow, bob_slow) in (
393 (False, False), # both fast: FIXME: we want to test the case where both Alice and Bob sends channel-reestablish before
394 # receiving what the other sent. This is not a reliable way to do that...
395 (True, False),
396 (False, True),
397 ):
398 kwargs = {"alice_slow": alice_slow, "bob_slow": bob_slow}
399 # note: Alice's channel state will stay OPEN in every case:
400 # she is intentionally sending weird data that does not reflect her true state.
401 with self.subTest(msg="next_local_ctn from past", **kwargs):
402 a_chan, b_chan = await f(ctn_delta=-2, **kwargs)
403 self.assertEqual((a_chan._state, b_chan._state), (cs.OPEN, cs.FORCE_CLOSING))
404 with self.subTest(msg="next_local_ctn from future", **kwargs):
405 a_chan, b_chan = await f(ctn_delta=1000, **kwargs)
406 self.assertEqual((a_chan._state, b_chan._state), (cs.OPEN, cs.FORCE_CLOSING))
407 with self.subTest(msg="oldest_unrevoked_remote_ctn from past", **kwargs):
408 a_chan, b_chan = await f(revnum_delta=-2, **kwargs)
409 self.assertEqual((a_chan._state, b_chan._state), (cs.OPEN, cs.FORCE_CLOSING))
410 with self.subTest(msg="oldest_unrevoked_remote_ctn from future", **kwargs):
411 a_chan, b_chan = await f(revnum_delta=1000, **kwargs)
412 self.assertEqual((a_chan._state, b_chan._state), (cs.OPEN, cs.WE_ARE_TOXIC))
413 with self.subTest(msg="invalid last_rev_secret", **kwargs):
414 a_chan, b_chan = await f(last_rev_secret=sha256("fake_data"), **kwargs)
415 self.assertEqual((a_chan._state, b_chan._state), (cs.OPEN, cs.FORCE_CLOSING))
416 with self.subTest(msg="overflow of next_local_ctn", **kwargs):
417 with self.assertLogs('electrum', level='INFO') as logs:
418 a_chan, b_chan = await f(ctn_delta=2**48, **kwargs)
419 self.assertEqual((a_chan._state, b_chan._state), (cs.OPEN, cs.FORCE_CLOSING))
420 self.assertTrue(any(("bob->alice" in msg and "channel_reestablish" in msg and "ctn overflow" in msg)
421 for msg in logs.output))
422 with self.subTest(msg="overflow of oldest_unrevoked_remote_ctn", **kwargs):
423 with self.assertLogs('electrum', level='INFO') as logs:
424 a_chan, b_chan = await f(revnum_delta=2**48, **kwargs)
425 self.assertEqual((a_chan._state, b_chan._state), (cs.OPEN, cs.FORCE_CLOSING))
426 self.assertTrue(any(("bob->alice" in msg and "channel_reestablish" in msg and "ctn overflow" in msg)
427 for msg in logs.output))
428
429 @staticmethod
430 def _send_fake_htlc(peer: Peer, chan: Channel) -> UpdateAddHtlc:
431 htlc = UpdateAddHtlc(amount_msat=10000, payment_hash=os.urandom(32), cltv_abs=999, timestamp=1)
432 htlc = chan.add_htlc(htlc)
433 peer.send_message(
434 "update_add_htlc",
435 channel_id=chan.channel_id,
436 id=htlc.htlc_id,
437 cltv_expiry=htlc.cltv_abs,
438 amount_msat=htlc.amount_msat,
439 payment_hash=htlc.payment_hash,
440 onion_routing_packet=1366 * b"0",
441 )
442 return htlc
443
444 async def _test_reestablish_replay_messages(self, rev_then_sig: bool):
445 alice_lnwallet, bob_lnwallet = self.prepare_lnwallets(self.GRAPH_DEFINITIONS['single_chan']).values()
446 chan_AB, chan_BA = create_test_channels(alice_lnwallet=alice_lnwallet, bob_lnwallet=bob_lnwallet)
447 # note: we don't start peer.htlc_switch() so that the fake htlcs are left alone.
448 async def f():
449 p1, p2, w1, w2 = self.prepare_peers(chan_AB, chan_BA)
450 p1.MIN_TIME_BETWEEN_SENDING_COMMITSIGS = 0
451 p2.MIN_TIME_BETWEEN_SENDING_COMMITSIGS = 0
452 async with OldTaskGroup() as group:
453 await group.spawn(p1._message_loop())
454 await group.spawn(p2._message_loop())
455 await p1.initialized
456 await p2.initialized
457 self._send_fake_htlc(p2, chan_BA)
458 self._send_fake_htlc(p1, chan_AB)
459 p2.transport.queue.put_nowait(asyncio.Event()) # break Bob's incoming pipe
460 if rev_then_sig:
461 self.assertTrue(p2.maybe_send_commitment(chan_BA))
462 await p1.received_commitsig_event.wait()
463 else:
464 self.assertTrue(p1.maybe_send_commitment(chan_AB))
465 self.assertTrue(p2.maybe_send_commitment(chan_BA))
466 await p1.received_commitsig_event.wait()
467 await group.cancel_remaining()
468 # simulating disconnection. recreate transports.
469 self.logger.info("simulating disconnection. recreating transports.")
470 p1, p2, w1, w2 = self.prepare_peers(chan_AB, chan_BA)
471 p1.MIN_TIME_BETWEEN_SENDING_COMMITSIGS = 0
472 p2.MIN_TIME_BETWEEN_SENDING_COMMITSIGS = 0
473 for chan in (chan_AB, chan_BA):
474 chan.peer_state = PeerState.DISCONNECTED
475 async with OldTaskGroup() as group:
476 await group.spawn(p1._message_loop())
477 await group.spawn(p2._message_loop())
478 with self.assertLogs('electrum', level='INFO') as logs:
479 async with OldTaskGroup() as group2:
480 await group2.spawn(p1.reestablish_channel(chan_AB))
481 await group2.spawn(p2.reestablish_channel(chan_BA))
482 s = "replaying a revoke_and_ack " + ("first" if rev_then_sig else "last")
483 self.assertTrue(any(("alice->bob" in msg and s in msg) for msg in logs.output))
484 self.assertTrue(any(("alice->bob" in msg and
485 "replayed 2 unacked messages. ['update_add_htlc', 'commitment_signed']" in msg) for msg in logs.output))
486 self.assertEqual(chan_AB.peer_state, PeerState.GOOD)
487 self.assertEqual(chan_BA.peer_state, PeerState.GOOD)
488 await group.cancel_remaining()
489 raise SuccessfulTest()
490 with self.assertRaises(SuccessfulTest):
491 await f()
492
493 async def test_reestablish_replay_messages_rev_then_sig(self):
494 """
495 See https://github.com/lightning/bolts/pull/810#issue-728299277
496
497 Rev then Sig
498 A B
499 <---add-----
500 ----add---->
501 <---sig-----
502 ----rev----x
503 ----sig----x
504
505 A needs to retransmit:
506 ----rev--> (note that 'add' can be first too)
507 ----add-->
508 ----sig-->
509 """
510 await self._test_reestablish_replay_messages(True)
511
512 async def test_reestablish_replay_messages_sig_then_rev(self):
513 """
514 See https://github.com/lightning/bolts/pull/810#issue-728299277
515
516 Sig then Rev
517 A B
518 <---add-----
519 ----add---->
520 ----sig----x
521 <---sig-----
522 ----rev----x
523
524 A needs to retransmit:
525 ----add-->
526 ----sig-->
527 ----rev-->
528 """
529 await self._test_reestablish_replay_messages(False)
530
531 async def _test_simple_payment(
532 self,
533 test_trampoline: bool,
534 test_hold_invoice=False,
535 test_failure=False,
536 test_bundle=False,
537 test_bundle_timeout=False
538 ):
539 """Alice pays Bob a single HTLC via direct channel."""
540 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['single_chan'])
541 p1, p2 = graph.peers.values()
542 w1, w2 = graph.workers.values()
543 results = {}
544 async def pay(lnaddr, pay_req):
545 self.assertEqual(PR_UNPAID, w2.get_payment_status(lnaddr.paymenthash, direction=RECEIVED))
546 result, log = await w1.pay_invoice(pay_req)
547 if result is True:
548 self.assertEqual(PR_PAID, w2.get_payment_status(lnaddr.paymenthash, direction=RECEIVED))
549 results[lnaddr] = PaymentDone()
550 else:
551 results[lnaddr] = PaymentFailure()
552 lnaddr, pay_req = self.prepare_invoice(w2)
553 to_pay = [(lnaddr, pay_req)]
554 self.prepare_recipient(w2, lnaddr.paymenthash, test_hold_invoice, test_failure)
555
556 if test_bundle:
557 lnaddr2, pay_req2 = self.prepare_invoice(w2)
558 w2.bundle_payments([lnaddr.paymenthash, lnaddr2.paymenthash])
559 if not test_bundle_timeout:
560 to_pay.append((lnaddr2, pay_req2))
561
562 if test_trampoline:
563 await self._activate_trampoline(w1)
564 # declare bob as trampoline node
565 electrum.trampoline._TRAMPOLINE_NODES_UNITTESTS = {
566 'bob': LNPeerAddr(host="127.0.0.1", port=9735, pubkey=w2.node_keypair.pubkey),
567 }
568
569 async def f():
570 async with OldTaskGroup() as group:
571 await group.spawn(p1._message_loop())
572 await group.spawn(p1.htlc_switch())
573 await group.spawn(p2._message_loop())
574 await group.spawn(p2.htlc_switch())
575 await asyncio.sleep(0.01)
576 invoice_features = lnaddr.get_features()
577 self.assertFalse(invoice_features.supports(LnFeatures.BASIC_MPP_OPT))
578 for lnaddr_to_pay, pay_req_to_pay in to_pay:
579 await group.spawn(pay(lnaddr_to_pay, pay_req_to_pay))
580 elapsed = 0
581 while len(results) < len(to_pay) and elapsed < 4:
582 await asyncio.sleep(0.05) # wait for all payments to finish/fail (or timeout)
583 elapsed += 0.05
584 self.assertEqual(len(results), len(to_pay), msg="timeout")
585 # all payment results should be similar
586 self.assertEqual(len(set(type(res) for res in results.values())), 1, msg=results)
587 raise list(results.values())[0]
588
589 await f()
590
591 async def test_simple_payment_success(self):
592 for test_trampoline in [False, True]:
593 with self.assertRaises(PaymentDone):
594 await self._test_simple_payment(test_trampoline=test_trampoline)
595
596 async def test_simple_payment_failure(self):
597 for test_trampoline in [False, True]:
598 with self.assertRaises(PaymentFailure):
599 await self._test_simple_payment(test_trampoline=test_trampoline, test_failure=True)
600
601 async def test_payment_bundle(self):
602 for test_trampoline in [False, True]:
603 with self.assertRaises(PaymentDone):
604 await self._test_simple_payment(test_trampoline=test_trampoline, test_bundle=True)
605
606 async def test_payment_bundle_timeout(self):
607 for test_trampoline in [False, True]:
608 with self.assertRaises(PaymentFailure):
609 await self._test_simple_payment(test_trampoline=test_trampoline, test_bundle=True, test_bundle_timeout=True)
610
611 async def test_payment_bundle_with_hold_invoice(self):
612 for test_trampoline in [False, True]:
613 with self.assertRaises(PaymentDone):
614 await self._test_simple_payment(test_trampoline=test_trampoline, test_bundle=True, test_hold_invoice=True)
615
616 async def test_simple_payment_success_with_hold_invoice(self):
617 for test_trampoline in [False, True]:
618 with self.assertRaises(PaymentDone):
619 await self._test_simple_payment(test_trampoline=test_trampoline, test_hold_invoice=True)
620
621 async def test_simple_payment_failure_with_hold_invoice(self):
622 for test_trampoline in [False, True]:
623 with self.assertRaises(PaymentFailure):
624 await self._test_simple_payment(test_trampoline=test_trampoline, test_hold_invoice=True, test_failure=True)
625
626 async def test_check_invoice_before_payment(self):
627 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['single_chan'])
628 p1, p2 = graph.peers.values()
629 w1, w2 = graph.workers.values()
630 async def try_paying_some_invoices():
631 # feature bits: unknown even fbit
632 invoice_features = w2.features.for_bolt11_invoice() | (1 << 990) # add undefined even fbit
633 lnaddr, pay_req = self.prepare_invoice(w2, invoice_features=invoice_features)
634 with self.assertRaises(lnutil.UnknownEvenFeatureBits):
635 result, log = await w1.pay_invoice(pay_req)
636 # feature bits: not all transitive dependencies are set
637 invoice_features = LnFeatures((1 << 8) + (1 << 17))
638 lnaddr, pay_req = self.prepare_invoice(w2, invoice_features=invoice_features)
639 with self.assertRaises(lnutil.IncompatibleOrInsaneFeatures):
640 result, log = await w1.pay_invoice(pay_req)
641 # too large CLTV
642 lnaddr, pay_req = self.prepare_invoice(w2, min_final_cltv_delta=10**6)
643 with self.assertRaises(InvoiceError):
644 result, log = await w1.pay_invoice(pay_req)
645 raise SuccessfulTest()
646
647 async def f():
648 async with OldTaskGroup() as group:
649 await group.spawn(p1._message_loop())
650 await group.spawn(p1.htlc_switch())
651 await group.spawn(p2._message_loop())
652 await group.spawn(p2.htlc_switch())
653 await asyncio.sleep(0.01)
654 await group.spawn(try_paying_some_invoices())
655
656 with self.assertRaises(SuccessfulTest):
657 await f()
658
659 async def test_reject_invalid_min_final_cltv_delta(self):
660 """
661 Tests that htlcs with a final cltv delta < the minimum requested in the invoice get
662 rejected immediately upon receiving them.
663 """
664 async def run_test(test_trampoline):
665 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['single_chan'])
666 p1, p2 = graph.peers.values()
667 w1, w2 = graph.workers.values()
668
669 async def try_pay_with_too_low_final_cltv_delta(lnaddr, w1=w1, w2=w2):
670 self.assertEqual(PR_UNPAID, w2.get_payment_status(lnaddr.paymenthash, direction=RECEIVED))
671 assert lnaddr.get_min_final_cltv_delta() == 400 # what the receiver expects
672 lnaddr.tags = [tag for tag in lnaddr.tags if tag[0] != 'c'] + [['c', 144]]
673 b11 = encode_bolt11_invoice(lnaddr, w2.node_keypair.privkey)
674 pay_req = Invoice.from_bech32(b11)
675 assert pay_req._lnaddr.get_min_final_cltv_delta() == 144 # what w1 will use to pay
676 result, log = await w1.pay_invoice(pay_req)
677 if not result:
678 raise PaymentFailure()
679 raise PaymentDone()
680
681 # create invoice with high min final cltv delta
682 lnaddr, _pay_req = self.prepare_invoice(w2, min_final_cltv_delta=400)
683
684 if test_trampoline:
685 await self._activate_trampoline(w1)
686 # declare bob as trampoline node
687 electrum.trampoline._TRAMPOLINE_NODES_UNITTESTS = {
688 'bob': LNPeerAddr(host="127.0.0.1", port=9735, pubkey=w2.node_keypair.pubkey),
689 }
690
691 async def f():
692 async with OldTaskGroup() as group:
693 await group.spawn(p1._message_loop())
694 await group.spawn(p1.htlc_switch())
695 await group.spawn(p2._message_loop())
696 await group.spawn(p2.htlc_switch())
697 await asyncio.sleep(0.01)
698 await group.spawn(try_pay_with_too_low_final_cltv_delta(lnaddr))
699
700 with self.assertRaises(PaymentFailure):
701 await f()
702
703 for _test_trampoline in [False, True]:
704 await run_test(_test_trampoline)
705
706 async def test_reject_payment_for_expired_invoice(self):
707 """Tests that new htlcs paying an invoice that has already been expired will get rejected."""
708 async def run_test(test_trampoline):
709 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['single_chan'])
710 p1, p2 = graph.peers.values()
711 w1, w2 = graph.workers.values()
712
713 # create lightning invoice in the past, so it is expired
714 with mock.patch('time.time', return_value=int(time.time()) - 10000):
715 lnaddr, _pay_req = self.prepare_invoice(w2, expiry=3600)
716 b11 = encode_bolt11_invoice(lnaddr, w2.node_keypair.privkey)
717 pay_req = Invoice.from_bech32(b11)
718
719 async def try_pay_expired_invoice(pay_req: Invoice, w1=w1):
720 assert pay_req.has_expired()
721 assert lnaddr.is_expired()
722 with mock.patch.object(w1, "_check_bolt11_invoice", return_value=lnaddr):
723 result, log = await w1.pay_invoice(pay_req)
724 if not result:
725 raise PaymentFailure()
726 raise PaymentDone()
727
728 if test_trampoline:
729 await self._activate_trampoline(w1)
730 # declare bob as trampoline node
731 electrum.trampoline._TRAMPOLINE_NODES_UNITTESTS = {
732 'bob': LNPeerAddr(host="127.0.0.1", port=9735, pubkey=w2.node_keypair.pubkey),
733 }
734
735 async def f():
736 async with OldTaskGroup() as group:
737 await group.spawn(p1._message_loop())
738 await group.spawn(p1.htlc_switch())
739 await group.spawn(p2._message_loop())
740 await group.spawn(p2.htlc_switch())
741 await asyncio.sleep(0.01)
742 await group.spawn(try_pay_expired_invoice(pay_req))
743
744 with self.assertRaises(PaymentFailure):
745 await f()
746
747 for _test_trampoline in [False, True]:
748 await run_test(_test_trampoline)
749
750 async def test_reject_mpp_for_non_mpp_invoice(self):
751 """Test that we reject a payment if it is mpp and we didn't signal support for mpp in the invoice"""
752 async def run_test(test_trampoline):
753 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['single_chan'])
754 p1, p2 = graph.peers.values()
755 w1, w2 = graph.workers.values()
756 w1.config.TEST_FORCE_MPP = True # force alice to send mpp
757
758 if test_trampoline:
759 await self._activate_trampoline(w1)
760 await self._activate_trampoline(w2)
761 # declare bob as trampoline node
762 electrum.trampoline._TRAMPOLINE_NODES_UNITTESTS = {
763 'bob': LNPeerAddr(host="127.0.0.1", port=9735, pubkey=w2.node_keypair.pubkey),
764 }
765
766 lnaddr, pay_req = self.prepare_invoice(w2)
767 self.assertFalse(lnaddr.get_features().supports(LnFeatures.BASIC_MPP_OPT))
768 self.assertFalse(lnaddr.get_features().supports(LnFeatures.BASIC_MPP_REQ))
769
770 async def try_pay_invoice_with_mpp(pay_req: Invoice, w1=w1):
771 result, log = await w1.pay_invoice(pay_req)
772 if not result:
773 raise PaymentFailure()
774 raise PaymentDone()
775
776 async def f():
777 async with OldTaskGroup() as group:
778 await group.spawn(p1._message_loop())
779 await group.spawn(p1.htlc_switch())
780 await group.spawn(p2._message_loop())
781 await group.spawn(p2.htlc_switch())
782 await asyncio.sleep(0.01)
783 await group.spawn(try_pay_invoice_with_mpp(pay_req))
784
785 with self.assertRaises(PaymentFailure):
786 await f()
787
788 for _test_trampoline in [False, True]:
789 await run_test(_test_trampoline)
790
791 async def test_reject_multiple_payments_of_same_invoice(self):
792 """Tests that new htlcs paying an invoice that has already been paid will get rejected."""
793 async def run_test(test_trampoline):
794 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['single_chan'])
795 p1, p2 = graph.peers.values()
796 w1, w2 = graph.workers.values()
797
798 lnaddr, _pay_req = self.prepare_invoice(w2)
799
800 async def try_pay_invoice_twice(pay_req: Invoice, w1=w1):
801 result, log = await w1.pay_invoice(pay_req)
802 assert result is True
803 # now pay the same invoice again, the payment should be rejected by w2
804 w1.set_payment_status(pay_req._lnaddr.paymenthash, PR_UNPAID, direction=lnutil.SENT)
805 result, log = await w1.pay_invoice(pay_req)
806 if not result:
807 # w1.pay_invoice returned a payment failure as the payment got rejected by w2
808 raise SuccessfulTest()
809 raise PaymentDone()
810
811 if test_trampoline:
812 await self._activate_trampoline(w1)
813 # declare bob as trampoline node
814 electrum.trampoline._TRAMPOLINE_NODES_UNITTESTS = {
815 'bob': LNPeerAddr(host="127.0.0.1", port=9735, pubkey=w2.node_keypair.pubkey),
816 }
817
818 async def f():
819 async with OldTaskGroup() as group:
820 await group.spawn(p1._message_loop())
821 await group.spawn(p1.htlc_switch())
822 await group.spawn(p2._message_loop())
823 await group.spawn(p2.htlc_switch())
824 await asyncio.sleep(0.01)
825 await group.spawn(try_pay_invoice_twice(_pay_req))
826
827 with self.assertRaises(SuccessfulTest):
828 await f()
829
830 for _test_trampoline in [False, True]:
831 await run_test(_test_trampoline)
832
833 async def test_payment_race(self):
834 """Alice and Bob pay each other simultaneously.
835 They both send 'update_add_htlc' and receive each other's update
836 before sending 'commitment_signed'. Neither party should fulfill
837 the respective HTLCs until those are irrevocably committed to.
838 """
839 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['single_chan'])
840 p1, p2 = graph.peers.values()
841 w1, w2 = graph.workers.values()
842 alice_channel = graph.channels[('alice', 'bob')][0]
843 bob_channel = graph.channels[('bob', 'alice')][0]
844 async def pay():
845 await util.wait_for2(p1.initialized, 1)
846 await util.wait_for2(p2.initialized, 1)
847 # prep
848 _maybe_send_commitment1 = p1.maybe_send_commitment
849 _maybe_send_commitment2 = p2.maybe_send_commitment
850 lnaddr2, pay_req2 = self.prepare_invoice(w2)
851 lnaddr1, pay_req1 = self.prepare_invoice(w1)
852 # alice sends htlc BUT NOT COMMITMENT_SIGNED
853 p1.maybe_send_commitment = lambda x: None
854 route1 = (await w1.create_routes_from_invoice(lnaddr2.get_amount_msat(), decoded_invoice=lnaddr2))[0][0].route
855 paysession1 = w1._paysessions[lnaddr2.paymenthash + lnaddr2.payment_secret]
856 shi1 = SentHtlcInfo(
857 route=route1,
858 payment_secret_orig=lnaddr2.payment_secret,
859 payment_secret_bucket=lnaddr2.payment_secret,
860 amount_msat=lnaddr2.get_amount_msat(),
861 bucket_msat=lnaddr2.get_amount_msat(),
862 amount_receiver_msat=lnaddr2.get_amount_msat(),
863 trampoline_fee_level=None,
864 trampoline_route=None,
865 )
866 await w1.pay_to_route(
867 sent_htlc_info=shi1,
868 paysession=paysession1,
869 min_final_cltv_delta=lnaddr2.get_min_final_cltv_delta(),
870 )
871 p1.maybe_send_commitment = _maybe_send_commitment1
872 # bob sends htlc BUT NOT COMMITMENT_SIGNED
873 p2.maybe_send_commitment = lambda x: None
874 route2 = (await w2.create_routes_from_invoice(lnaddr1.get_amount_msat(), decoded_invoice=lnaddr1))[0][0].route
875 paysession2 = w2._paysessions[lnaddr1.paymenthash + lnaddr1.payment_secret]
876 shi2 = SentHtlcInfo(
877 route=route2,
878 payment_secret_orig=lnaddr1.payment_secret,
879 payment_secret_bucket=lnaddr1.payment_secret,
880 amount_msat=lnaddr1.get_amount_msat(),
881 bucket_msat=lnaddr1.get_amount_msat(),
882 amount_receiver_msat=lnaddr1.get_amount_msat(),
883 trampoline_fee_level=None,
884 trampoline_route=None,
885 )
886 await w2.pay_to_route(
887 sent_htlc_info=shi2,
888 paysession=paysession2,
889 min_final_cltv_delta=lnaddr1.get_min_final_cltv_delta(),
890 )
891 p2.maybe_send_commitment = _maybe_send_commitment2
892 # sleep a bit so that they both receive msgs sent so far
893 await asyncio.sleep(0.2)
894 # now they both send COMMITMENT_SIGNED
895 p1.maybe_send_commitment(alice_channel)
896 p2.maybe_send_commitment(bob_channel)
897
898 htlc_log1 = await paysession1.sent_htlcs_q.get()
899 self.assertTrue(htlc_log1.success)
900 htlc_log2 = await paysession2.sent_htlcs_q.get()
901 self.assertTrue(htlc_log2.success)
902 raise PaymentDone()
903
904 async def f():
905 async with OldTaskGroup() as group:
906 await group.spawn(p1._message_loop())
907 await group.spawn(p1.htlc_switch())
908 await group.spawn(p2._message_loop())
909 await group.spawn(p2.htlc_switch())
910 await asyncio.sleep(0.01)
911 await group.spawn(pay())
912 with self.assertRaises(PaymentDone):
913 await f()
914
915 #@unittest.skip("too expensive")
916 async def test_payments_stresstest(self):
917 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['single_chan'])
918 p1, p2 = graph.peers.values()
919 w1, w2 = graph.workers.values()
920 alice_channel = graph.channels[('alice', 'bob')][0]
921 bob_channel = graph.channels[('bob', 'alice')][0]
922 alice_init_balance_msat = alice_channel.balance(HTLCOwner.LOCAL)
923 bob_init_balance_msat = bob_channel.balance(HTLCOwner.LOCAL)
924 num_payments = 50
925 payment_value_msat = 10_000_000 # make it large enough so that there are actually HTLCs on the ctx
926 max_htlcs_in_flight = asyncio.Semaphore(5)
927 async def single_payment(pay_req):
928 async with max_htlcs_in_flight:
929 await w1.pay_invoice(pay_req)
930 async def many_payments():
931 async with OldTaskGroup() as group:
932 for i in range(num_payments):
933 lnaddr, pay_req = self.prepare_invoice(w2, amount_msat=payment_value_msat)
934 await group.spawn(single_payment(pay_req))
935 gath.cancel()
936 gath = asyncio.gather(many_payments(), p1._message_loop(), p2._message_loop(), p1.htlc_switch(), p2.htlc_switch())
937 with self.assertRaises(asyncio.CancelledError):
938 await gath
939 self.assertEqual(alice_init_balance_msat - num_payments * payment_value_msat, alice_channel.balance(HTLCOwner.LOCAL))
940 self.assertEqual(alice_init_balance_msat - num_payments * payment_value_msat, bob_channel.balance(HTLCOwner.REMOTE))
941 self.assertEqual(bob_init_balance_msat + num_payments * payment_value_msat, bob_channel.balance(HTLCOwner.LOCAL))
942 self.assertEqual(bob_init_balance_msat + num_payments * payment_value_msat, alice_channel.balance(HTLCOwner.REMOTE))
943
944 async def test_payment_recv_mpp_confusion1(self):
945 """Regression test for https://github.com/spesmilo/electrum/security/advisories/GHSA-8r85-vp7r-hjxf"""
946 # This test checks that the following attack does not work:
947 # - Bob creates invoice1: 1 BTC, H1, S1
948 # - Bob creates invoice2: 1 BTC, H2, S2; both given to attacker to pay
949 # - Alice sends htlc1: 0.1 BTC, H1, S1 (total_msat=1 BTC)
950 # - Alice sends htlc2: 0.9 BTC, H2, S1 (total_msat=1 BTC)
951 # - Bob(victim) reveals preimage for H1 and fulfills htlc1 (fails other)
952 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['single_chan'])
953 p1, p2 = graph.peers.values()
954 w1, w2 = graph.workers.values()
955 alice_channel = graph.channels[('alice', 'bob')][0]
956 bob_channel = graph.channels[('bob', 'alice')][0]
957 async def pay():
958 self.assertEqual(PR_UNPAID, w2.get_payment_status(lnaddr1.paymenthash, direction=RECEIVED))
959 self.assertEqual(PR_UNPAID, w2.get_payment_status(lnaddr2.paymenthash, direction=RECEIVED))
960
961 route = (await w1.create_routes_from_invoice(amount_msat=1000, decoded_invoice=lnaddr1))[0][0].route
962 p1.pay(
963 route=route,
964 chan=alice_channel,
965 amount_msat=1000,
966 total_msat=lnaddr1.get_amount_msat(),
967 payment_hash=lnaddr1.paymenthash,
968 min_final_cltv_delta=lnaddr1.get_min_final_cltv_delta(),
969 payment_secret=lnaddr1.payment_secret,
970 )
971 p1.pay(
972 route=route,
973 chan=alice_channel,
974 amount_msat=lnaddr1.get_amount_msat() - 1000,
975 total_msat=lnaddr1.get_amount_msat(),
976 payment_hash=lnaddr2.paymenthash,
977 min_final_cltv_delta=lnaddr1.get_min_final_cltv_delta(),
978 payment_secret=lnaddr1.payment_secret,
979 )
980
981 while nhtlc_success + nhtlc_failed < 2:
982 await htlc_resolved.wait()
983 self.assertEqual(0, nhtlc_success)
984 self.assertEqual(2, nhtlc_failed)
985 raise SuccessfulTest()
986
987 w2.features |= LnFeatures.BASIC_MPP_OPT
988 lnaddr1, _pay_req = self.prepare_invoice(w2, amount_msat=100_000_000)
989 lnaddr2, _pay_req = self.prepare_invoice(w2, amount_msat=100_000_000)
990 self.assertTrue(lnaddr1.get_features().supports(LnFeatures.BASIC_MPP_OPT))
991 self.assertTrue(lnaddr2.get_features().supports(LnFeatures.BASIC_MPP_OPT))
992
993 async def f():
994 async with OldTaskGroup() as group:
995 await group.spawn(p1._message_loop())
996 await group.spawn(p1.htlc_switch())
997 await group.spawn(p2._message_loop())
998 await group.spawn(p2.htlc_switch())
999 await asyncio.sleep(0.01)
1000 await group.spawn(pay())
1001
1002 htlc_resolved = asyncio.Event()
1003 nhtlc_success = 0
1004 nhtlc_failed = 0
1005 async def on_htlc_fulfilled(*args):
1006 htlc_resolved.set()
1007 htlc_resolved.clear()
1008 nonlocal nhtlc_success
1009 nhtlc_success += 1
1010 async def on_htlc_failed(*args):
1011 htlc_resolved.set()
1012 htlc_resolved.clear()
1013 nonlocal nhtlc_failed
1014 nhtlc_failed += 1
1015 util.register_callback(on_htlc_fulfilled, ["htlc_fulfilled"])
1016 util.register_callback(on_htlc_failed, ["htlc_failed"])
1017
1018 with self.assertRaises(SuccessfulTest):
1019 await f()
1020
1021 async def test_payment_recv_mpp_confusion2(self):
1022 """Regression test for https://github.com/spesmilo/electrum/security/advisories/GHSA-8r85-vp7r-hjxf"""
1023 # This test checks that the following attack does not work:
1024 # - Bob creates invoice: 1 BTC
1025 # - Alice sends htlc1: 0.1 BTC (total_msat=0.2 BTC)
1026 # - Alice sends htlc2: 0.1 BTC (total_msat=1 BTC)
1027 # - Bob(victim) reveals preimage and fulfills htlc2 (fails other)
1028 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['single_chan'])
1029 p1, p2 = graph.peers.values()
1030 w1, w2 = graph.workers.values()
1031 alice_channel = graph.channels[('alice', 'bob')][0]
1032 bob_channel = graph.channels[('bob', 'alice')][0]
1033 async def pay():
1034 self.assertEqual(PR_UNPAID, w2.get_payment_status(lnaddr1.paymenthash, direction=RECEIVED))
1035
1036 route = (await w1.create_routes_from_invoice(amount_msat=1000, decoded_invoice=lnaddr1))[0][0].route
1037 p1.pay(
1038 route=route,
1039 chan=alice_channel,
1040 amount_msat=1000,
1041 total_msat=2000,
1042 payment_hash=lnaddr1.paymenthash,
1043 min_final_cltv_delta=lnaddr1.get_min_final_cltv_delta(),
1044 payment_secret=lnaddr1.payment_secret,
1045 )
1046 p1.pay(
1047 route=route,
1048 chan=alice_channel,
1049 amount_msat=1000,
1050 total_msat=lnaddr1.get_amount_msat(),
1051 payment_hash=lnaddr1.paymenthash,
1052 min_final_cltv_delta=lnaddr1.get_min_final_cltv_delta(),
1053 payment_secret=lnaddr1.payment_secret,
1054 )
1055
1056 while nhtlc_success + nhtlc_failed < 2:
1057 await htlc_resolved.wait()
1058 self.assertEqual(0, nhtlc_success)
1059 self.assertEqual(2, nhtlc_failed)
1060 raise SuccessfulTest()
1061
1062 w2.features |= LnFeatures.BASIC_MPP_OPT
1063 lnaddr1, _pay_req = self.prepare_invoice(w2, amount_msat=100_000_000)
1064 self.assertTrue(lnaddr1.get_features().supports(LnFeatures.BASIC_MPP_OPT))
1065
1066 async def f():
1067 async with OldTaskGroup() as group:
1068 await group.spawn(p1._message_loop())
1069 await group.spawn(p1.htlc_switch())
1070 await group.spawn(p2._message_loop())
1071 await group.spawn(p2.htlc_switch())
1072 await asyncio.sleep(0.01)
1073 await group.spawn(pay())
1074
1075 htlc_resolved = asyncio.Event()
1076 nhtlc_success = 0
1077 nhtlc_failed = 0
1078 async def on_htlc_fulfilled(*args):
1079 htlc_resolved.set()
1080 htlc_resolved.clear()
1081 nonlocal nhtlc_success
1082 nhtlc_success += 1
1083 async def on_htlc_failed(*args):
1084 htlc_resolved.set()
1085 htlc_resolved.clear()
1086 nonlocal nhtlc_failed
1087 nhtlc_failed += 1
1088 util.register_callback(on_htlc_fulfilled, ["htlc_fulfilled"])
1089 util.register_callback(on_htlc_failed, ["htlc_failed"])
1090
1091 with self.assertRaises(SuccessfulTest):
1092 await f()
1093
1094 async def test_dont_settle_partial_mpp_trigger_with_invalid_cltv_htlc(self):
1095 """Alice gets two htlcs as part of a mpp, one has a cltv too close to expiry and will get failed.
1096 Test that the other htlc won't get settled if the mpp isn't complete anymore after failing the other htlc.
1097 """
1098 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['single_chan'])
1099 p1, p2 = graph.peers.values()
1100 w1, w2 = graph.workers.values()
1101 alice_channel = graph.channels[('alice', 'bob')][0]
1102 bob_channel = graph.channels[('bob', 'alice')][0]
1103 async def pay():
1104 await util.wait_for2(p1.initialized, 1)
1105 await util.wait_for2(p2.initialized, 1)
1106 w2.features |= LnFeatures.BASIC_MPP_OPT
1107 lnaddr1, _pay_req = self.prepare_invoice(w2, amount_msat=10_000, min_final_cltv_delta=144)
1108 self.assertTrue(lnaddr1.get_features().supports(LnFeatures.BASIC_MPP_OPT))
1109 route = (await w1.create_routes_from_invoice(amount_msat=10_000, decoded_invoice=lnaddr1))[0][0].route
1110
1111 # now p1 sends two htlcs, one is valid (1 msat), one is invalid (9_999 msat)
1112 p1.pay(
1113 route=route,
1114 chan=alice_channel,
1115 amount_msat=1,
1116 total_msat=lnaddr1.get_amount_msat(),
1117 payment_hash=lnaddr1.paymenthash,
1118 # this htlc is valid and will get accepted, but it shouldn't get settled
1119 min_final_cltv_delta=400,
1120 payment_secret=lnaddr1.payment_secret,
1121 )
1122 await asyncio.sleep(0.1)
1123 assert w1.get_preimage(lnaddr1.paymenthash) is None
1124 p1.pay(
1125 route=route,
1126 chan=alice_channel,
1127 amount_msat=9_999,
1128 total_msat=lnaddr1.get_amount_msat(),
1129 payment_hash=lnaddr1.paymenthash,
1130 # this htlc will get failed directly as the cltv is too close to expiry (< 144)
1131 min_final_cltv_delta=1,
1132 payment_secret=lnaddr1.payment_secret,
1133 )
1134
1135 while nhtlc_success + nhtlc_failed < 2:
1136 await htlc_resolved.wait()
1137 # both htlcs of the mpp set should get failed and w2 shouldn't release the preimage
1138 self.assertEqual(0, nhtlc_success, f"{nhtlc_success=} | {nhtlc_failed=}")
1139 self.assertEqual(2, nhtlc_failed, f"{nhtlc_success=} | {nhtlc_failed=}")
1140 assert w1.get_preimage(lnaddr1.paymenthash) is None, "w1 shouldn't get the preimage"
1141 raise SuccessfulTest()
1142
1143 async def f():
1144 async with OldTaskGroup() as group:
1145 await group.spawn(p1._message_loop())
1146 await group.spawn(p1.htlc_switch())
1147 await group.spawn(p2._message_loop())
1148 await group.spawn(p2.htlc_switch())
1149 await asyncio.sleep(0.01)
1150 await group.spawn(pay())
1151
1152 htlc_resolved = asyncio.Event()
1153 nhtlc_success = 0
1154 nhtlc_failed = 0
1155 async def on_htlc_fulfilled(*args):
1156 htlc_resolved.set()
1157 htlc_resolved.clear()
1158 nonlocal nhtlc_success
1159 nhtlc_success += 1
1160 async def on_htlc_failed(*args):
1161 htlc_resolved.set()
1162 htlc_resolved.clear()
1163 nonlocal nhtlc_failed
1164 nhtlc_failed += 1
1165 util.register_callback(on_htlc_fulfilled, ["htlc_fulfilled"])
1166 util.register_callback(on_htlc_failed, ["htlc_failed"])
1167
1168 try:
1169 with self.assertRaises(SuccessfulTest):
1170 await f()
1171 finally:
1172 util.unregister_callback(on_htlc_fulfilled)
1173 util.unregister_callback(on_htlc_failed)
1174
1175 async def test_mpp_cleanup_after_expiry(self):
1176 """
1177 1. Alice sends two HTLCs to Bob, not reaching total_msat, and eventually they MPP_TIMEOUT
1178 2. Bob fails both HTLCs
1179 3. Alice then retries and sends HTLCs again to Bob, for the same RHASH,
1180 this time reaching total_msat, and the payment succeeds
1181
1182 Test that the sets are properly cleaned up after MPP_TIMEOUT
1183 and the sender gets a second chance to pay the same invoice.
1184 """
1185 async def run_test(test_trampoline: bool):
1186 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['single_chan'])
1187 alice_peer, bob_peer = graph.peers.values()
1188 alice_wallet, bob_wallet = graph.workers.values()
1189 alice_channel = graph.channels[('alice', 'bob')][0]
1190 bob_channel = graph.channels[('bob', 'alice')][0]
1191 bob_wallet.features |= LnFeatures.BASIC_MPP_OPT
1192 lnaddr1, pay_req1 = self.prepare_invoice(bob_wallet, amount_msat=10_000)
1193
1194 if test_trampoline:
1195 await self._activate_trampoline(alice_wallet)
1196 # declare bob as trampoline node
1197 electrum.trampoline._TRAMPOLINE_NODES_UNITTESTS = {
1198 'bob': LNPeerAddr(host="127.0.0.1", port=9735, pubkey=bob_wallet.node_keypair.pubkey),
1199 }
1200
1201 async def _test():
1202 route = (await alice_wallet.create_routes_from_invoice(amount_msat=10_000, decoded_invoice=lnaddr1))[0][0].route
1203 assert len(bob_wallet.received_mpp_htlcs) == 0
1204 # now alice sends two small htlcs, so the set stays incomplete
1205 alice_peer.pay( # htlc 1
1206 route=route,
1207 chan=alice_channel,
1208 amount_msat=lnaddr1.get_amount_msat() // 4,
1209 total_msat=lnaddr1.get_amount_msat(),
1210 payment_hash=lnaddr1.paymenthash,
1211 min_final_cltv_delta=400,
1212 payment_secret=lnaddr1.payment_secret,
1213 )
1214 alice_peer.pay( # htlc 2
1215 route=route,
1216 chan=alice_channel,
1217 amount_msat=lnaddr1.get_amount_msat() // 4,
1218 total_msat=lnaddr1.get_amount_msat(),
1219 payment_hash=lnaddr1.paymenthash,
1220 min_final_cltv_delta=400,
1221 payment_secret=lnaddr1.payment_secret,
1222 )
1223 await asyncio.sleep(bob_wallet.MPP_EXPIRY // 2) # give bob time to receive the htlc
1224 bob_payment_key = bob_wallet._get_payment_key(lnaddr1.paymenthash).hex()
1225 assert bob_wallet.received_mpp_htlcs[bob_payment_key].resolution == RecvMPPResolution.WAITING
1226 assert len(bob_wallet.received_mpp_htlcs[bob_payment_key].htlcs) == 2
1227 # now wait until bob expires the mpp (set)
1228 async with util.async_timeout(bob_wallet.MPP_EXPIRY * 3): # this can take some time, esp. on CI
1229 while nhtlc_success + nhtlc_failed < 2:
1230 await alice_htlc_resolved.wait()
1231 # check that bob failed the htlc
1232 assert nhtlc_success == 0 and nhtlc_failed == 2
1233 # check that bob deleted the mpp set as it should be expired and resolved now
1234 assert bob_payment_key not in bob_wallet.received_mpp_htlcs
1235 alice_wallet._paysessions.clear()
1236 assert alice_wallet.get_preimage(lnaddr1.paymenthash) is None # bob didn't preimage
1237 # now try to pay again, this time the full amount
1238 result, log = await alice_wallet.pay_invoice(pay_req1)
1239 assert result is True
1240 assert alice_wallet.get_preimage(lnaddr1.paymenthash) is not None # bob revealed preimage
1241 assert len(bob_wallet.received_mpp_htlcs) == 0 # bob should also clean up a successful set
1242 raise SuccessfulTest()
1243
1244 async def f():
1245 async with OldTaskGroup() as group:
1246 await group.spawn(alice_peer._message_loop())
1247 await group.spawn(alice_peer.htlc_switch())
1248 await group.spawn(bob_peer._message_loop())
1249 await group.spawn(bob_peer.htlc_switch())
1250 await asyncio.sleep(0.01)
1251 await group.spawn(_test())
1252
1253 alice_htlc_resolved = asyncio.Event()
1254 nhtlc_success = 0
1255 nhtlc_failed = 0
1256 async def on_sender_htlc_fulfilled(*args):
1257 alice_htlc_resolved.set()
1258 alice_htlc_resolved.clear()
1259 nonlocal nhtlc_success
1260 nhtlc_success += 1
1261 async def on_sender_htlc_failed(*args):
1262 alice_htlc_resolved.set()
1263 alice_htlc_resolved.clear()
1264 nonlocal nhtlc_failed
1265 nhtlc_failed += 1
1266 util.register_callback(on_sender_htlc_fulfilled, ["htlc_fulfilled"])
1267 util.register_callback(on_sender_htlc_failed, ["htlc_failed"])
1268
1269 try:
1270 with self.assertRaises(SuccessfulTest):
1271 await f()
1272 finally:
1273 util.unregister_callback(on_sender_htlc_fulfilled)
1274 util.unregister_callback(on_sender_htlc_failed)
1275
1276 for use_trampoline in [True, False]:
1277 self.logger.debug(f"test_mpp_cleanup_after_expiry: {use_trampoline=}")
1278 await run_test(use_trampoline)
1279
1280 async def test_legacy_shutdown_low(self):
1281 await self._test_shutdown(alice_fee=100, bob_fee=150)
1282
1283 async def test_legacy_shutdown_high(self):
1284 await self._test_shutdown(alice_fee=2000, bob_fee=100)
1285
1286 async def test_modern_shutdown_with_overlap(self):
1287 await self._test_shutdown(
1288 alice_fee=1,
1289 bob_fee=200,
1290 alice_fee_range={'min_fee_satoshis': 1, 'max_fee_satoshis': 10},
1291 bob_fee_range={'min_fee_satoshis': 10, 'max_fee_satoshis': 300})
1292
1293 @mock.patch('electrum.lnpeer.LN_P2P_NETWORK_TIMEOUT', 0.05)
1294 async def test_modern_shutdown_no_overlap(self):
1295 with self.assertLogs('electrum', level='ERROR') as logs:
1296 with self.assertRaisesRegex(Exception, "closing_signed not received"):
1297 await self._test_shutdown(
1298 alice_fee=1,
1299 bob_fee=200,
1300 alice_fee_range={'min_fee_satoshis': 1, 'max_fee_satoshis': 10},
1301 bob_fee_range={'min_fee_satoshis': 50, 'max_fee_satoshis': 300})
1302 self.assertTrue(any(("bob->alice" in msg and "There is no overlap between between their and our fee range." in msg) for msg in logs.output))
1303 self.assertTrue(any(("alice->bob" in msg and "closing_signed not received, force closing." in msg) for msg in logs.output))
1304 # note: "Task exception was never retrieved" for "Exception: There is no overlap [...]"
1305 # is because we don't start peer.main_loop and hence peer.taskgroup is never joined.
1306
1307 async def _test_shutdown(self, alice_fee, bob_fee, alice_fee_range=None, bob_fee_range=None):
1308 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['single_chan'])
1309 p1, p2 = graph.peers.values()
1310 w1, w2 = graph.workers.values()
1311 alice_channel = graph.channels[('alice', 'bob')][0]
1312 bob_channel = graph.channels[('bob', 'alice')][0]
1313 w1.network.config.TEST_SHUTDOWN_FEE = alice_fee
1314 w2.network.config.TEST_SHUTDOWN_FEE = bob_fee
1315 if alice_fee_range is not None:
1316 w1.network.config.TEST_SHUTDOWN_FEE_RANGE = alice_fee_range
1317 else:
1318 w1.network.config.TEST_SHUTDOWN_LEGACY = True
1319 if bob_fee_range is not None:
1320 w2.network.config.TEST_SHUTDOWN_FEE_RANGE = bob_fee_range
1321 else:
1322 w2.network.config.TEST_SHUTDOWN_LEGACY = True
1323 w2.enable_htlc_settle = False
1324 lnaddr, pay_req = self.prepare_invoice(w2)
1325 async def pay():
1326 await util.wait_for2(p1.initialized, 1)
1327 await util.wait_for2(p2.initialized, 1)
1328 # alice sends htlc
1329 route = (await w1.create_routes_from_invoice(lnaddr.get_amount_msat(), decoded_invoice=lnaddr))[0][0].route
1330 p1.pay(route=route,
1331 chan=alice_channel,
1332 amount_msat=lnaddr.get_amount_msat(),
1333 total_msat=lnaddr.get_amount_msat(),
1334 payment_hash=lnaddr.paymenthash,
1335 min_final_cltv_delta=lnaddr.get_min_final_cltv_delta(),
1336 payment_secret=lnaddr.payment_secret)
1337 await p2.received_commitsig_event.wait()
1338 # alice closes
1339 await p1.close_channel(alice_channel.channel_id)
1340 gath.cancel()
1341 async def set_settle():
1342 await asyncio.sleep(0.1)
1343 w2.enable_htlc_settle = True
1344 gath = asyncio.gather(pay(), set_settle(), p1._message_loop(), p2._message_loop(), p1.htlc_switch(), p2.htlc_switch())
1345 with self.assertRaises(asyncio.CancelledError):
1346 await gath
1347
1348 async def test_warning(self):
1349 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['single_chan'])
1350 p1, p2 = graph.peers.values()
1351 alice_channel = graph.channels[('alice', 'bob')][0]
1352 bob_channel = graph.channels[('bob', 'alice')][0]
1353
1354 async def action():
1355 await util.wait_for2(p1.initialized, 1)
1356 await util.wait_for2(p2.initialized, 1)
1357 p1.send_warning(alice_channel.channel_id, 'be warned!', close_connection=True)
1358 gath = asyncio.gather(action(), p1._message_loop(), p2._message_loop(), p1.htlc_switch(), p2.htlc_switch())
1359 with self.assertRaises(GracefulDisconnect):
1360 await gath
1361
1362 async def test_error(self):
1363 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['single_chan'])
1364 p1, p2 = graph.peers.values()
1365 alice_channel = graph.channels[('alice', 'bob')][0]
1366 bob_channel = graph.channels[('bob', 'alice')][0]
1367
1368 async def action():
1369 await util.wait_for2(p1.initialized, 1)
1370 await util.wait_for2(p2.initialized, 1)
1371 p1.send_error(alice_channel.channel_id, 'some error happened!', force_close_channel=True)
1372 assert alice_channel.is_closed()
1373 gath.cancel()
1374 gath = asyncio.gather(action(), p1._message_loop(), p2._message_loop(), p1.htlc_switch(), p2.htlc_switch())
1375 with self.assertRaises(GracefulDisconnect):
1376 await gath
1377
1378 async def test_close_upfront_shutdown_script(self):
1379 alice_lnwallet, bob_lnwallet = self.prepare_lnwallets(self.GRAPH_DEFINITIONS['single_chan']).values()
1380 alice_channel, bob_channel = create_test_channels(alice_lnwallet=alice_lnwallet, bob_lnwallet=bob_lnwallet)
1381
1382 # create upfront shutdown script for bob, alice doesn't use upfront
1383 # shutdown script
1384 bob_uss_pub = privkey_to_pubkey(os.urandom(32))
1385 bob_uss_addr = bitcoin.pubkey_to_address('p2wpkh', bob_uss_pub.hex())
1386 bob_uss = bitcoin.address_to_script(bob_uss_addr)
1387
1388 # bob commits to close to bob_uss
1389 alice_channel.config[HTLCOwner.REMOTE].upfront_shutdown_script = bob_uss
1390 # but bob closes to some receiving address, which we achieve by not
1391 # setting the upfront shutdown script in the channel config
1392 bob_channel.config[HTLCOwner.LOCAL].upfront_shutdown_script = b''
1393
1394 p1, p2, w1, w2 = self.prepare_peers(alice_channel, bob_channel)
1395 w1.network.config.FEE_POLICY = 'feerate:5000'
1396 w2.network.config.FEE_POLICY = 'feerate:1000'
1397
1398 async def test():
1399 async def close():
1400 await util.wait_for2(p1.initialized, 1)
1401 await util.wait_for2(p2.initialized, 1)
1402 # bob closes channel with different shutdown script
1403 await p1.close_channel(alice_channel.channel_id)
1404 self.fail("p1.close_channel should have raised above!")
1405
1406 async def main_loop(peer):
1407 async with peer.taskgroup as group:
1408 await group.spawn(peer._message_loop())
1409 await group.spawn(peer.htlc_switch())
1410
1411 coros = [close(), main_loop(p1), main_loop(p2)]
1412 gath = asyncio.gather(*coros)
1413 await gath
1414
1415 with self.assertRaises(GracefulDisconnect):
1416 await test()
1417 # check that neither party broadcast a closing tx (as it was not even signed)
1418 self.assertEqual(0, w1.network.tx_queue.qsize())
1419 self.assertEqual(0, w2.network.tx_queue.qsize())
1420
1421 # -- new scenario:
1422 # bob sends the same upfront_shutdown_script has he announced
1423 alice_channel.config[HTLCOwner.REMOTE].upfront_shutdown_script = bob_uss
1424 bob_channel.config[HTLCOwner.LOCAL].upfront_shutdown_script = bob_uss
1425
1426 p1, p2, w1, w2 = self.prepare_peers(alice_channel, bob_channel)
1427 w1.network.config.FEE_POLICY = 'feerate:5000'
1428 w2.network.config.FEE_POLICY = 'feerate:1000'
1429
1430 async def test():
1431 async def close():
1432 await util.wait_for2(p1.initialized, 1)
1433 await util.wait_for2(p2.initialized, 1)
1434 await p1.close_channel(alice_channel.channel_id)
1435 gath.cancel()
1436
1437 async def main_loop(peer):
1438 async with peer.taskgroup as group:
1439 await group.spawn(peer._message_loop())
1440 await group.spawn(peer.htlc_switch())
1441
1442 coros = [close(), main_loop(p1), main_loop(p2)]
1443 gath = asyncio.gather(*coros)
1444 await gath
1445
1446 with self.assertRaises(asyncio.CancelledError):
1447 await test()
1448
1449 # check if p1 has broadcast the closing tx, and if it pays to Bob's uss
1450 self.assertEqual(1, w1.network.tx_queue.qsize())
1451 closing_tx = w1.network.tx_queue.get_nowait() # type: Transaction
1452 self.assertEqual(2, len(closing_tx.outputs()))
1453 self.assertEqual(1, len(closing_tx.get_output_idxs_from_address(bob_uss_addr)))
1454
1455 async def test_channel_usage_after_closing(self):
1456 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['single_chan'])
1457 p1, p2 = graph.peers.values()
1458 w1, w2 = graph.workers.values()
1459 alice_channel = graph.channels[('alice', 'bob')][0]
1460 bob_channel = graph.channels[('bob', 'alice')][0]
1461 lnaddr, pay_req = self.prepare_invoice(w2)
1462
1463 lnaddr = w1._check_bolt11_invoice(pay_req.lightning_invoice)
1464 shi = (await w1.create_routes_from_invoice(lnaddr.get_amount_msat(), decoded_invoice=lnaddr))[0][0]
1465 route, amount_msat = shi.route, shi.amount_msat
1466 assert amount_msat == lnaddr.get_amount_msat()
1467
1468 await w1.force_close_channel(alice_channel.channel_id)
1469 # check if a tx (commitment transaction) was broadcasted:
1470 assert w1.network.tx_queue.qsize() == 1
1471
1472 with self.assertRaises(NoPathFound) as e:
1473 await w1.create_routes_from_invoice(lnaddr.get_amount_msat(), decoded_invoice=lnaddr)
1474
1475 peer = w1.lnpeermgr._peers[route[0].node_id]
1476 # AssertionError is ok since we shouldn't use old routes, and the
1477 # route finding should fail when channel is closed
1478 async def f():
1479 shi = SentHtlcInfo(
1480 route=route,
1481 payment_secret_orig=lnaddr.payment_secret,
1482 payment_secret_bucket=lnaddr.payment_secret,
1483 amount_msat=amount_msat,
1484 bucket_msat=amount_msat,
1485 amount_receiver_msat=amount_msat,
1486 trampoline_fee_level=None,
1487 trampoline_route=None,
1488 )
1489 paysession = w1._paysessions[lnaddr.paymenthash + lnaddr.payment_secret]
1490 pay = w1.pay_to_route(
1491 sent_htlc_info=shi,
1492 paysession=paysession,
1493 min_final_cltv_delta=lnaddr.get_min_final_cltv_delta(),
1494 )
1495 await asyncio.gather(pay, p1._message_loop(), p2._message_loop(), p1.htlc_switch(), p2.htlc_switch())
1496 with self.assertRaises(PaymentFailure):
1497 await f()
1498
1499 async def test_sending_weird_messages_that_should_be_ignored(self):
1500 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['single_chan'])
1501 p1, p2 = graph.peers.values()
1502
1503 async def send_weird_messages():
1504 await util.wait_for2(p1.initialized, 1)
1505 await util.wait_for2(p2.initialized, 1)
1506 # peer1 sends known message with trailing garbage
1507 # BOLT-01 says peer2 should ignore trailing garbage
1508 raw_msg1 = encode_msg('ping', num_pong_bytes=4, byteslen=4) + bytes(range(55))
1509 p1.transport.send_bytes(raw_msg1)
1510 await asyncio.sleep(0.05)
1511 # peer1 sends unknown 'odd-type' message
1512 # BOLT-01 says peer2 should ignore whole message
1513 raw_msg2 = (43333).to_bytes(length=2, byteorder="big") + bytes(range(55))
1514 p1.transport.send_bytes(raw_msg2)
1515 await asyncio.sleep(0.05)
1516 raise SuccessfulTest()
1517
1518 async def f():
1519 async with OldTaskGroup() as group:
1520 for peer in [p1, p2]:
1521 await group.spawn(peer._message_loop())
1522 await group.spawn(peer.htlc_switch())
1523 for peer in [p1, p2]:
1524 await peer.initialized
1525 await group.spawn(send_weird_messages())
1526
1527 with self.assertRaises(SuccessfulTest):
1528 await f()
1529
1530 async def test_sending_weird_messages__unknown_even_type(self):
1531 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['single_chan'])
1532 p1, p2 = graph.peers.values()
1533
1534 async def send_weird_messages():
1535 await util.wait_for2(p1.initialized, 1)
1536 await util.wait_for2(p2.initialized, 1)
1537 # peer1 sends unknown 'even-type' message
1538 # BOLT-01 says peer2 should close the connection
1539 raw_msg2 = (43334).to_bytes(length=2, byteorder="big") + bytes(range(55))
1540 p1.transport.send_bytes(raw_msg2)
1541 await asyncio.sleep(0.05)
1542
1543 failing_task = None
1544 async def f():
1545 nonlocal failing_task
1546 async with OldTaskGroup() as group:
1547 await group.spawn(p1._message_loop())
1548 await group.spawn(p1.htlc_switch())
1549 failing_task = await group.spawn(p2._message_loop())
1550 await group.spawn(p2.htlc_switch())
1551 for peer in [p1, p2]:
1552 await peer.initialized
1553 await group.spawn(send_weird_messages())
1554
1555 with self.assertRaises(GracefulDisconnect):
1556 await f()
1557 self.assertTrue(isinstance(failing_task.exception().__cause__, lnmsg.UnknownMandatoryMsgType))
1558
1559 async def test_sending_weird_messages__known_msg_with_insufficient_length(self):
1560 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['single_chan'])
1561 p1, p2 = graph.peers.values()
1562
1563 async def send_weird_messages():
1564 await util.wait_for2(p1.initialized, 1)
1565 await util.wait_for2(p2.initialized, 1)
1566 # peer1 sends known message with insufficient length for the contents
1567 # BOLT-01 says peer2 should fail the connection
1568 raw_msg1 = encode_msg('ping', num_pong_bytes=4, byteslen=4)[:-1]
1569 p1.transport.send_bytes(raw_msg1)
1570 await asyncio.sleep(0.05)
1571
1572 failing_task = None
1573 async def f():
1574 nonlocal failing_task
1575 async with OldTaskGroup() as group:
1576 await group.spawn(p1._message_loop())
1577 await group.spawn(p1.htlc_switch())
1578 failing_task = await group.spawn(p2._message_loop())
1579 await group.spawn(p2.htlc_switch())
1580 for peer in [p1, p2]:
1581 await peer.initialized
1582 await group.spawn(send_weird_messages())
1583
1584 with self.assertRaises(GracefulDisconnect):
1585 await f()
1586 self.assertTrue(isinstance(failing_task.exception().__cause__, lnmsg.UnexpectedEndOfStream))
1587
1588 async def test_hold_invoice_set_doesnt_get_expired(self):
1589 """
1590 Alice pays a hold invoice from Bob, Bob doesn't release preimage. Verify that Bob doesn't
1591 expire the htlc set MIN_FINAL_CLTV_DELTA_ACCEPTED blocks before htlc.cltv_abs (as we would do with normal htlc sets).
1592 The htlc set should only get failed if the user of the hold invoice callback explicitly removes the
1593 callback (e.g. after refunding and failing a swap), otherwise it should get timed out onchain (force-close).
1594
1595 This only tests hold invoice logic for hold invoices registered with `LNWallet.register_hold_invoice()`,
1596 as used e.g. by submarine swaps. It doesn't cover the hold invoices created by the hold invoice CLI
1597 which behave differently and use the persisted `LNWallet.dont_expire_htlcs` dict.
1598 """
1599 async def run_test(test_trampoline):
1600 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['single_chan'])
1601 alice_p, bob_p = graph.peers.values()
1602 alice_w, bob_w = graph.workers.values()
1603
1604 lnaddr, pay_req = self.prepare_invoice(bob_w, min_final_cltv_delta=150)
1605 del bob_w._preimages[pay_req.rhash] # del preimage so bob doesn't settle
1606 payment_key = bob_w._get_payment_key(lnaddr.paymenthash).hex()
1607
1608 cb_got_called = asyncio.Event()
1609 async def cb(_payment_hash):
1610 self.logger.debug(f"hold invoice callback called. {bob_w.network.get_local_height()=}")
1611 cb_got_called.set()
1612
1613 bob_w.register_hold_invoice(lnaddr.paymenthash, cb)
1614
1615 async def check_mpp_state():
1616 await util.wait_for2(cb_got_called.wait(), timeout=2)
1617 mpp_set = bob_w.received_mpp_htlcs[payment_key]
1618 self.assertEqual(mpp_set.resolution, RecvMPPResolution.SETTLING, msg=mpp_set.resolution)
1619 self.assertEqual(len(mpp_set.htlcs), 1, f"should get only one htlc: {mpp_set.htlcs=}")
1620 left_to_expiry = next(iter(mpp_set.htlcs)).htlc.cltv_abs - bob_w.network.get_local_height()
1621 # now mine up to one block after the expiry
1622 bob_w.network._blockchain._height += left_to_expiry + 1
1623 await asyncio.sleep(0.2)
1624 # bob still has the mpp set and it is not failed
1625 # it should only get removed once the channel is redeemed
1626 self.assertIn(bob_w.received_mpp_htlcs[payment_key].resolution, (RecvMPPResolution.COMPLETE, RecvMPPResolution.SETTLING))
1627 # now also check that the mpp set will get set failed if the hold invoice
1628 # is being explicitly unregistered, and we don't have a preimage to settle it
1629 bob_w.unregister_hold_invoice(lnaddr.paymenthash)
1630 self.assertEqual(bob_w.received_mpp_htlcs[payment_key].resolution, RecvMPPResolution.FAILED)
1631 raise SuccessfulTest()
1632
1633 if test_trampoline:
1634 await self._activate_trampoline(alice_w)
1635 # declare bob as trampoline node
1636 electrum.trampoline._TRAMPOLINE_NODES_UNITTESTS = {
1637 'bob': LNPeerAddr(host="127.0.0.1", port=9735, pubkey=bob_w.node_keypair.pubkey),
1638 }
1639
1640 async def f():
1641 async with OldTaskGroup() as group:
1642 await group.spawn(alice_p._message_loop())
1643 await group.spawn(alice_p.htlc_switch())
1644 await group.spawn(bob_p._message_loop())
1645 await group.spawn(bob_p.htlc_switch())
1646 await asyncio.sleep(0.01)
1647 await group.spawn(alice_w.pay_invoice(pay_req))
1648 await group.spawn(check_mpp_state())
1649
1650 with self.assertRaises(SuccessfulTest):
1651 await f()
1652
1653 for _test_trampoline in [False, True]:
1654 await run_test(_test_trampoline)
1655
1656 async def test_htlc_switch_iteration_benchmark(self):
1657 """Test how long a call to _run_htlc_switch_iteration takes with 10 trampoline
1658 mpp sets of 1 htlc each. Raise if it takes longer than 20ms (median).
1659 To create flamegraph with py-spy raise NUM_ITERATIONS to 1000 (for more samples) then run:
1660 $ py-spy record -o flamegraph.svg --subprocesses -- python -m pytest tests/test_lnpeer.py::TestPeerDirect::test_htlc_switch_iteration_benchmark
1661 """
1662 NUM_ITERATIONS = 25
1663 alice_lnwallet, bob_lnwallet = self.prepare_lnwallets(self.GRAPH_DEFINITIONS['single_chan']).values()
1664 alice_channel, bob_channel = create_test_channels(
1665 alice_lnwallet=alice_lnwallet, bob_lnwallet=bob_lnwallet, max_accepted_htlcs=20,
1666 )
1667 alice_p, bob_p, alice_w, bob_w = self.prepare_peers(alice_channel, bob_channel)
1668
1669 await self._activate_trampoline(alice_w)
1670 electrum.trampoline._TRAMPOLINE_NODES_UNITTESTS = {
1671 'bob': LNPeerAddr(host="127.0.0.1", port=9735, pubkey=bob_w.node_keypair.pubkey),
1672 }
1673
1674 # create 10 invoices (10 pending htlc sets with 1 htlc each)
1675 invoices = [] # type: list[tuple[BOLT11Addr, Invoice]]
1676 for i in range(10):
1677 lnaddr, pay_req = self.prepare_invoice(bob_w)
1678 # prevent bob from settling so that htlc switch will have to iterate through all pending htlcs
1679 bob_w.dont_settle_htlcs[pay_req.rhash] = None
1680 invoices.append((lnaddr, pay_req))
1681 self.assertEqual(len(invoices), 10, msg=len(invoices))
1682
1683 iterations = []
1684 do_benchmark = False
1685 _run_bob_htlc_switch_iteration = bob_p._run_htlc_switch_iteration
1686 def timed_htlc_switch_iteration():
1687 start = time.perf_counter()
1688 _run_bob_htlc_switch_iteration()
1689 duration = time.perf_counter() - start
1690 if do_benchmark:
1691 iterations.append(duration)
1692 bob_p._run_htlc_switch_iteration = timed_htlc_switch_iteration
1693
1694 async def benchmark_htlc_switch_iterations():
1695 waited = 0
1696 while not len(bob_w.received_mpp_htlcs) == 10 :
1697 waited += 0.1
1698 await asyncio.sleep(0.1)
1699 if waited > 2:
1700 raise TimeoutError()
1701 nonlocal do_benchmark
1702 do_benchmark = True
1703 while len(iterations) < NUM_ITERATIONS:
1704 await asyncio.sleep(0.05)
1705 # average = sum(iterations) / len(iterations)
1706 median_duration = statistics.median(iterations)
1707 res = f"median duration per htlc switch iteration: {median_duration:.6f}s over {len(iterations)=}"
1708 self.logger.info(res)
1709 self.assertLess(median_duration, 0.02, msg=res)
1710 raise SuccessfulTest()
1711
1712 async def f():
1713 async with OldTaskGroup() as group:
1714 await group.spawn(alice_p._message_loop())
1715 await group.spawn(alice_p.htlc_switch())
1716 await group.spawn(bob_p._message_loop())
1717 await group.spawn(bob_p.htlc_switch())
1718 await asyncio.sleep(0.01)
1719 for _lnaddr, req in invoices:
1720 await group.spawn(alice_w.pay_invoice(req))
1721 await benchmark_htlc_switch_iterations()
1722
1723 with self.assertRaises(SuccessfulTest):
1724 await f()
1725
1726 async def test_dont_expire_htlcs(self):
1727 """
1728 Test that htlcs registered in LNWallet.dont_expire_htlcs don't get expired before the
1729 specified expiry delta if their preimage isn't available.
1730 Also test that htlcs registered in LNWallet.dont_expire_htlcs get settled right away if their
1731 preimage is available.
1732 """
1733 async def run_test(test_trampoline, test_expiry):
1734 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['single_chan'])
1735 p1, p2 = graph.peers.values()
1736 w1, w2 = graph.workers.values()
1737 if test_trampoline:
1738 await self._activate_trampoline(w1)
1739 # declare bob as trampoline node
1740 electrum.trampoline._TRAMPOLINE_NODES_UNITTESTS = {
1741 'bob': LNPeerAddr(host="127.0.0.1", port=9735, pubkey=w2.node_keypair.pubkey),
1742 }
1743
1744 preimage = os.urandom(32)
1745 lnaddr, pay_req = self.prepare_invoice(w2, payment_preimage=preimage, min_final_cltv_delta=144)
1746
1747 # delete preimage, this would fail the htlcs if payment_hash wasn't in dont_expire_htlcs
1748 del w2._preimages[pay_req.rhash]
1749 # add payment_hash to dont_expire_htlcs so the htlcs are not getting failed
1750 w2.dont_expire_htlcs[pay_req.rhash] = None if not test_expiry else 20
1751
1752 async def pay(lnaddr, pay_req):
1753 self.assertEqual(PR_UNPAID, w2.get_payment_status(lnaddr.paymenthash, direction=RECEIVED))
1754 result, log = await util.wait_for2(w1.pay_invoice(pay_req), timeout=3)
1755 if result is True:
1756 self.assertEqual(PR_PAID, w2.get_payment_status(lnaddr.paymenthash, direction=RECEIVED))
1757 return PaymentDone()
1758 else:
1759 self.assertIsNone(w2.get_preimage(lnaddr.paymenthash))
1760 return PaymentFailure()
1761
1762 async def wait_for_htlcs():
1763 payment_key = w2._get_payment_key(lnaddr.paymenthash)
1764 while payment_key.hex() not in w2.received_mpp_htlcs:
1765 await asyncio.sleep(0.05)
1766 if not test_expiry:
1767 # the htlcs should never get expired if the dont_expire_htlcs value is None
1768 w2.network.blockchain()._height += 1000
1769 await asyncio.sleep(0.25) # give w2 some time to do mistakes
1770 self.assertEqual(w2.received_mpp_htlcs[payment_key.hex()].resolution, RecvMPPResolution.COMPLETE)
1771 if test_expiry:
1772 # we set an expiry delta of 20 blocks before expiry, htlc expiry should be +144 current height
1773 # so adding some blocks should get the htlcs failed
1774 w2.network.blockchain()._height += 50
1775 await asyncio.sleep(0.1)
1776 # the htlcs should not get failed yet as 144-50 > 20
1777 self.assertEqual(w2.received_mpp_htlcs[payment_key.hex()].resolution, RecvMPPResolution.COMPLETE)
1778 w2.network.blockchain()._height += 75
1779 return # the htlcs should get failed and pay should return PaymentFailure
1780
1781 # saving the preimage should let the htlcs get fulfilled
1782 w2.save_preimage(lnaddr.paymenthash, preimage)
1783
1784 async def f():
1785 async with OldTaskGroup() as group:
1786 await group.spawn(p1._message_loop())
1787 await group.spawn(p1.htlc_switch())
1788 await group.spawn(p2._message_loop())
1789 await group.spawn(p2.htlc_switch())
1790 await asyncio.sleep(0.01)
1791 invoice_features = lnaddr.get_features()
1792 self.assertFalse(invoice_features.supports(LnFeatures.BASIC_MPP_OPT))
1793 pay_task = await group.spawn(pay(lnaddr, pay_req))
1794 await util.wait_for2(wait_for_htlcs(), timeout=3)
1795 raise await pay_task
1796
1797 await f()
1798
1799 for test_trampoline in [False, True]:
1800 for test_expiry in [False, True]:
1801 with self.assertRaises(PaymentFailure if test_expiry else PaymentDone):
1802 await run_test(test_trampoline, test_expiry )
1803
1804
1805 class TestPeerForwarding(TestPeer):
1806
1807 async def test_payment_in_graph_with_direct_channel(self):
1808 """Test payment over a direct channel where sender has multiple available channels."""
1809 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['line_graph'])
1810 peers = graph.peers.values()
1811 # use same MPP_SPLIT_PART_FRACTION as in regular LNWallet
1812 graph.workers['bob'].MPP_SPLIT_PART_FRACTION = LNWallet.MPP_SPLIT_PART_FRACTION
1813
1814 # mock split_amount_normal so it's possible to test both cases, the amount getting sorted
1815 # out because one part is below the min size and the other case of both parts being just
1816 # above the min size, so no part is getting sorted out
1817 def mocked_split_amount_normal(total_amount: int, num_parts: int) -> List[int]:
1818 if num_parts == 2 and total_amount == 21_000_000: # test amount 21k sat
1819 # this will not get sorted out by suggest_splits
1820 return [10_500_000, 10_500_000]
1821 elif num_parts == 2 and total_amount == 21_000_001: # 2nd test case
1822 # this will get sorted out by suggest_splits
1823 return [11_000_002, 9_999_999]
1824 else:
1825 return split_amount_normal(total_amount, num_parts)
1826
1827 async def pay(lnaddr, pay_req):
1828 self.assertEqual(PR_UNPAID, graph.workers['alice'].get_payment_status(lnaddr.paymenthash, direction=RECEIVED))
1829 with mock.patch('electrum.mpp_split.split_amount_normal',
1830 side_effect=mocked_split_amount_normal):
1831 result, log = await graph.workers['bob'].pay_invoice(pay_req)
1832 self.assertTrue(result)
1833 self.assertEqual(PR_PAID, graph.workers['alice'].get_payment_status(lnaddr.paymenthash, direction=RECEIVED))
1834
1835 async def f():
1836 async with OldTaskGroup() as group:
1837 for peer in peers:
1838 await group.spawn(peer._message_loop())
1839 await group.spawn(peer.htlc_switch())
1840 for peer in peers:
1841 await peer.initialized
1842 for test in [21_000_000, 21_000_001]:
1843 lnaddr, pay_req = self.prepare_invoice(
1844 graph.workers['alice'],
1845 amount_msat=test,
1846 include_routing_hints=True,
1847 invoice_features=LnFeatures.BASIC_MPP_OPT
1848 | LnFeatures.PAYMENT_SECRET_REQ
1849 | LnFeatures.VAR_ONION_REQ
1850 )
1851 await pay(lnaddr, pay_req)
1852 raise PaymentDone()
1853 with self.assertRaises(PaymentDone):
1854 await f()
1855
1856 async def test_payment_multihop(self):
1857 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['square_graph'])
1858 peers = graph.peers.values()
1859 async def pay(lnaddr, pay_req):
1860 self.assertEqual(PR_UNPAID, graph.workers['dave'].get_payment_status(lnaddr.paymenthash, direction=RECEIVED))
1861 result, log = await graph.workers['alice'].pay_invoice(pay_req)
1862 self.assertTrue(result)
1863 self.assertEqual(PR_PAID, graph.workers['dave'].get_payment_status(lnaddr.paymenthash, direction=RECEIVED))
1864 raise PaymentDone()
1865 async def f():
1866 async with OldTaskGroup() as group:
1867 for peer in peers:
1868 await group.spawn(peer._message_loop())
1869 await group.spawn(peer.htlc_switch())
1870 for peer in peers:
1871 await peer.initialized
1872 lnaddr, pay_req = self.prepare_invoice(graph.workers['dave'], include_routing_hints=True)
1873 await group.spawn(pay(lnaddr, pay_req))
1874 with self.assertRaises(PaymentDone):
1875 await f()
1876
1877 async def test_payment_multihop_with_preselected_path(self):
1878 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['square_graph'])
1879 peers = graph.peers.values()
1880 async def pay(pay_req):
1881 with self.subTest(msg="bad path: edges do not chain together"):
1882 path = [PathEdge(start_node=graph.workers['alice'].node_keypair.pubkey,
1883 end_node=graph.workers['carol'].node_keypair.pubkey,
1884 short_channel_id=graph.channels[('alice', 'bob')][0].short_channel_id),
1885 PathEdge(start_node=graph.workers['bob'].node_keypair.pubkey,
1886 end_node=graph.workers['dave'].node_keypair.pubkey,
1887 short_channel_id=graph.channels['bob', 'dave'][0].short_channel_id)]
1888 with self.assertRaises(LNPathInconsistent):
1889 await graph.workers['alice'].pay_invoice(pay_req, full_path=path)
1890 with self.subTest(msg="bad path: last node id differs from invoice pubkey"):
1891 path = [PathEdge(start_node=graph.workers['alice'].node_keypair.pubkey,
1892 end_node=graph.workers['bob'].node_keypair.pubkey,
1893 short_channel_id=graph.channels[('alice', 'bob')][0].short_channel_id)]
1894 with self.assertRaises(LNPathInconsistent):
1895 await graph.workers['alice'].pay_invoice(pay_req, full_path=path)
1896 with self.subTest(msg="good path"):
1897 path = [PathEdge(start_node=graph.workers['alice'].node_keypair.pubkey,
1898 end_node=graph.workers['bob'].node_keypair.pubkey,
1899 short_channel_id=graph.channels[('alice', 'bob')][0].short_channel_id),
1900 PathEdge(start_node=graph.workers['bob'].node_keypair.pubkey,
1901 end_node=graph.workers['dave'].node_keypair.pubkey,
1902 short_channel_id=graph.channels['bob', 'dave'][0].short_channel_id)]
1903 result, log = await graph.workers['alice'].pay_invoice(pay_req, full_path=path)
1904 self.assertTrue(result)
1905 self.assertEqual(
1906 [edge.short_channel_id for edge in path],
1907 [edge.short_channel_id for edge in log[0].route])
1908 raise PaymentDone()
1909 async def f():
1910 async with OldTaskGroup() as group:
1911 for peer in peers:
1912 await group.spawn(peer._message_loop())
1913 await group.spawn(peer.htlc_switch())
1914 for peer in peers:
1915 await peer.initialized
1916 lnaddr, pay_req = self.prepare_invoice(graph.workers['dave'], include_routing_hints=True)
1917 await group.spawn(pay(pay_req))
1918 with self.assertRaises(PaymentDone):
1919 await f()
1920
1921 async def test_payment_multihop_temp_node_failure(self):
1922 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['square_graph'])
1923 graph.workers['bob'].network.config.TEST_FAIL_HTLCS_WITH_TEMP_NODE_FAILURE = True
1924 graph.workers['carol'].network.config.TEST_FAIL_HTLCS_WITH_TEMP_NODE_FAILURE = True
1925 peers = graph.peers.values()
1926 async def pay(lnaddr, pay_req):
1927 self.assertEqual(PR_UNPAID, graph.workers['dave'].get_payment_status(lnaddr.paymenthash, direction=RECEIVED))
1928 result, log = await graph.workers['alice'].pay_invoice(pay_req)
1929 self.assertFalse(result)
1930 self.assertEqual(PR_UNPAID, graph.workers['dave'].get_payment_status(lnaddr.paymenthash, direction=RECEIVED))
1931 self.assertEqual(OnionFailureCode.TEMPORARY_NODE_FAILURE, log[0].failure_msg.code)
1932 raise PaymentDone()
1933 async def f():
1934 async with OldTaskGroup() as group:
1935 for peer in peers:
1936 await group.spawn(peer._message_loop())
1937 await group.spawn(peer.htlc_switch())
1938 for peer in peers:
1939 await peer.initialized
1940 lnaddr, pay_req = self.prepare_invoice(graph.workers['dave'], include_routing_hints=True)
1941 await group.spawn(pay(lnaddr, pay_req))
1942 with self.assertRaises(PaymentDone):
1943 await f()
1944
1945 async def test_payment_multihop_route_around_failure(self):
1946 # Alice will pay Dave. Alice first tries A->C->D route, due to lower fees, but Carol
1947 # will fail the htlc and get blacklisted. Alice will then try A->B->D and succeed.
1948 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['square_graph'])
1949 graph.workers['carol'].network.config.TEST_FAIL_HTLCS_WITH_TEMP_NODE_FAILURE = True
1950 peers = graph.peers.values()
1951 async def pay(lnaddr, pay_req):
1952 self.assertEqual(500000000000, graph.channels[('alice', 'bob')][0].balance(LOCAL))
1953 self.assertEqual(500000000000, graph.channels[('dave', 'bob')][0].balance(LOCAL))
1954 self.assertEqual(PR_UNPAID, graph.workers['dave'].get_payment_status(lnaddr.paymenthash, direction=RECEIVED))
1955 result, log = await graph.workers['alice'].pay_invoice(pay_req, attempts=2)
1956 self.assertEqual(2, len(log))
1957 self.assertTrue(result)
1958 self.assertEqual(PR_PAID, graph.workers['dave'].get_payment_status(lnaddr.paymenthash, direction=RECEIVED))
1959 self.assertEqual([graph.channels[('alice', 'carol')][0].short_channel_id, graph.channels[('carol', 'dave')][0].short_channel_id],
1960 [edge.short_channel_id for edge in log[0].route])
1961 self.assertEqual([graph.channels[('alice', 'bob')][0].short_channel_id, graph.channels[('bob', 'dave')][0].short_channel_id],
1962 [edge.short_channel_id for edge in log[1].route])
1963 self.assertEqual(OnionFailureCode.TEMPORARY_NODE_FAILURE, log[0].failure_msg.code)
1964 self.assertEqual(499899450000, graph.channels[('alice', 'bob')][0].balance(LOCAL))
1965 await asyncio.sleep(0.2) # wait for COMMITMENT_SIGNED / REVACK msgs to update balance
1966 self.assertEqual(500100000000, graph.channels[('dave', 'bob')][0].balance(LOCAL))
1967 raise PaymentDone()
1968 async def f():
1969 async with OldTaskGroup() as group:
1970 for peer in peers:
1971 await group.spawn(peer._message_loop())
1972 await group.spawn(peer.htlc_switch())
1973 for peer in peers:
1974 await peer.initialized
1975 lnaddr, pay_req = self.prepare_invoice(graph.workers['dave'], include_routing_hints=True)
1976 invoice_features = lnaddr.get_features()
1977 self.assertFalse(invoice_features.supports(LnFeatures.BASIC_MPP_OPT))
1978 await group.spawn(pay(lnaddr, pay_req))
1979 with self.assertRaises(PaymentDone):
1980 await f()
1981
1982 async def test_refuse_to_forward_htlc_that_corresponds_to_payreq_we_created(self):
1983 # This test checks that the following attack does not work:
1984 # - Bob creates payment request with HASH1, for 1 BTC; and gives the payreq to Alice
1985 # - Alice sends htlc A->B->D, for 100k sat, with HASH1
1986 # - Bob must not release the preimage of HASH1
1987 graph_def = self.GRAPH_DEFINITIONS['square_graph']
1988 graph_def.pop('carol')
1989 graph_def['alice']['channels'].pop('carol')
1990 # now graph is linear: A <-> B <-> D
1991 graph = self.prepare_chans_and_peers_in_graph(graph_def)
1992 peers = graph.peers.values()
1993 async def pay():
1994 lnaddr1, pay_req1 = self.prepare_invoice(
1995 graph.workers['bob'],
1996 amount_msat=100_000_000_000,
1997 )
1998 lnaddr2, pay_req2 = self.prepare_invoice(
1999 graph.workers['dave'],
2000 amount_msat=100_000_000,
2001 payment_hash=lnaddr1.paymenthash, # Dave is cooperating with Alice, and he reuses Bob's hash
2002 include_routing_hints=True,
2003 )
2004 with self.subTest(msg="try to make Bob forward in legacy (non-trampoline) mode"):
2005 result, log = await graph.workers['alice'].pay_invoice(pay_req2, attempts=1)
2006 self.assertFalse(result)
2007 self.assertEqual(OnionFailureCode.TEMPORARY_NODE_FAILURE, log[0].failure_msg.code)
2008 self.assertEqual(None, graph.workers['alice'].get_preimage(lnaddr1.paymenthash))
2009 with self.subTest(msg="try to make Bob forward in trampoline mode"):
2010 # declare Bob as trampoline forwarding node
2011 electrum.trampoline._TRAMPOLINE_NODES_UNITTESTS = {
2012 graph.workers['bob'].name: LNPeerAddr(host="127.0.0.1", port=9735, pubkey=graph.workers['bob'].node_keypair.pubkey),
2013 }
2014 await self._activate_trampoline(graph.workers['alice'])
2015 result, log = await graph.workers['alice'].pay_invoice(pay_req2, attempts=5)
2016 self.assertFalse(result)
2017 self.assertEqual(OnionFailureCode.TEMPORARY_NODE_FAILURE, log[0].failure_msg.code)
2018 self.assertEqual(None, graph.workers['alice'].get_preimage(lnaddr1.paymenthash))
2019 raise SuccessfulTest()
2020
2021 async def f():
2022 async with OldTaskGroup() as group:
2023 for peer in peers:
2024 await group.spawn(peer._message_loop())
2025 await group.spawn(peer.htlc_switch())
2026 for peer in peers:
2027 await peer.initialized
2028 await group.spawn(pay())
2029
2030 with self.assertRaises(SuccessfulTest):
2031 await f()
2032
2033 async def test_payment_with_temp_channel_failure_and_liquidity_hints(self):
2034 # prepare channels such that a temporary channel failure happens at c->d
2035 graph_definition = self.GRAPH_DEFINITIONS['square_graph']
2036 graph_definition['alice']['channels']['carol'][0]['local_balance_msat'] = 200_000_000
2037 graph_definition['alice']['channels']['carol'][0]['remote_balance_msat'] = 200_000_000
2038 graph_definition['carol']['channels']['dave'][0]['local_balance_msat'] = 50_000_000
2039 graph_definition['carol']['channels']['dave'][0]['remote_balance_msat'] = 200_000_000
2040 graph_definition['alice']['channels']['bob'][0]['local_balance_msat'] = 200_000_000
2041 graph_definition['alice']['channels']['bob'][0]['remote_balance_msat'] = 200_000_000
2042 graph_definition['bob']['channels']['dave'][0]['local_balance_msat'] = 200_000_000
2043 graph_definition['bob']['channels']['dave'][0]['remote_balance_msat'] = 200_000_000
2044 graph = self.prepare_chans_and_peers_in_graph(graph_definition)
2045
2046 # the payment happens in two attempts:
2047 # 1. along a->c->d due to low fees with temp channel failure:
2048 # with chanupd: ORPHANED, private channel update
2049 # c->d gets a liquidity hint and gets blocked
2050 # 2. along a->b->d with success
2051 amount_to_pay = 100_000_000
2052 peers = graph.peers.values()
2053 async def pay(lnaddr, pay_req):
2054 self.assertEqual(PR_UNPAID, graph.workers['dave'].get_payment_status(lnaddr.paymenthash, direction=RECEIVED))
2055 result, log = await graph.workers['alice'].pay_invoice(pay_req, attempts=3)
2056 self.assertTrue(result)
2057 self.assertEqual(2, len(log))
2058 self.assertEqual(PR_PAID, graph.workers['dave'].get_payment_status(lnaddr.paymenthash, direction=RECEIVED))
2059 self.assertEqual(OnionFailureCode.TEMPORARY_CHANNEL_FAILURE, log[0].failure_msg.code)
2060
2061 liquidity_hints = graph.workers['alice'].network.path_finder.liquidity_hints
2062 pubkey_a = graph.workers['alice'].node_keypair.pubkey
2063 pubkey_b = graph.workers['bob'].node_keypair.pubkey
2064 pubkey_c = graph.workers['carol'].node_keypair.pubkey
2065 pubkey_d = graph.workers['dave'].node_keypair.pubkey
2066 # check liquidity hints for failing route:
2067 hint_ac = liquidity_hints.get_hint(graph.channels[('alice', 'carol')][0].short_channel_id)
2068 hint_cd = liquidity_hints.get_hint(graph.channels[('carol', 'dave')][0].short_channel_id)
2069 self.assertEqual(amount_to_pay, hint_ac.can_send(pubkey_a < pubkey_c))
2070 self.assertEqual(None, hint_ac.cannot_send(pubkey_a < pubkey_c))
2071 self.assertEqual(None, hint_cd.can_send(pubkey_c < pubkey_d))
2072 self.assertEqual(amount_to_pay, hint_cd.cannot_send(pubkey_c < pubkey_d))
2073 # check liquidity hints for successful route:
2074 hint_ab = liquidity_hints.get_hint(graph.channels[('alice', 'bob')][0].short_channel_id)
2075 hint_bd = liquidity_hints.get_hint(graph.channels[('bob', 'dave')][0].short_channel_id)
2076 self.assertEqual(amount_to_pay, hint_ab.can_send(pubkey_a < pubkey_b))
2077 self.assertEqual(None, hint_ab.cannot_send(pubkey_a < pubkey_b))
2078 self.assertEqual(amount_to_pay, hint_bd.can_send(pubkey_b < pubkey_d))
2079 self.assertEqual(None, hint_bd.cannot_send(pubkey_b < pubkey_d))
2080
2081 raise PaymentDone()
2082 async def f():
2083 async with OldTaskGroup() as group:
2084 for peer in peers:
2085 await group.spawn(peer._message_loop())
2086 await group.spawn(peer.htlc_switch())
2087 for peer in peers:
2088 await peer.initialized
2089 lnaddr, pay_req = self.prepare_invoice(graph.workers['dave'], amount_msat=amount_to_pay, include_routing_hints=True)
2090 await group.spawn(pay(lnaddr, pay_req))
2091 with self.assertRaises(PaymentDone):
2092 await f()
2093
2094 async def _assert_no_inflight_htlcs_in_liquidity_hints(self, w: MockLNWallet):
2095 # pay_invoice returns when the first htlc resolution is processed; the remaining
2096 # parts resolve later. only when all parts have resolved is the paysession removed.
2097 async def wait_for_paysessions_to_be_cleaned_up():
2098 while w._paysessions:
2099 await asyncio.sleep(0.01)
2100 await util.wait_for2(wait_for_paysessions_to_be_cleaned_up(), timeout=10)
2101 for hint in w.network.path_finder.liquidity_hints._liquidity_hints.values():
2102 self.assertEqual(0, hint.num_inflight_htlcs(True))
2103 self.assertEqual(0, hint.num_inflight_htlcs(False))
2104
2105 def _assert_all_parts_reported_can_send(self, w: MockLNWallet):
2106 # every part of the mpp resolved successfully, so every edge an htlc was
2107 # sent over should have received a can_send report for its direction of use
2108 for hint in w.network.path_finder.liquidity_hints._liquidity_hints.values():
2109 self.assertTrue(hint.can_send(True) is not None or hint.can_send(False) is not None)
2110
2111 async def _run_mpp(self, graph, kwargs):
2112 """Tests a multipart payment scenario for failing and successful cases."""
2113 self.assertEqual(500_000_000_000, graph.channels[('alice', 'bob')][0].balance(LOCAL))
2114 self.assertEqual(500_000_000_000, graph.channels[('alice', 'carol')][0].balance(LOCAL))
2115 amount_to_pay = 600_000_000_000
2116 peers = graph.peers.values()
2117 async def pay(
2118 attempts=1,
2119 alice_uses_trampoline=False,
2120 bob_forwarding=True,
2121 mpp_invoice=True,
2122 disable_trampoline_receiving=False,
2123 test_hold_invoice=False,
2124 test_failure=False,
2125 ):
2126 alice_w = graph.workers['alice']
2127 bob_w = graph.workers['bob']
2128 carol_w = graph.workers['carol']
2129 dave_w = graph.workers['dave']
2130 if mpp_invoice:
2131 dave_w.features |= LnFeatures.BASIC_MPP_OPT
2132 if disable_trampoline_receiving:
2133 dave_w.features &= ~LnFeatures.OPTION_TRAMPOLINE_ROUTING_OPT_ELECTRUM
2134 if not bob_forwarding:
2135 bob_w.enable_htlc_forwarding = False
2136 if alice_uses_trampoline:
2137 await self._activate_trampoline(alice_w)
2138 else:
2139 assert alice_w.network.channel_db is not None
2140 lnaddr, pay_req = self.prepare_invoice(dave_w, include_routing_hints=True, amount_msat=amount_to_pay)
2141 self.prepare_recipient(dave_w, lnaddr.paymenthash, test_hold_invoice, test_failure)
2142 self.assertEqual(PR_UNPAID, dave_w.get_payment_status(lnaddr.paymenthash, direction=RECEIVED))
2143 result, log = await alice_w.pay_invoice(pay_req, attempts=attempts)
2144 if not bob_forwarding:
2145 # reset to previous state, sleep 2s so that the second htlc can time out
2146 graph.workers['bob'].enable_htlc_forwarding = True
2147 await asyncio.sleep(2)
2148 if result:
2149 self.assertEqual(PR_PAID, dave_w.get_payment_status(lnaddr.paymenthash, direction=RECEIVED))
2150 # check mpp is cleaned up
2151 async with OldTaskGroup() as g:
2152 for peer in peers:
2153 await g.spawn(peer.wait_one_htlc_switch_iteration())
2154 # wait another iteration
2155 async with OldTaskGroup() as g:
2156 for peer in peers:
2157 await g.spawn(peer.wait_one_htlc_switch_iteration())
2158 for peer in peers:
2159 self.assertEqual(len(peer.lnworker.received_mpp_htlcs), 0)
2160 await self._assert_no_inflight_htlcs_in_liquidity_hints(alice_w)
2161 self._assert_all_parts_reported_can_send(alice_w)
2162 raise PaymentDone()
2163 elif len(log) == 1 and log[0].failure_msg.code == OnionFailureCode.MPP_TIMEOUT:
2164 await self._assert_no_inflight_htlcs_in_liquidity_hints(alice_w)
2165 raise PaymentTimeout()
2166 else:
2167 raise NoPathFound()
2168
2169 async with OldTaskGroup() as group:
2170 for peer in peers:
2171 await group.spawn(peer._message_loop())
2172 await group.spawn(peer.htlc_switch())
2173 for peer in peers:
2174 await peer.initialized
2175 await group.spawn(pay(**kwargs))
2176
2177 async def test_payment_multipart(self):
2178 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['square_graph'])
2179 with self.assertRaises(PaymentDone):
2180 await self._run_mpp(graph, {})
2181
2182 async def test_payment_multipart_with_hold_invoice(self):
2183 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['square_graph'])
2184 with self.assertRaises(PaymentDone):
2185 await self._run_mpp(graph, {'test_hold_invoice': True})
2186
2187 async def test_payment_multipart_with_timeout(self):
2188 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['square_graph'])
2189 with self.assertRaises(PaymentTimeout):
2190 await self._run_mpp(graph, {'bob_forwarding': False})
2191
2192 async def test_payment_multipart_wrong_invoice(self):
2193 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['square_graph'])
2194 with self.assertRaises(NoPathFound):
2195 await self._run_mpp(graph, {'mpp_invoice': False})
2196
2197 async def test_payment_multipart_fee_budget(self):
2198 """The fee budget must be shared between the parts of an MPP payment: each part
2199 is checked with its part amount against its share of the budget, so that the
2200 aggregate fee over all parts cannot exceed the budget."""
2201 graph_def = self.GRAPH_DEFINITIONS['square_graph']
2202 # use base-fee-dominated routing fees, so each part pays the full base fee
2203 # and the aggregate fee doubles when the payment is split into two parts
2204 base_fee_msat = 1_000_000
2205 for node in ('bob', 'carol'):
2206 graph_def[node]['channels']['dave'][0].update({'local_base_fee_msat': base_fee_msat, 'local_fee_rate_millionths': 0})
2207 graph = self.prepare_chans_and_peers_in_graph(graph_def)
2208 amount_to_pay = 600_000_000_000 # exceeds single channel capacity
2209 alice_w, dave_w = graph.workers['alice'], graph.workers['dave']
2210 dave_w.features |= LnFeatures.BASIC_MPP_OPT
2211 self.assertFalse(alice_w.uses_trampoline())
2212 peers = graph.peers.values()
2213 async def pay(fee_budget_msat: int) -> bool:
2214 lnaddr, pay_req = self.prepare_invoice(dave_w, include_routing_hints=True, amount_msat=amount_to_pay)
2215 budget = PaymentFeeBudget.from_invoice_amount(invoice_amount_msat=amount_to_pay, config=alice_w.config, max_fee_msat=fee_budget_msat)
2216 result, log = await alice_w.pay_invoice(pay_req, attempts=1, budget=budget)
2217 return result
2218 async def f():
2219 async with OldTaskGroup() as group:
2220 for peer in peers:
2221 await group.spawn(peer._message_loop())
2222 await group.spawn(peer.htlc_switch())
2223 for peer in peers:
2224 await peer.initialized
2225 # a budget covering one part's base fee but not both must fail the payment
2226 self.assertFalse(await pay(fee_budget_msat=base_fee_msat * 3 // 2))
2227 # a budget covering the base fee of both parts must succeed
2228 self.assertTrue(await pay(fee_budget_msat=base_fee_msat * 2))
2229 raise PaymentDone()
2230 with self.assertRaises(PaymentDone):
2231 await f()
2232
2233 async def test_payment_multipart_trampoline_e2e(self):
2234 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['square_graph'])
2235 electrum.trampoline._TRAMPOLINE_NODES_UNITTESTS = {
2236 graph.workers['bob'].name: LNPeerAddr(host="127.0.0.1", port=9735, pubkey=graph.workers['bob'].node_keypair.pubkey),
2237 graph.workers['carol'].name: LNPeerAddr(host="127.0.0.1", port=9735, pubkey=graph.workers['carol'].node_keypair.pubkey),
2238 }
2239 with self.assertRaises(PaymentDone):
2240 await self._run_mpp(graph,{'alice_uses_trampoline': True, 'attempts': 1})
2241
2242 async def test_payment_multipart_trampoline_legacy(self):
2243 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['square_graph'])
2244 electrum.trampoline._TRAMPOLINE_NODES_UNITTESTS = {
2245 graph.workers['bob'].name: LNPeerAddr(host="127.0.0.1", port=9735, pubkey=graph.workers['bob'].node_keypair.pubkey),
2246 graph.workers['carol'].name: LNPeerAddr(host="127.0.0.1", port=9735, pubkey=graph.workers['carol'].node_keypair.pubkey),
2247 }
2248 # trampoline-to-legacy: this is restricted, as there are no forwarders capable of doing this
2249 with self.assertRaises(NoPathFound):
2250 await self._run_mpp(graph, {'alice_uses_trampoline': True, 'attempts': 30, 'disable_trampoline_receiving': True})
2251
2252 async def test_fail_pending_htlcs_on_shutdown(self):
2253 """Alice tries to pay Dave via MPP. Dave receives some HTLCs but not all.
2254 Dave shuts down (stops wallet).
2255 We test if Dave fails the pending HTLCs during shutdown.
2256 """
2257 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['square_graph'])
2258 self.assertEqual(500_000_000_000, graph.channels[('alice', 'bob')][0].balance(LOCAL))
2259 self.assertEqual(500_000_000_000, graph.channels[('alice', 'carol')][0].balance(LOCAL))
2260 amount_to_pay = 600_000_000_000
2261 peers = graph.peers.values()
2262 graph.workers['dave'].MPP_EXPIRY = 120
2263 graph.workers['dave'].TIMEOUT_SHUTDOWN_FAIL_PENDING_HTLCS = 3
2264 async def pay():
2265 graph.workers['dave'].features |= LnFeatures.BASIC_MPP_OPT
2266 graph.workers['bob'].enable_htlc_forwarding = False # Bob will hold forwarded HTLCs
2267 assert graph.workers['alice'].network.channel_db is not None
2268 lnaddr, pay_req = self.prepare_invoice(graph.workers['dave'], include_routing_hints=True, amount_msat=amount_to_pay)
2269 result, log = await graph.workers['alice'].pay_invoice(pay_req, attempts=1)
2270 async def stop():
2271 hm = graph.channels[('dave', 'carol')][0].hm
2272 while len(hm.htlcs(LOCAL)) == 0 or len(hm.htlcs(REMOTE)) == 0:
2273 await asyncio.sleep(0.1)
2274 self.assertTrue(len(hm.htlcs(LOCAL)) > 0)
2275 self.assertTrue(len(hm.htlcs(REMOTE)) > 0)
2276 await graph.workers['dave'].stop()
2277 # Dave is supposed to have failed the pending incomplete MPP HTLCs
2278 self.assertEqual(0, len(hm.htlcs(LOCAL)))
2279 self.assertEqual(0, len(hm.htlcs(REMOTE)))
2280 raise SuccessfulTest()
2281
2282 async def f():
2283 async with OldTaskGroup() as group:
2284 for peer in peers:
2285 await group.spawn(peer._message_loop())
2286 await group.spawn(peer.htlc_switch())
2287 for peer in peers:
2288 await peer.initialized
2289 await group.spawn(pay())
2290 await group.spawn(stop())
2291
2292 with self.assertRaises(SuccessfulTest):
2293 await f()
2294
2295 async def _run_trampoline_payment(
2296 self, graph: 'Graph', *,
2297 include_routing_hints=True,
2298 test_hold_invoice=False,
2299 test_failure=False,
2300 attempts=2,
2301 sender_name="alice",
2302 destination_name="dave",
2303 trampoline_forwarders=("bob", "carol"),
2304 trampoline_users=(), # sender is also a trampoline user
2305 ):
2306
2307 sender_w = graph.workers[sender_name]
2308 dest_w = graph.workers[destination_name]
2309
2310 async def pay(lnaddr, pay_req):
2311 self.assertEqual(PR_UNPAID, dest_w.get_payment_status(lnaddr.paymenthash, direction=RECEIVED))
2312 result, log = await sender_w.pay_invoice(pay_req, attempts=attempts)
2313 async with OldTaskGroup() as g:
2314 for peer in peers:
2315 await g.spawn(peer.wait_one_htlc_switch_iteration())
2316 async with OldTaskGroup() as g:
2317 for peer in peers:
2318 await g.spawn(peer.wait_one_htlc_switch_iteration())
2319 for peer in peers:
2320 self.assertEqual(len(peer.lnworker.active_forwardings), 0)
2321 if result:
2322 self.assertEqual(PR_PAID, dest_w.get_payment_status(lnaddr.paymenthash, direction=RECEIVED))
2323 raise PaymentDone()
2324 else:
2325 raise NoPathFound()
2326
2327 async def f():
2328 await self._activate_trampoline(sender_w)
2329 async with OldTaskGroup() as group:
2330 for peer in peers:
2331 await group.spawn(peer._message_loop())
2332 await group.spawn(peer.htlc_switch())
2333 for peer in peers:
2334 await peer.initialized
2335 lnaddr, pay_req = self.prepare_invoice(dest_w, include_routing_hints=include_routing_hints)
2336 self.prepare_recipient(dest_w, lnaddr.paymenthash, test_hold_invoice, test_failure)
2337 await group.spawn(pay(lnaddr, pay_req))
2338
2339 peers = graph.peers.values()
2340
2341 # declare routing nodes as trampoline nodes
2342 electrum.trampoline._TRAMPOLINE_NODES_UNITTESTS = {}
2343 for name in trampoline_forwarders:
2344 user_w = graph.workers[name]
2345 user_w.config.EXPERIMENTAL_LN_FORWARD_TRAMPOLINE_PAYMENTS = True
2346 peer_addr = LNPeerAddr(host="127.0.0.1", port=9735, pubkey=user_w.node_keypair.pubkey)
2347 electrum.trampoline._TRAMPOLINE_NODES_UNITTESTS[user_w.name] = peer_addr
2348
2349 for user in trampoline_users:
2350 user_w = graph.workers[user]
2351 await self._activate_trampoline(user_w)
2352 assert user_w.uses_trampoline()
2353
2354 await f()
2355
2356 def create_square_graph(self, *, direct=False, test_mpp_consolidation=False, is_legacy=False):
2357 graph_definition = self.GRAPH_DEFINITIONS['square_graph']
2358 if not direct:
2359 # deplete channel from alice to carol and from bob to dave
2360 graph_definition['alice']['channels']['carol'] = [depleted_channel]
2361 graph_definition['bob']['channels']['dave'] = [depleted_channel]
2362 # insert a channel from bob to carol
2363 graph_definition['bob']['channels']['carol'] = [low_fee_channel]
2364 # now the only route possible is alice -> bob -> carol -> dave
2365 if test_mpp_consolidation:
2366 # deplete alice to carol so that all htlcs go through bob
2367 graph_definition['alice']['channels']['carol'] = [depleted_channel]
2368 graph = self.prepare_chans_and_peers_in_graph(graph_definition)
2369 if test_mpp_consolidation:
2370 graph.workers['dave'].features |= LnFeatures.BASIC_MPP_OPT
2371 graph.workers['alice'].network.config.TEST_FORCE_MPP = True # trampoline must wait until all incoming htlcs are received before sending outgoing htlcs
2372 graph.workers['bob'].network.config.TEST_FORCE_MPP = True # trampoline must wait until all outgoing htlcs have failed before failing incoming htlcs
2373 if is_legacy:
2374 # turn off trampoline features in invoice
2375 graph.workers['dave'].features = graph.workers['dave'].features ^ LnFeatures.OPTION_TRAMPOLINE_ROUTING_OPT_ELECTRUM
2376 return graph
2377
2378 async def test_trampoline_mpp_consolidation(self):
2379 with self.assertRaises(PaymentDone):
2380 graph = self.create_square_graph(direct=False, test_mpp_consolidation=True, is_legacy=True)
2381 await self._run_trampoline_payment(graph)
2382
2383 async def test_trampoline_mpp_consolidation_forwarding_amount(self):
2384 """sanity check that bob is forwarding less than he is receiving"""
2385 # alice->bob->carol->dave
2386 graph = self.create_square_graph(direct=False, test_mpp_consolidation=True, is_legacy=True)
2387 # bump alices trampoline fee level so the first payment succeeds and the htlc sums can be compared usefully below.
2388 alice = graph.workers['alice']
2389 alice.config.INITIAL_TRAMPOLINE_FEE_LEVEL = 6
2390 with self.assertRaises(PaymentDone):
2391 await self._run_trampoline_payment(graph, attempts=1)
2392
2393 # assert bob hasn't forwarded more than he received
2394 bob_alice_channel = graph.channels[('bob', 'alice')][0]
2395 htlcs_bob_received_from_alice = bob_alice_channel.hm.all_htlcs_ever()
2396 bob_carol_channel = graph.channels[('bob', 'carol')][0]
2397 htlcs_bob_sent_to_carol = bob_carol_channel.hm.all_htlcs_ever()
2398 sum_bob_received = sum(htlc.amount_msat for (direction, htlc) in htlcs_bob_received_from_alice)
2399 sum_bob_sent = sum(htlc.amount_msat for (direction, htlc) in htlcs_bob_sent_to_carol)
2400 assert sum_bob_sent < sum_bob_received, f"{sum_bob_sent=} > {sum_bob_received=}"
2401
2402 async def test_trampoline_mpp_consolidation_with_hold_invoice(self):
2403 with self.assertRaises(PaymentDone):
2404 graph = self.create_square_graph(direct=False, test_mpp_consolidation=True, is_legacy=True)
2405 await self._run_trampoline_payment(graph, test_hold_invoice=True)
2406
2407 async def test_trampoline_mpp_consolidation_with_hold_invoice_failure(self):
2408 with self.assertRaises(NoPathFound):
2409 graph = self.create_square_graph(direct=False, test_mpp_consolidation=True, is_legacy=True)
2410 await self._run_trampoline_payment(graph, test_hold_invoice=True, test_failure=True)
2411
2412 async def test_payment_trampoline_legacy(self):
2413 # alice -> T1_bob -> carol -> dave
2414 with self.assertRaises(PaymentDone):
2415 graph = self.create_square_graph(direct=False, is_legacy=True)
2416 await self._run_trampoline_payment(graph, include_routing_hints=True)
2417 with self.assertRaises(NoPathFound):
2418 graph = self.create_square_graph(direct=False, is_legacy=True)
2419 await self._run_trampoline_payment(graph, include_routing_hints=False)
2420
2421 async def test_payment_trampoline_e2e_alice_t1_dave(self):
2422 with self.assertRaises(PaymentDone):
2423 graph = self.create_square_graph(direct=True, is_legacy=False)
2424 await self._run_trampoline_payment(graph)
2425
2426 async def test_payment_trampoline_e2e_alice_t1_t2_dave(self):
2427 with self.assertRaises(PaymentDone):
2428 graph = self.create_square_graph(direct=False, is_legacy=False)
2429 await self._run_trampoline_payment(graph)
2430
2431 async def test_payment_trampoline_e2e_alice_t1_carol_t2_edward(self):
2432 # alice -> T1_bob -> carol -> T2_dave -> edward
2433 graph_definition = self.GRAPH_DEFINITIONS['line_graph']
2434 graph = self.prepare_chans_and_peers_in_graph(graph_definition)
2435 inject_chan_into_gossipdb(
2436 channel_db=graph.workers['bob'].channel_db,
2437 chanAB=graph.channels[('carol', 'dave')][0],
2438 chanBA=graph.channels[('dave', 'carol')][0],
2439 )
2440 # end-to-end trampoline: we attempt
2441 # * a payment with one trial: fails, because initial fees are too low
2442 # * a payment with several trials: should succeed
2443 with self.assertRaises(NoPathFound):
2444 await self._run_trampoline_payment(
2445 graph, sender_name='alice',
2446 destination_name='edward',
2447 trampoline_forwarders=('bob', 'dave'),
2448 attempts=1,
2449 )
2450 with self.assertRaises(PaymentDone):
2451 await self._run_trampoline_payment(
2452 graph, sender_name='alice',
2453 destination_name='edward',
2454 trampoline_forwarders=('bob', 'dave'),
2455 attempts=2,
2456 )
2457
2458 async def test_payment_trampoline_e2e_lazy(self):
2459 # alice -> T1_bob -> T2_carol -> T3_dave -> edward
2460 graph_definition = self.GRAPH_DEFINITIONS['line_graph']
2461 graph = self.prepare_chans_and_peers_in_graph(graph_definition)
2462 with self.assertRaises(NoPathFound):
2463 await self._run_trampoline_payment(
2464 graph, sender_name='alice',
2465 destination_name='edward',
2466 trampoline_forwarders=('bob', 'dave'),
2467 trampoline_users=('alice', 'bob'),
2468 attempts=3, # fails with only 2
2469 )
2470 with self.assertRaises(PaymentDone):
2471 await self._run_trampoline_payment(
2472 graph, sender_name='alice',
2473 destination_name='edward',
2474 trampoline_forwarders=('bob', 'carol', 'dave'),
2475 trampoline_users=('alice', 'bob'),
2476 attempts=3, # fails with only 2
2477 )
2478
2479 async def test_multi_trampoline_payment(self):
2480 """
2481 Alice splits her payment to Dave between two trampoline forwarding nodes Carol and Bob.
2482 This should test Multi-Trampoline MPP:
2483 https://github.com/lightning/bolts/blob/bc7a1a0bc97b2293e7f43dd8a06529e5fdcf7cd2/proposals/trampoline.md#multi-trampoline-mpp
2484 """
2485 graph_definition = self.GRAPH_DEFINITIONS['square_graph']
2486 # payment amount is 100_000_000 msat, size the channels so that alice must use both to succeed
2487 graph_definition['alice']['channels']['bob'][0]['local_balance_msat'] = int(100_000_000 * 0.75)
2488 graph_definition['alice']['channels']['carol'][0]['local_balance_msat'] = int(100_000_000 * 0.75)
2489 g = self.prepare_chans_and_peers_in_graph(graph_definition)
2490 w = g.workers['alice'], g.workers['carol'], g.workers['bob'], g.workers['dave']
2491 alice_w, carol_w, bob_w, dave_w = w
2492
2493 alice_w.config.TEST_FORCE_MPP = True
2494 bob_w.config.TEST_FORCE_MPP = True
2495 carol_w.config.TEST_FORCE_MPP = True
2496 dave_w.features |= LnFeatures.BASIC_MPP_OPT
2497
2498 with self.assertRaises(PaymentDone):
2499 await self._run_trampoline_payment(
2500 g,
2501 sender_name='alice',
2502 destination_name='dave',
2503 trampoline_forwarders=('bob', 'carol'),
2504 attempts=30, # the default used in LNWallet.pay_invoice()
2505 )
2506
2507 async def test_forwarder_fails_for_inconsistent_trampoline_onions(self):
2508 """
2509 verify that the receiver of a trampoline forwarding fails the mpp set
2510 if the trampoline onions are not similar
2511 In this test alice tries to forward through bob, however in one trampoline onion she sends
2512 amt_to_forward is off by one msat. Bob should compare the trampoline onions and fail the set.
2513 """
2514
2515 # store a modified trampoline onion to be injected into lnworker.new_onion_packet later when sending the htlcs
2516 modified_trampoline_onion = None
2517 def modified_new_onion_packet_trampoline(payment_path_pubkeys, session_key, hops_data: List[OnionHopsDataSingle], **kwargs):
2518 nonlocal modified_trampoline_onion
2519 assert modified_trampoline_onion is None, "this mock should get called only once"
2520 modified_hops_data = copy.copy(hops_data)
2521 # first payload (i[0]) is for bob who is supposed to forward the trampoline payment, in this
2522 # test he should fail the incoming htlcs as their trampolines are not similar
2523 new_payload = dict(modified_hops_data[0].payload)
2524 amt_to_forward = dict(new_payload['amt_to_forward'])
2525 amt_to_forward['amt_to_forward'] -= 1
2526 new_payload['amt_to_forward'] = amt_to_forward
2527 modified_hops_data[0] = dataclasses.replace(modified_hops_data[0], payload=new_payload)
2528 self.logger.debug(f"{modified_hops_data=}\nsent_{hops_data=}")
2529 modified_trampoline_onion = electrum.lnonion.new_onion_packet(
2530 payment_path_pubkeys,
2531 session_key,
2532 modified_hops_data,
2533 **kwargs
2534 )
2535 # return the unmodified onion
2536 return electrum.lnonion.new_onion_packet(
2537 payment_path_pubkeys,
2538 session_key,
2539 hops_data,
2540 **kwargs
2541 )
2542
2543 # this gets called in lnworker per sent htlc, for one sent htlc we inject the modified trampoline
2544 # onion created before in the mock above
2545 def modified_new_onion_packet_lnworker(payment_path_pubkeys, session_key, hops_data: List[OnionHopsDataSingle], **kwargs):
2546 nonlocal modified_trampoline_onion
2547 hops_data = copy.copy(hops_data)
2548 if modified_trampoline_onion:
2549 assert isinstance(modified_trampoline_onion, OnionPacket)
2550 assert len(hops_data) == 1
2551 new_payload = dict(hops_data[0].payload)
2552 new_payload['trampoline_onion_packet'] = {
2553 "trampoline_onion_packet": modified_trampoline_onion.to_bytes()
2554 }
2555 hops_data[0] = dataclasses.replace(hops_data[0], payload=MappingProxyType(new_payload))
2556 modified_trampoline_onion = None
2557 return electrum.lnonion.new_onion_packet(
2558 payment_path_pubkeys,
2559 session_key,
2560 hops_data,
2561 **kwargs
2562 )
2563
2564 graph = self.create_square_graph(direct=False, test_mpp_consolidation=True, is_legacy=True)
2565 alice = graph.workers['alice']
2566 alice.config.INITIAL_TRAMPOLINE_FEE_LEVEL = 6 # set high so the first attempt would succeed
2567 with self.assertRaises(PaymentFailure):
2568 with mock.patch('electrum.trampoline.new_onion_packet', side_effect=modified_new_onion_packet_trampoline), \
2569 mock.patch('electrum.lnworker.new_onion_packet', side_effect=modified_new_onion_packet_lnworker):
2570 await self._run_trampoline_payment(graph, attempts=1)
2571 bob_alice_channel = graph.channels[('bob', 'alice')][0]
2572 bob_hm = bob_alice_channel.hm
2573 assert len(bob_hm.all_htlcs_ever()) == 2
2574 assert all(bob_hm.was_htlc_failed(htlc_id=htlc.htlc_id, htlc_proposer=HTLCOwner.REMOTE) for (_, htlc) in bob_hm.all_htlcs_ever())
2575
2576 async def test_payment_with_malformed_onion(self):
2577 """
2578 Alice -> Bob -> Carol. Carol fails htlc with update_fail_malformed_htlc because she is unable
2579 to parse the onion Alice sent to her.
2580 """
2581 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['line_graph'])
2582 peers = graph.peers.values()
2583
2584 async def pay(lnaddr, pay_req):
2585 self.assertEqual(PR_UNPAID, graph.workers['carol'].get_payment_status(lnaddr.paymenthash, direction=RECEIVED))
2586 result, log = await graph.workers['alice'].pay_invoice(pay_req)
2587 self.assertEqual(OnionFailureCode.INVALID_ONION_VERSION, log[0].failure_msg.code)
2588 self.assertFalse(result, msg=log)
2589 raise PaymentFailure()
2590
2591 # this will make carol send update_fail_malformed_htlc
2592 graph.workers['carol'].config.TEST_FAIL_HTLCS_AS_MALFORMED = True
2593
2594 async def f():
2595 async with OldTaskGroup() as group:
2596 for peer in peers:
2597 await group.spawn(peer._message_loop())
2598 await group.spawn(peer.htlc_switch())
2599 for peer in peers:
2600 await peer.initialized
2601 lnaddr, pay_req = self.prepare_invoice(graph.workers['carol'], include_routing_hints=True)
2602 await group.spawn(pay(lnaddr, pay_req))
2603
2604 with self.assertLogs('electrum', level='INFO') as logs:
2605 with self.assertRaises(PaymentFailure):
2606 await f()
2607 self.assertTrue(
2608 any('carol->bob' in msg and 'fail_malformed_htlc' in msg for msg in logs.output)
2609 )
2610 self.assertTrue(
2611 any('bob->carol' in msg and 'on_update_fail_malformed_htlc' in msg for msg in logs.output)
2612 )
2613
2614 async def test_dont_settle_htlcs_receiver_and_forwarder(self):
2615 """
2616 Test that the receiver and forwarder doesn't settle htlcs once they get the preimage if the payment
2617 hash is in LNWallet.dont_settle_htlcs. E.g. the forwarder could be a just-in-time channel provider.
2618 Alice -> Bob -> Carol. Carol and Bob shouldn't release the preimage.
2619 """
2620 async def run_test(test_trampoline):
2621 graph = self.prepare_chans_and_peers_in_graph(self.GRAPH_DEFINITIONS['line_graph'])
2622 peers = graph.peers.values()
2623
2624 if test_trampoline:
2625 # trampoline forwarder
2626 graph.workers['bob'].config.EXPERIMENTAL_LN_FORWARD_TRAMPOLINE_PAYMENTS = True
2627 electrum.trampoline._TRAMPOLINE_NODES_UNITTESTS = {
2628 graph.workers['bob'].name: LNPeerAddr(host="127.0.0.1", port=9735, pubkey=graph.workers['bob'].node_keypair.pubkey),
2629 }
2630 # trampoline users
2631 await self._activate_trampoline(graph.workers['carol'])
2632 await self._activate_trampoline(graph.workers['alice'])
2633
2634 lnaddr, pay_req = self.prepare_invoice(graph.workers['carol'], include_routing_hints=True)
2635 # test both receiver (carol) and forwarder (bob)
2636 graph.workers['bob'].dont_settle_htlcs[lnaddr.paymenthash.hex()] = None
2637 graph.workers['carol'].dont_settle_htlcs[lnaddr.paymenthash.hex()] = None
2638
2639 payment_successful = asyncio.Event()
2640 async def pay():
2641 self.assertEqual(PR_UNPAID, graph.workers['carol'].get_payment_status(lnaddr.paymenthash, direction=RECEIVED))
2642 result, log = await graph.workers['alice'].pay_invoice(pay_req)
2643 self.assertEqual(PR_PAID, graph.workers['carol'].get_payment_status(lnaddr.paymenthash, direction=RECEIVED))
2644 self.assertTrue(result)
2645 payment_successful.set()
2646
2647 async def check_doesnt_settle():
2648 while not graph.workers['carol'].received_mpp_htlcs:
2649 await asyncio.sleep(0.1) # wait until carol received the htlcs
2650
2651 await asyncio.sleep(0.2) # give carol time to accidentally release the preimage
2652 self.assertEqual(PR_UNPAID, graph.workers['carol'].get_payment_status(lnaddr.paymenthash, direction=RECEIVED))
2653 self.assertIsNone(graph.workers['bob'].get_preimage(lnaddr.paymenthash), "bob got preimage from carol")
2654 # now allow carol to release the preimage to bob
2655 del graph.workers['carol'].dont_settle_htlcs[lnaddr.paymenthash.hex()]
2656
2657 # wait for carol to release the preimage to bob
2658 while not graph.workers['bob'].get_preimage(lnaddr.paymenthash):
2659 await asyncio.sleep(0.1)
2660
2661 # give bob some time to settle the htlcs to alice (this would complete the payment)
2662 await asyncio.sleep(0.2)
2663 self.assertIsNone(graph.workers['alice'].get_preimage(lnaddr.paymenthash), "alice got preimage from bob")
2664 self.assertFalse(payment_successful.is_set(), "bob released preimage")
2665
2666 # now allow bob to settle the htlcs
2667 del graph.workers['bob'].dont_settle_htlcs[lnaddr.paymenthash.hex()]
2668 await payment_successful.wait()
2669 raise PaymentDone()
2670
2671 async def f():
2672 async with OldTaskGroup() as group:
2673 for peer in peers:
2674 await group.spawn(peer._message_loop())
2675 await group.spawn(peer.htlc_switch())
2676 for peer in peers:
2677 await peer.initialized
2678
2679 await group.spawn(pay())
2680 await group.spawn(check_doesnt_settle())
2681 # stop the taskgroup if anything takes too long
2682 await group.spawn(asyncio.wait_for(asyncio.sleep(4), timeout=3))
2683
2684 await f()
2685
2686 for trampoline in (False, True):
2687 with self.assertRaises(PaymentDone):
2688 await run_test(trampoline)
2689
2690
2691 class TestPeerDirectNoAnchors(TestPeerDirect):
2692 assert TestPeerDirect.TEST_ANCHOR_CHANNELS is True
2693 TEST_ANCHOR_CHANNELS = False
2694
2695 class TestPeerForwardinNoAnchors(TestPeerForwarding):
2696 assert TestPeerForwarding.TEST_ANCHOR_CHANNELS is True
2697 TEST_ANCHOR_CHANNELS = False
2698
2699
2700 def run(coro):
2701 return asyncio.run_coroutine_threadsafe(coro, loop=util.get_asyncio_loop()).result()