| 1 |
import logging |
| 2 |
import os |
| 3 |
import asyncio |
| 4 |
import time |
| 5 |
from unittest import mock |
| 6 |
from decimal import Decimal |
| 7 |
from typing import Optional, Sequence |
| 8 |
|
| 9 |
from electrum.address_synchronizer import TX_HEIGHT_LOCAL |
| 10 |
from electrum import bitcoin |
| 11 |
import electrum.trampoline |
| 12 |
from electrum.channel_db import UpdateStatus |
| 13 |
from electrum.lnutil import RECEIVED, MIN_FINAL_CLTV_DELTA_ACCEPTED, serialize_htlc_key, LnFeatures, HTLCOwner |
| 14 |
from electrum.logging import console_stderr_handler |
| 15 |
from electrum.lnmsg import decode_msg |
| 16 |
from electrum.lnrouter import RouteEdge |
| 17 |
from electrum.lntransport import LNPeerAddr |
| 18 |
from electrum.invoices import LN_EXPIRY_NEVER, PR_UNPAID |
| 19 |
from electrum.lnpeer import Peer |
| 20 |
from electrum.lnchannel import Channel, ChannelState |
| 21 |
from electrum.lnonion import OnionPacket, OnionRoutingFailure, OnionFailureCode |
| 22 |
from electrum.mpp_split import SplitConfig, SplitConfigRating |
| 23 |
from electrum.crypto import sha256 |
| 24 |
from electrum.simple_config import SimpleConfig |
| 25 |
|
| 26 |
from . import ElectrumTestCase, lnhelpers |
| 27 |
from .lnhelpers import create_test_channels |
| 28 |
|
| 29 |
|
| 30 |
class TestLNWallet(ElectrumTestCase): |
| 31 |
TESTNET = True |
| 32 |
TEST_ANCHOR_CHANNELS = True |
| 33 |
|
| 34 |
@classmethod |
| 35 |
def setUpClass(cls): |
| 36 |
super().setUpClass() |
| 37 |
console_stderr_handler.setLevel(logging.DEBUG) |
| 38 |
|
| 39 |
async def asyncSetUp(self): |
| 40 |
self.lnwallet_anchors = self.create_mock_lnwallet(name='mock_lnwallet_anchors') |
| 41 |
await super().asyncSetUp() |
| 42 |
|
| 43 |
def test_create_payment_info(self): |
| 44 |
wallet = self.lnwallet_anchors |
| 45 |
tests = ( |
| 46 |
(100_000, 200, 100), |
| 47 |
(None, 200, 100), |
| 48 |
(None, None, LN_EXPIRY_NEVER), |
| 49 |
(100_000, None, 0), |
| 50 |
) |
| 51 |
for amount_msat, min_final_cltv_delta, exp_delay in tests: |
| 52 |
payment_hash = wallet.create_payment_info( |
| 53 |
amount_msat=amount_msat, |
| 54 |
min_final_cltv_delta=min_final_cltv_delta, |
| 55 |
exp_delay=exp_delay, |
| 56 |
) |
| 57 |
self.assertIsNotNone(wallet.get_preimage(payment_hash)) |
| 58 |
pi = wallet.get_payment_info(payment_hash, direction=RECEIVED) |
| 59 |
self.assertEqual(pi.amount_msat, amount_msat) |
| 60 |
self.assertEqual(pi.min_final_cltv_delta, min_final_cltv_delta or MIN_FINAL_CLTV_DELTA_ACCEPTED) |
| 61 |
self.assertEqual(pi.expiry_delay, exp_delay or LN_EXPIRY_NEVER) |
| 62 |
self.assertEqual(pi.db_key, f"{payment_hash.hex()}:{int(pi.direction)}") |
| 63 |
self.assertEqual(pi.status, PR_UNPAID) |
| 64 |
self.assertIsNone(wallet.get_payment_info(os.urandom(32), direction=RECEIVED)) |
| 65 |
|
| 66 |
def test_create_payment_info__amount_must_not_be_zero(self): |
| 67 |
wallet = self.lnwallet_anchors |
| 68 |
amount_msat, min_final_cltv_delta, exp_delay = (0, 200, 100) |
| 69 |
with self.assertRaises(ValueError): |
| 70 |
wallet.create_payment_info( |
| 71 |
amount_msat=amount_msat, |
| 72 |
min_final_cltv_delta=min_final_cltv_delta, |
| 73 |
exp_delay=exp_delay, |
| 74 |
) |
| 75 |
|
| 76 |
async def test_trampoline_invoice_features_and_routing_hints(self): |
| 77 |
""" |
| 78 |
When the invoice_features signal trampoline support, routing hints must only |
| 79 |
contain trampoline nodes. When it does not, all channel can be added as r_tags. |
| 80 |
We only signal trampoline support in the invoice if all open channels do support trampoline. |
| 81 |
""" |
| 82 |
wallet = self.lnwallet_anchors |
| 83 |
self.assertFalse(wallet.uses_trampoline()) |
| 84 |
|
| 85 |
trampoline_peer = self.create_mock_lnwallet(name='trampoline_peer') |
| 86 |
trampoline_pubkey = trampoline_peer.node_keypair.pubkey |
| 87 |
|
| 88 |
regular_peer = self.create_mock_lnwallet(name='regular_peer') |
| 89 |
regular_pubkey = regular_peer.node_keypair.pubkey |
| 90 |
|
| 91 |
chan_t, _ = create_test_channels(alice_lnwallet=wallet, bob_lnwallet=trampoline_peer) |
| 92 |
chan_r, _ = create_test_channels(alice_lnwallet=wallet, bob_lnwallet=regular_peer) |
| 93 |
wallet._add_channel(chan_t) |
| 94 |
wallet._add_channel(chan_r) |
| 95 |
|
| 96 |
|
| 97 |
electrum.trampoline._TRAMPOLINE_NODES_UNITTESTS = { |
| 98 |
'trampoline_peer': LNPeerAddr( |
| 99 |
host="127.0.0.1", |
| 100 |
port=9735, |
| 101 |
pubkey=trampoline_pubkey, |
| 102 |
), |
| 103 |
} |
| 104 |
self.addCleanup(lambda: electrum.trampoline._TRAMPOLINE_NODES_UNITTESTS.clear()) |
| 105 |
|
| 106 |
amount_msat = 100_000 |
| 107 |
|
| 108 |
|
| 109 |
payment_hash = wallet.create_payment_info(amount_msat=amount_msat) |
| 110 |
pi = wallet.get_payment_info(payment_hash, direction=RECEIVED) |
| 111 |
self.assertFalse( |
| 112 |
pi.invoice_features.supports(LnFeatures.OPTION_TRAMPOLINE_ROUTING_OPT_ELECTRUM), |
| 113 |
"trampoline bit should be stripped when not all peers are trampoline", |
| 114 |
) |
| 115 |
|
| 116 |
lnaddr, _ = wallet.get_bolt11_invoice(payment_info=pi, message='test', fallback_address=None) |
| 117 |
hint_node_ids = {route[0][0] for route in lnaddr.get_routing_info('r')} |
| 118 |
self.assertEqual(hint_node_ids, {trampoline_pubkey, regular_pubkey}) |
| 119 |
|
| 120 |
|
| 121 |
old_check, wallet.uses_trampoline = wallet.uses_trampoline, lambda: True |
| 122 |
self.assertTrue(wallet.uses_trampoline()) |
| 123 |
|
| 124 |
payment_hash = wallet.create_payment_info(amount_msat=amount_msat) |
| 125 |
pi = wallet.get_payment_info(payment_hash, direction=RECEIVED) |
| 126 |
self.assertFalse( |
| 127 |
pi.invoice_features.supports(LnFeatures.OPTION_TRAMPOLINE_ROUTING_OPT_ELECTRUM), |
| 128 |
"trampoline feature should not be set if we use trampoline but one peer is not a trampoline", |
| 129 |
) |
| 130 |
|
| 131 |
wallet.clear_invoices_cache() |
| 132 |
lnaddr, _ = wallet.get_bolt11_invoice(payment_info=pi, message='test', fallback_address=None) |
| 133 |
hint_node_ids = {route[0][0] for route in lnaddr.get_routing_info('r')} |
| 134 |
self.assertEqual(hint_node_ids, {trampoline_pubkey, regular_pubkey}) |
| 135 |
|
| 136 |
wallet.uses_trampoline = old_check |
| 137 |
self.assertFalse(wallet.uses_trampoline()) |
| 138 |
|
| 139 |
|
| 140 |
electrum.trampoline._TRAMPOLINE_NODES_UNITTESTS['regular_peer'] = LNPeerAddr( |
| 141 |
host="127.0.0.1", |
| 142 |
port=9735, |
| 143 |
pubkey=regular_pubkey, |
| 144 |
) |
| 145 |
|
| 146 |
payment_hash2 = wallet.create_payment_info(amount_msat=amount_msat) |
| 147 |
pi2 = wallet.get_payment_info(payment_hash2, direction=RECEIVED) |
| 148 |
self.assertTrue( |
| 149 |
pi2.invoice_features.supports(LnFeatures.OPTION_TRAMPOLINE_ROUTING_OPT_ELECTRUM), |
| 150 |
"trampoline bit should be present when all peers are trampoline", |
| 151 |
) |
| 152 |
|
| 153 |
wallet.clear_invoices_cache() |
| 154 |
lnaddr2, _ = wallet.get_bolt11_invoice(payment_info=pi2, message='test', fallback_address=None) |
| 155 |
hint_node_ids2 = {route[0][0] for route in lnaddr2.get_routing_info('r')} |
| 156 |
self.assertEqual(hint_node_ids2, {trampoline_pubkey, regular_pubkey}) |
| 157 |
|
| 158 |
|
| 159 |
del electrum.trampoline._TRAMPOLINE_NODES_UNITTESTS['regular_peer'] |
| 160 |
wallet.clear_invoices_cache() |
| 161 |
lnaddr3, _ = wallet.get_bolt11_invoice(payment_info=pi2, message='test', fallback_address=None) |
| 162 |
hint_node_ids3 = {route[0][0] for route in lnaddr3.get_routing_info('r')} |
| 163 |
self.assertEqual(hint_node_ids3, {trampoline_pubkey}) |
| 164 |
|
| 165 |
async def test_open_channel_just_in_time_success(self): |
| 166 |
wallet = self.lnwallet_anchors |
| 167 |
wallet.config.ZEROCONF_MIN_OPENING_FEE = 0 |
| 168 |
wallet.config.OPEN_ZEROCONF_CHANNELS = True |
| 169 |
|
| 170 |
next_peer = mock.Mock(spec=Peer) |
| 171 |
next_chan = mock.Mock(spec=Channel) |
| 172 |
next_chan.get_scid_or_local_alias.return_value = bytes(8) |
| 173 |
|
| 174 |
funding_tx = mock.Mock() |
| 175 |
funding_tx.txid.return_value = os.urandom(32).hex() |
| 176 |
funding_tx.get_fee = lambda: 250 |
| 177 |
|
| 178 |
wallet.open_channel_with_peer = mock.AsyncMock(return_value=(next_chan, funding_tx)) |
| 179 |
wallet.network.try_broadcasting = mock.AsyncMock(return_value=True) |
| 180 |
|
| 181 |
preimage = os.urandom(32) |
| 182 |
payment_hash = sha256(preimage) |
| 183 |
|
| 184 |
htlc = mock.Mock() |
| 185 |
htlc.htlc_id = 0 |
| 186 |
next_peer.send_htlc.return_value = htlc |
| 187 |
|
| 188 |
task = asyncio.create_task(wallet.open_channel_just_in_time( |
| 189 |
next_peer=next_peer, |
| 190 |
next_amount_msat_htlc=1000000, |
| 191 |
next_cltv_abs=500, |
| 192 |
payment_hash=payment_hash, |
| 193 |
next_onion=mock.Mock(spec=OnionPacket) |
| 194 |
)) |
| 195 |
|
| 196 |
await asyncio.sleep(0.1) |
| 197 |
wallet.save_preimage(payment_hash, preimage) |
| 198 |
htlc_key = await task |
| 199 |
htlc_key_correct = serialize_htlc_key(next_chan.get_scid_or_local_alias(), htlc.htlc_id) |
| 200 |
self.assertEqual(htlc_key, htlc_key_correct) |
| 201 |
|
| 202 |
wallet.open_channel_with_peer.assert_called_once() |
| 203 |
next_peer.send_htlc.assert_called_once() |
| 204 |
wallet.network.try_broadcasting.assert_called() |
| 205 |
|
| 206 |
async def test_open_channel_just_in_time_failure_channel_open(self): |
| 207 |
"""The channel opening failed on the LSP side because the client rejected the incoming channel""" |
| 208 |
wallet = self.lnwallet_anchors |
| 209 |
wallet.config.ZEROCONF_MIN_OPENING_FEE = 0 |
| 210 |
wallet.config.OPEN_ZEROCONF_CHANNELS = True |
| 211 |
next_peer = mock.Mock(spec=Peer) |
| 212 |
wallet.open_channel_with_peer = mock.AsyncMock(side_effect=Exception("peer rejected incoming channel")) |
| 213 |
preimage = os.urandom(32) |
| 214 |
wallet.save_preimage(sha256(preimage), preimage) |
| 215 |
wallet._cleanup_failed_jit_channel = mock.AsyncMock() |
| 216 |
|
| 217 |
with self.assertRaises(OnionRoutingFailure): |
| 218 |
await wallet.open_channel_just_in_time( |
| 219 |
next_peer=next_peer, |
| 220 |
next_amount_msat_htlc=1000000, |
| 221 |
next_cltv_abs=500, |
| 222 |
payment_hash=sha256(preimage), |
| 223 |
next_onion=mock.Mock(spec=OnionPacket) |
| 224 |
) |
| 225 |
|
| 226 |
self.assertIsNone(wallet.get_preimage(sha256(preimage))) |
| 227 |
wallet._cleanup_failed_jit_channel.assert_not_called() |
| 228 |
|
| 229 |
async def test_open_channel_just_in_time_failure_send_htlc(self): |
| 230 |
"""The LSP fails to forward the htlc to the client""" |
| 231 |
wallet = self.lnwallet_anchors |
| 232 |
wallet.config.ZEROCONF_MIN_OPENING_FEE = 0 |
| 233 |
wallet.config.OPEN_ZEROCONF_CHANNELS = True |
| 234 |
|
| 235 |
next_peer = mock.Mock(spec=Peer) |
| 236 |
chan = mock.Mock(spec=Channel) |
| 237 |
funding_tx = mock.Mock() |
| 238 |
|
| 239 |
wallet.open_channel_with_peer = mock.AsyncMock(return_value=(chan, funding_tx)) |
| 240 |
next_peer.send_htlc.side_effect = Exception("couldn't send htlc, peer disconnected") |
| 241 |
preimage = os.urandom(32) |
| 242 |
wallet.save_preimage(sha256(preimage), preimage) |
| 243 |
wallet._cleanup_failed_jit_channel = mock.AsyncMock() |
| 244 |
|
| 245 |
with self.assertRaises(OnionRoutingFailure): |
| 246 |
await wallet.open_channel_just_in_time( |
| 247 |
next_peer=next_peer, |
| 248 |
next_amount_msat_htlc=1000000, |
| 249 |
next_cltv_abs=500, |
| 250 |
payment_hash=sha256(preimage), |
| 251 |
next_onion=mock.Mock(spec=OnionPacket) |
| 252 |
) |
| 253 |
|
| 254 |
self.assertIsNone(wallet.get_preimage(sha256(preimage))) |
| 255 |
wallet._cleanup_failed_jit_channel.assert_called_once_with(chan) |
| 256 |
|
| 257 |
async def test_open_channel_just_in_time_failure_preimage_timeout(self): |
| 258 |
"""The client never releases the preimage""" |
| 259 |
wallet = self.lnwallet_anchors |
| 260 |
wallet.config.ZEROCONF_MIN_OPENING_FEE = 0 |
| 261 |
wallet.config.OPEN_ZEROCONF_CHANNELS = True |
| 262 |
|
| 263 |
next_peer = mock.Mock(spec=Peer) |
| 264 |
chan = mock.Mock(spec=Channel) |
| 265 |
funding_tx = mock.Mock() |
| 266 |
|
| 267 |
wallet.open_channel_with_peer = mock.AsyncMock(return_value=(chan, funding_tx)) |
| 268 |
|
| 269 |
htlc = mock.Mock() |
| 270 |
next_peer.send_htlc.return_value = htlc |
| 271 |
|
| 272 |
wallet._cleanup_failed_jit_channel = mock.AsyncMock() |
| 273 |
|
| 274 |
with mock.patch('electrum.lnworker.LN_P2P_NETWORK_TIMEOUT', 0.01): |
| 275 |
with self.assertRaises(OnionRoutingFailure): |
| 276 |
await wallet.open_channel_just_in_time( |
| 277 |
next_peer=next_peer, |
| 278 |
next_amount_msat_htlc=1000000, |
| 279 |
next_cltv_abs=500, |
| 280 |
payment_hash=os.urandom(32), |
| 281 |
next_onion=mock.Mock(spec=OnionPacket) |
| 282 |
) |
| 283 |
|
| 284 |
wallet._cleanup_failed_jit_channel.assert_called_once_with(chan) |
| 285 |
|
| 286 |
async def test_open_channel_just_in_time_failure_broadcast(self): |
| 287 |
wallet = self.lnwallet_anchors |
| 288 |
wallet.config.ZEROCONF_MIN_OPENING_FEE = 0 |
| 289 |
wallet.config.OPEN_ZEROCONF_CHANNELS = True |
| 290 |
|
| 291 |
next_peer = mock.Mock(spec=Peer) |
| 292 |
chan = mock.Mock(spec=Channel) |
| 293 |
|
| 294 |
funding_tx = mock.Mock() |
| 295 |
|
| 296 |
wallet.open_channel_with_peer = mock.AsyncMock(return_value=(chan, funding_tx)) |
| 297 |
|
| 298 |
preimage = os.urandom(32) |
| 299 |
wallet.save_preimage(sha256(preimage), preimage) |
| 300 |
|
| 301 |
wallet.network.try_broadcasting = mock.AsyncMock(return_value=False) |
| 302 |
wallet.wallet.adb.get_tx_height = mock.Mock(return_value=mock.Mock(height=lambda: TX_HEIGHT_LOCAL)) |
| 303 |
|
| 304 |
wallet._cleanup_failed_jit_channel = mock.AsyncMock() |
| 305 |
|
| 306 |
with mock.patch('electrum.lnworker.ZEROCONF_TIMEOUT', 0.01), \ |
| 307 |
mock.patch('electrum.lnworker.asyncio.sleep', new_callable=mock.AsyncMock): |
| 308 |
with self.assertRaises(OnionRoutingFailure): |
| 309 |
await wallet.open_channel_just_in_time( |
| 310 |
next_peer=next_peer, |
| 311 |
next_amount_msat_htlc=1000000, |
| 312 |
next_cltv_abs=500, |
| 313 |
payment_hash=sha256(preimage), |
| 314 |
next_onion=mock.Mock(spec=OnionPacket) |
| 315 |
) |
| 316 |
|
| 317 |
self.assertIsNone(wallet.get_preimage(sha256(preimage))) |
| 318 |
wallet._cleanup_failed_jit_channel.assert_called_once_with(chan) |
| 319 |
|
| 320 |
async def test_open_channel_just_in_time_config_disabled(self): |
| 321 |
"""open_channel_just_in_time rejects to open a channel if the config is disabled""" |
| 322 |
wallet = self.lnwallet_anchors |
| 323 |
wallet.config.ZEROCONF_MIN_OPENING_FEE = 0 |
| 324 |
wallet.config.OPEN_ZEROCONF_CHANNELS = False |
| 325 |
|
| 326 |
with self.assertRaises(AssertionError): |
| 327 |
await wallet.open_channel_just_in_time( |
| 328 |
next_peer=mock.Mock(spec=Peer), |
| 329 |
next_amount_msat_htlc=1000000, |
| 330 |
next_cltv_abs=500, |
| 331 |
payment_hash=os.urandom(32), |
| 332 |
next_onion=mock.Mock(spec=OnionPacket) |
| 333 |
) |
| 334 |
|
| 335 |
async def test_cleanup_failed_jit_channel(self): |
| 336 |
wallet = self.lnwallet_anchors |
| 337 |
|
| 338 |
chan = mock.Mock(spec=Channel) |
| 339 |
chan_id = os.urandom(32).hex() |
| 340 |
chan.channel_id = chan_id |
| 341 |
funding_txid = os.urandom(32).hex() |
| 342 |
chan.funding_outpoint = mock.Mock() |
| 343 |
chan.funding_outpoint.txid = funding_txid |
| 344 |
chan.get_funding_height.return_value = None |
| 345 |
|
| 346 |
|
| 347 |
wallet.close_channel = mock.AsyncMock(side_effect=Exception("peer disconnected")) |
| 348 |
wallet.remove_channel = mock.Mock() |
| 349 |
wallet.lnwatcher = mock.Mock() |
| 350 |
wallet.lnwatcher.stop = mock.AsyncMock() |
| 351 |
wallet.lnwatcher.adb = mock.Mock() |
| 352 |
wallet.lnwatcher.adb.remove_transaction = mock.Mock() |
| 353 |
|
| 354 |
await wallet._cleanup_failed_jit_channel(chan) |
| 355 |
|
| 356 |
wallet.close_channel.assert_called_once_with(chan_id) |
| 357 |
chan.set_state.assert_called_once_with(ChannelState.REDEEMED, force=True) |
| 358 |
wallet.lnwatcher.adb.remove_transaction.assert_called_once_with(funding_txid) |
| 359 |
wallet.remove_channel.assert_called_once_with(chan_id) |
| 360 |
|
| 361 |
async def test_receive_requires_jit_channel(self): |
| 362 |
wallet = self.lnwallet_anchors |
| 363 |
|
| 364 |
with self.subTest(msg="cannot get jit channel"): |
| 365 |
wallet.can_get_zeroconf_channel = mock.Mock(return_value=False) |
| 366 |
wallet.num_sats_can_receive = mock.Mock(return_value=Decimal(0)) |
| 367 |
self.assertFalse(wallet.receive_requires_jit_channel(1_000_000)) |
| 368 |
|
| 369 |
with self.subTest(msg="could get zeroconf channel but doesn't need one"): |
| 370 |
wallet.can_get_zeroconf_channel = mock.Mock(return_value=True) |
| 371 |
wallet.num_sats_can_receive = mock.Mock(return_value=Decimal(2000)) |
| 372 |
self.assertFalse(wallet.receive_requires_jit_channel(1_000_000)) |
| 373 |
|
| 374 |
with self.subTest(msg="could get zeroconf channel and needs one"): |
| 375 |
wallet.can_get_zeroconf_channel = mock.Mock(return_value=True) |
| 376 |
wallet.num_sats_can_receive = mock.Mock(return_value=Decimal(500)) |
| 377 |
self.assertTrue(wallet.receive_requires_jit_channel(1_000_000)) |
| 378 |
|
| 379 |
with self.subTest(msg="could get one but can receive exactly the requested amount"): |
| 380 |
wallet.can_get_zeroconf_channel = mock.Mock(return_value=True) |
| 381 |
wallet.num_sats_can_receive = mock.Mock(return_value=Decimal(1000)) |
| 382 |
self.assertFalse(wallet.receive_requires_jit_channel(1_000_000)) |
| 383 |
|
| 384 |
with self.subTest(msg="0 amount invoice, could get channel but can receive something"): |
| 385 |
wallet.can_get_zeroconf_channel = mock.Mock(return_value=True) |
| 386 |
wallet.num_sats_can_receive = mock.Mock(return_value=Decimal(1)) |
| 387 |
self.assertFalse(wallet.receive_requires_jit_channel(None)) |
| 388 |
|
| 389 |
with self.subTest(msg="0 amount invoice (None amount), cannot receive anything and can get channel"): |
| 390 |
wallet.can_get_zeroconf_channel = mock.Mock(return_value=True) |
| 391 |
wallet.num_sats_can_receive = mock.Mock(return_value=Decimal(0)) |
| 392 |
self.assertTrue(wallet.receive_requires_jit_channel(None)) |
| 393 |
|
| 394 |
with self.subTest(msg="0 amount invoice (0 msat), cannot receive anything, could get channel"): |
| 395 |
wallet.can_get_zeroconf_channel = mock.Mock(return_value=True) |
| 396 |
wallet.num_sats_can_receive = mock.Mock(return_value=Decimal(0)) |
| 397 |
self.assertTrue(wallet.receive_requires_jit_channel(0)) |
| 398 |
|
| 399 |
async def test_can_get_zeroconf_channel(self): |
| 400 |
wallet = self.lnwallet_anchors |
| 401 |
valid_peer = "02" * 33 + "@localhost:9735" |
| 402 |
|
| 403 |
with self.subTest(msg="disabled in config"): |
| 404 |
wallet.config.OPEN_ZEROCONF_CHANNELS = False |
| 405 |
wallet.config.ZEROCONF_TRUSTED_NODE = valid_peer |
| 406 |
self.assertFalse(wallet.can_get_zeroconf_channel()) |
| 407 |
|
| 408 |
with self.subTest(msg="enabled, but no trusted node configured"): |
| 409 |
wallet.config.OPEN_ZEROCONF_CHANNELS = True |
| 410 |
wallet.config.ZEROCONF_TRUSTED_NODE = '' |
| 411 |
self.assertFalse(wallet.can_get_zeroconf_channel()) |
| 412 |
|
| 413 |
with self.subTest(msg="enabled, invalid trusted node string"): |
| 414 |
wallet.config.OPEN_ZEROCONF_CHANNELS = True |
| 415 |
wallet.config.ZEROCONF_TRUSTED_NODE = "invalid_node_string" |
| 416 |
self.assertFalse(wallet.can_get_zeroconf_channel()) |
| 417 |
|
| 418 |
with self.subTest(msg="enabled, valid trusted node, but not connected"): |
| 419 |
wallet.config.OPEN_ZEROCONF_CHANNELS = True |
| 420 |
wallet.config.ZEROCONF_TRUSTED_NODE = valid_peer |
| 421 |
self.assertFalse(wallet.can_get_zeroconf_channel()) |
| 422 |
|
| 423 |
with self.subTest(msg="enabled, valid trusted node, and connected"): |
| 424 |
wallet.lnpeermgr.get_peer_by_pubkey = mock.Mock(return_value=mock.Mock(spec=Peer)) |
| 425 |
wallet.config.OPEN_ZEROCONF_CHANNELS = True |
| 426 |
wallet.config.ZEROCONF_TRUSTED_NODE = valid_peer |
| 427 |
self.assertTrue(wallet.can_get_zeroconf_channel()) |
| 428 |
|
| 429 |
async def test_rebalance_channels(self): |
| 430 |
graph_def = { |
| 431 |
'alice': { |
| 432 |
'channels': { |
| 433 |
'bob': [ |
| 434 |
{ |
| 435 |
'local_balance_msat': 10_000_000_000, |
| 436 |
'remote_balance_msat': 50_000_000, |
| 437 |
}, |
| 438 |
{ |
| 439 |
'local_balance_msat': 50_000_000, |
| 440 |
'remote_balance_msat': 10_000_000_000, |
| 441 |
}, |
| 442 |
], |
| 443 |
}, |
| 444 |
}, |
| 445 |
'bob': { |
| 446 |
'config': { |
| 447 |
SimpleConfig.EXPERIMENTAL_LN_FORWARD_PAYMENTS: True, |
| 448 |
}, |
| 449 |
}, |
| 450 |
} |
| 451 |
graph = lnhelpers.prepare_chans_and_peers_in_graph(self, graph_def) |
| 452 |
alice, bob = graph.workers.values() |
| 453 |
peer_ab, peer_ba = graph.peers.values() |
| 454 |
await alice.lnpeermgr.taskgroup.spawn(peer_ab.main_loop()) |
| 455 |
await bob.lnpeermgr.taskgroup.spawn(peer_ba.main_loop()) |
| 456 |
self.assertFalse(alice.uses_trampoline()) |
| 457 |
chan0 = graph.channels[('alice', 'bob')][0] |
| 458 |
chan1 = graph.channels[('alice', 'bob')][1] |
| 459 |
|
| 460 |
|
| 461 |
self.assertGreater(alice.num_sats_can_rebalance(chan0, chan1), 9_000_000) |
| 462 |
chan0.set_frozen_for_sending(True) |
| 463 |
self.assertEqual(alice.num_sats_can_rebalance(chan0, chan1), 0) |
| 464 |
chan0.set_frozen_for_sending(False) |
| 465 |
chan1.set_frozen_for_receiving(True) |
| 466 |
self.assertEqual(alice.num_sats_can_rebalance(chan0, chan1), 0) |
| 467 |
chan1.set_frozen_for_receiving(False) |
| 468 |
|
| 469 |
|
| 470 |
rebalance_amount = 60_000_000 |
| 471 |
self.assertEqual(chan0.balance(HTLCOwner.LOCAL), 10_000_000_000) |
| 472 |
success, log = await alice.rebalance_channels(chan0, chan1, amount_msat=rebalance_amount) |
| 473 |
self.assertTrue(success, msg=log) |
| 474 |
self.assertLessEqual(chan0.balance(HTLCOwner.LOCAL), 10_000_000_000 - rebalance_amount) |
| 475 |
self.assertEqual(chan1.balance(HTLCOwner.LOCAL), 50_000_000 + rebalance_amount) |
| 476 |
|
| 477 |
|
| 478 |
chan0.set_frozen_for_receiving(True) |
| 479 |
chan1.set_frozen_for_sending(True) |
| 480 |
success, log = await alice.rebalance_channels(chan0, chan1, amount_msat=150_000_000) |
| 481 |
self.assertTrue(success, msg=log) |
| 482 |
|
| 483 |
async def test_payment_multipart_single_channel_split(self): |
| 484 |
"""A split configuration can put multiple parts on a single channel. The parts |
| 485 |
must then be sent over that channel, instead of the pathfinder freely choosing |
| 486 |
a first hop, which would ignore the balance allocation of the config.""" |
| 487 |
graph = lnhelpers.prepare_chans_and_peers_in_graph(self, lnhelpers._GRAPH_DEFINITIONS['square_graph']) |
| 488 |
alice_w, dave_w = graph.workers['alice'], graph.workers['dave'] |
| 489 |
dave_w.features |= LnFeatures.BASIC_MPP_OPT |
| 490 |
self.assertFalse(alice_w.uses_trampoline()) |
| 491 |
amount_to_pay = 200_000_000 |
| 492 |
lnaddr, _pay_req = lnhelpers.prepare_invoice(dave_w, include_routing_hints=True, amount_msat=amount_to_pay) |
| 493 |
|
| 494 |
|
| 495 |
bob_chan = graph.channels[('alice', 'bob')][0] |
| 496 |
split_config = SplitConfig({(bob_chan.channel_id, bob_chan.node_id): [amount_to_pay // 2, amount_to_pay // 2]}) |
| 497 |
alice_w.suggest_payment_splits = lambda **kwargs: [SplitConfigRating(config=split_config, rating=0)] |
| 498 |
routes = await alice_w.create_routes_from_invoice(amount_to_pay, decoded_invoice=lnaddr) |
| 499 |
self.assertEqual(2, len(routes)) |
| 500 |
for shi, _, _ in routes: |
| 501 |
|
| 502 |
self.assertEqual(bob_chan.short_channel_id, shi.route[0].short_channel_id) |
| 503 |
|
| 504 |
async def test_unchanged_channel_update_from_failed_htlc(self): |
| 505 |
|
| 506 |
|
| 507 |
|
| 508 |
|
| 509 |
|
| 510 |
graph = lnhelpers.prepare_chans_and_peers_in_graph(self, lnhelpers._GRAPH_DEFINITIONS['square_graph']) |
| 511 |
alice_w = graph.workers['alice'] |
| 512 |
path_finder = alice_w.network.path_finder |
| 513 |
amount_msat = 100_000_000 |
| 514 |
now = int(time.time()) |
| 515 |
|
| 516 |
def add_chan_to_alice_channel_db(chan: Channel) -> bytes: |
| 517 |
|
| 518 |
|
| 519 |
chan_ann = decode_msg(chan.construct_channel_announcement_without_sigs()[0])[1] |
| 520 |
alice_w.channel_db.add_channel_announcements(chan_ann, trusted=True) |
| 521 |
chan_upd_raw = chan.get_outgoing_gossip_channel_update() |
| 522 |
chan_upd = decode_msg(chan_upd_raw)[1] |
| 523 |
chan_upd['timestamp'] -= 3600 |
| 524 |
self.assertEqual(UpdateStatus.GOOD, alice_w.channel_db.add_channel_update(chan_upd, verify=False)) |
| 525 |
return chan_upd_raw |
| 526 |
|
| 527 |
def two_hop_route(middle: str) -> Sequence[RouteEdge]: |
| 528 |
return [ |
| 529 |
RouteEdge( |
| 530 |
start_node=graph.workers[a].node_keypair.pubkey, |
| 531 |
end_node=graph.workers[b].node_keypair.pubkey, |
| 532 |
short_channel_id=graph.channels[(a, b)][0].short_channel_id, |
| 533 |
fee_base_msat=0, fee_proportional_millionths=0, cltv_delta=10, node_features=0, |
| 534 |
) for a, b in [('alice', middle), (middle, 'dave')] |
| 535 |
] |
| 536 |
|
| 537 |
|
| 538 |
chan_bd = graph.channels[('bob', 'dave')][0] |
| 539 |
chan_upd_raw = add_chan_to_alice_channel_db(chan_bd) |
| 540 |
failure_data = len(chan_upd_raw).to_bytes(2, 'big') + chan_upd_raw |
| 541 |
alice_w.handle_error_code_from_failed_htlc( |
| 542 |
route=two_hop_route('bob'), sender_idx=0, amount_msat=amount_msat, |
| 543 |
failure_msg=OnionRoutingFailure(code=OnionFailureCode.TEMPORARY_CHANNEL_FAILURE, data=failure_data)) |
| 544 |
self.assertFalse(path_finder._is_edge_blacklisted(chan_bd.short_channel_id, now=now)) |
| 545 |
hint_bd = path_finder.liquidity_hints.get_hint(chan_bd.short_channel_id) |
| 546 |
pubkey_b = graph.workers['bob'].node_keypair.pubkey |
| 547 |
pubkey_d = graph.workers['dave'].node_keypair.pubkey |
| 548 |
self.assertEqual(amount_msat, hint_bd.cannot_send(pubkey_b < pubkey_d)) |
| 549 |
|
| 550 |
|
| 551 |
chan_cd = graph.channels[('carol', 'dave')][0] |
| 552 |
chan_upd_raw = add_chan_to_alice_channel_db(chan_cd) |
| 553 |
failure_data = amount_msat.to_bytes(8, 'big') + len(chan_upd_raw).to_bytes(2, 'big') + chan_upd_raw |
| 554 |
alice_w.handle_error_code_from_failed_htlc( |
| 555 |
route=two_hop_route('carol'), sender_idx=0, amount_msat=amount_msat, |
| 556 |
failure_msg=OnionRoutingFailure(code=OnionFailureCode.FEE_INSUFFICIENT, data=failure_data)) |
| 557 |
self.assertTrue(path_finder._is_edge_blacklisted(chan_cd.short_channel_id, now=now)) |
| 558 |
|
| 559 |
async def test_missing_channel_update_from_failed_htlc(self): |
| 560 |
|
| 561 |
|
| 562 |
|
| 563 |
|
| 564 |
|
| 565 |
graph = lnhelpers.prepare_chans_and_peers_in_graph(self, lnhelpers._GRAPH_DEFINITIONS['square_graph']) |
| 566 |
alice_w = graph.workers['alice'] |
| 567 |
path_finder = alice_w.network.path_finder |
| 568 |
amount_msat = 100_000_000 |
| 569 |
route = [ |
| 570 |
RouteEdge( |
| 571 |
start_node=graph.workers[a].node_keypair.pubkey, |
| 572 |
end_node=graph.workers[b].node_keypair.pubkey, |
| 573 |
short_channel_id=graph.channels[(a, b)][0].short_channel_id, |
| 574 |
fee_base_msat=0, fee_proportional_millionths=0, cltv_delta=10, node_features=0, |
| 575 |
) for a, b in [('alice', 'bob'), ('bob', 'dave')] |
| 576 |
] |
| 577 |
failure_data = (0).to_bytes(2, 'big') |
| 578 |
alice_w.handle_error_code_from_failed_htlc( |
| 579 |
route=route, sender_idx=0, amount_msat=amount_msat, |
| 580 |
failure_msg=OnionRoutingFailure(code=OnionFailureCode.TEMPORARY_CHANNEL_FAILURE, data=failure_data)) |
| 581 |
chan_bd = graph.channels[('bob', 'dave')][0] |
| 582 |
self.assertFalse(path_finder._is_edge_blacklisted(chan_bd.short_channel_id, now=int(time.time()))) |
| 583 |
hint_bd = path_finder.liquidity_hints.get_hint(chan_bd.short_channel_id) |
| 584 |
pubkey_b = graph.workers['bob'].node_keypair.pubkey |
| 585 |
pubkey_d = graph.workers['dave'].node_keypair.pubkey |
| 586 |
self.assertEqual(amount_msat, hint_bd.cannot_send(pubkey_b < pubkey_d)) |