Debian Codegraph @

tests/lnhelpers.py

raw symbols SCIP
1 import asyncio
2 import copy
3 import os
4 from decimal import Decimal
5 from pprint import pformat
6 from typing import NamedTuple, Tuple, Dict, Mapping, TYPE_CHECKING, Sequence
7
8 import electrum
9 import electrum.trampoline
10 from electrum import (
11 bitcoin, lnpeer, lnchannel, lnutil, util,
12 )
13 from electrum.coinchooser import PRNG
14 from electrum.network import ProxySettings
15 from electrum.bitcoin import COIN, sha256
16 from electrum.bolt11 import encode_bolt11_invoice, BOLT11Addr, decode_bolt11_invoice
17 from electrum.invoices import PR_UNPAID, Invoice, LN_EXPIRY_NEVER
18 from electrum.lnpeer import Peer
19 from electrum.lnutil import (
20 LnFeatures, PaymentFeeBudget, LOCAL, REMOTE, ChannelType, LocalConfig, RemoteConfig,
21 OnlyPubkeyKeypair, secret_to_pubkey, RECEIVED,
22 )
23 from electrum.lnchannel import ChannelState, Channel
24 from electrum.lnrouter import LNPathFinder
25 from electrum.channel_db import ChannelDB
26 from electrum.lnworker import LNWallet, PaySession, PaymentInfo
27 from electrum.simple_config import SimpleConfig
28 from electrum.fee_policy import FeeTimeEstimates, FEE_ETA_TARGETS
29 from electrum.wallet import Standard_Wallet
30
31 from . import restore_wallet_from_text__for_unittest
32
33 if TYPE_CHECKING:
34 from . import ElectrumTestCase
35
36
37 high_fee_channel = {
38 'local_balance_msat': 10 * bitcoin.COIN * 1000 // 2,
39 'remote_balance_msat': 10 * bitcoin.COIN * 1000 // 2,
40 'local_base_fee_msat': 500_000,
41 'local_fee_rate_millionths': 500,
42 'remote_base_fee_msat': 500_000,
43 'remote_fee_rate_millionths': 500,
44 }
45
46 low_fee_channel = {
47 'local_balance_msat': 10 * bitcoin.COIN * 1000 // 2,
48 'remote_balance_msat': 10 * bitcoin.COIN * 1000 // 2,
49 'local_base_fee_msat': 1_000,
50 'local_fee_rate_millionths': 1,
51 'remote_base_fee_msat': 1_000,
52 'remote_fee_rate_millionths': 1,
53 }
54
55 depleted_channel = {
56 'local_balance_msat': 330 * 1000, # local pays anchors
57 'remote_balance_msat': 10 * bitcoin.COIN * 1000,
58 'local_base_fee_msat': 1_000,
59 'local_fee_rate_millionths': 1,
60 'remote_base_fee_msat': 1_000,
61 'remote_fee_rate_millionths': 1,
62 }
63
64 _GRAPH_DEFINITIONS = {
65 # A -- B
66 'single_chan' : {
67 'alice': {
68 'channels': {
69 'bob': [
70 {
71 'local_balance_msat': 10 * bitcoin.COIN * 1000 // 2,
72 'remote_balance_msat': 10 * bitcoin.COIN * 1000 // 2,
73 },
74 ],
75 },
76 },
77 'bob': {
78 },
79 },
80 # A
81 # high fee / \ low fee
82 # B C
83 # high fee \ / low fee
84 # D
85 'square_graph': {
86 'alice': {
87 'channels': {
88 # we should use copies of channel definitions if
89 # we want to independently alter them in a test
90 'bob': [high_fee_channel.copy()],
91 'carol': [low_fee_channel.copy()],
92 },
93 },
94 'bob': {
95 'channels': {
96 'dave': [high_fee_channel.copy()],
97 },
98 'config': {
99 SimpleConfig.EXPERIMENTAL_LN_FORWARD_PAYMENTS: True,
100 SimpleConfig.EXPERIMENTAL_LN_FORWARD_TRAMPOLINE_PAYMENTS: True,
101 },
102 },
103 'carol': {
104 'channels': {
105 'dave': [low_fee_channel.copy()],
106 },
107 'config': {
108 SimpleConfig.EXPERIMENTAL_LN_FORWARD_PAYMENTS: True,
109 SimpleConfig.EXPERIMENTAL_LN_FORWARD_TRAMPOLINE_PAYMENTS: True,
110 },
111 },
112 'dave': {
113 },
114 },
115 # A -- B -- C -- D -- E
116 'line_graph': {
117 'alice': {
118 'channels': {
119 'bob': [low_fee_channel.copy()],
120 },
121 },
122 'bob': { # Trampoline Forwarder
123 'channels': {
124 'carol': [low_fee_channel.copy()],
125 },
126 'config': {
127 SimpleConfig.EXPERIMENTAL_LN_FORWARD_PAYMENTS: True,
128 },
129 },
130 'carol': {
131 'channels': {
132 'dave': [low_fee_channel.copy()],
133 },
134 'config': {
135 SimpleConfig.EXPERIMENTAL_LN_FORWARD_PAYMENTS: True,
136 },
137 },
138 'dave': { # Trampoline Forwarder
139 'channels': {
140 'edward': [low_fee_channel.copy()],
141 },
142 'config': {
143 SimpleConfig.EXPERIMENTAL_LN_FORWARD_PAYMENTS: True,
144 },
145 },
146 'edward': {
147 },
148 },
149 }
150
151
152 class MockNetwork:
153 def __init__(self, *, config: SimpleConfig):
154 self.lnwatcher = None
155 self.interface = None
156 self.fee_estimates = FeeTimeEstimates()
157 self.populate_fee_estimates()
158 self.config = config
159 self.asyncio_loop = util.get_asyncio_loop()
160 self.channel_db = ChannelDB(self)
161 self.channel_db.data_loaded.set()
162 self.path_finder = LNPathFinder(self.channel_db)
163 self.lngossip = MockLNGossip()
164 self.tx_queue = asyncio.Queue()
165 self.proxy = ProxySettings()
166 self.is_proxy_tor = None
167 self._blockchain = MockBlockchain()
168
169 def get_local_height(self):
170 return self.blockchain().height()
171
172 def blockchain(self):
173 return self._blockchain
174
175 async def broadcast_transaction(self, tx):
176 await self.tx_queue.put(tx)
177
178 async def try_broadcasting(self, tx, name):
179 await self.broadcast_transaction(tx)
180
181 def populate_fee_estimates(self):
182 for target in FEE_ETA_TARGETS[:-1]:
183 self.fee_estimates.set_data(target, 50000 // target)
184
185
186 class MockBlockchain:
187 def __init__(self):
188 # Let's return a non-zero, realistic height.
189 # 0 might hide relative vs abs locktime confusion bugs.
190 self._height = 600_000
191
192 def height(self):
193 return self._height
194
195 def is_tip_stale(self):
196 return False
197
198
199 class MockLNGossip:
200 def get_sync_progress_estimate(self):
201 return None, None, None
202
203
204 class MockWalletFactory(electrum.wallet.Wallet):
205
206 @staticmethod
207 def wallet_class(wallet_type):
208 real_wallet_class = electrum.wallet.Wallet.wallet_class(wallet_type)
209 if real_wallet_class is Standard_Wallet:
210 return MockStandardWallet
211 return real_wallet_class
212
213
214 class MockStandardWallet(Standard_Wallet):
215 def _init_lnworker(self):
216 ln_xprv = self.db.get('lightning_xprv') or self.db.get('lightning_privkey2')
217 assert ln_xprv
218 self.lnworker = MockLNWallet(self, ln_xprv)
219
220 def basename(self):
221 passphrase = self.db.get("keystore").get("passphrase")
222 assert passphrase
223 return passphrase # lol, super secure name
224
225
226 def _create_mock_lnwallet(*, name: str, has_anchors: bool, data_dir: str) -> 'MockLNWallet':
227 config = SimpleConfig({}, read_user_dir_function=lambda: data_dir)
228 config.TEST_LN_OPEN_SRK_CHANNELS = not has_anchors
229 config.INITIAL_TRAMPOLINE_FEE_LEVEL = 0
230
231 network = MockNetwork(config=config)
232
233 wallet = restore_wallet_from_text__for_unittest(
234 "9dk", path=None, passphrase=name, config=config,
235 wallet_factory=MockWalletFactory,
236 )['wallet'] # type: MockStandardWallet
237 wallet.is_up_to_date = lambda: True
238 wallet.adb.network = wallet.network = network
239
240 lnworker = wallet.lnworker
241 assert isinstance(lnworker, MockLNWallet), f"{lnworker=!r}"
242 lnworker.lnpeermgr.network = network
243 lnworker.logger.info(f"created LNWallet[{name}] with nodeID={lnworker.node_keypair.pubkey.hex()}")
244 return lnworker
245
246
247 class MockLNWallet(LNWallet):
248 MPP_EXPIRY = 2 # HTLC timestamps are cast to int, so this cannot be 1
249 TIMEOUT_SHUTDOWN_FAIL_PENDING_HTLCS = 0
250 MPP_SPLIT_PART_FRACTION = 1 # this disables the forced splitting
251
252 def __init__(self, *args, **kwargs):
253 LNWallet.__init__(self, *args, **kwargs)
254 self.features &= ~LnFeatures.BASIC_MPP_OPT # by default, disable MPP
255
256 def _add_channel(self, chan: Channel):
257 self._channels[chan.channel_id] = chan
258 # assert chan.lnworker == self # this fails as some tests are reusing chans in a weird way
259 chan.lnworker = self
260
261 @LNWallet.features.setter
262 def features(self, value):
263 self.lnpeermgr.features = value
264
265 @property
266 def name(self):
267 return self.wallet.basename()
268
269 async def stop(self):
270 await LNWallet.stop(self)
271 if self.channel_db:
272 self.channel_db.stop()
273 await self.channel_db.stopped_event.wait()
274
275 async def create_routes_from_invoice(self, amount_msat: int, decoded_invoice: BOLT11Addr, *, full_path=None):
276 paysession = PaySession(
277 payment_hash=decoded_invoice.paymenthash,
278 payment_secret=decoded_invoice.payment_secret,
279 initial_trampoline_fee_level=0,
280 invoice_features=decoded_invoice.get_features(),
281 r_tags=decoded_invoice.get_routing_info('r'),
282 min_final_cltv_delta=decoded_invoice.get_min_final_cltv_delta(),
283 amount_to_pay=amount_msat,
284 invoice_pubkey=decoded_invoice.pubkey.serialize(),
285 uses_trampoline=False,
286 )
287 payment_key = decoded_invoice.paymenthash + decoded_invoice.payment_secret
288 self._paysessions[payment_key] = paysession
289 return [r async for r in self.create_routes_for_payment(
290 amount_msat=amount_msat,
291 paysession=paysession,
292 full_path=full_path,
293 budget=PaymentFeeBudget.from_invoice_amount(invoice_amount_msat=amount_msat, config=self.config),
294 )]
295
296
297 class PeerInTests(Peer):
298 DELAY_INC_MSG_PROCESSING_SLEEP = 0 # disable rate-limiting
299
300
301 class Graph(NamedTuple):
302 workers: Dict[str, 'MockLNWallet']
303 peers: Dict[Tuple[str, str], Peer]
304 channels: Dict[Tuple[str, str], list[Channel]]
305
306
307 class MockTransport:
308 def __init__(self, name):
309 self.queue = asyncio.Queue() # incoming messages
310 self._name = name
311 self.peer_addr = None
312
313 def name(self):
314 return self._name
315
316 async def read_messages(self):
317 while True:
318 data = await self.queue.get()
319 if isinstance(data, asyncio.Event): # to artificially delay messages
320 await data.wait()
321 continue
322 yield data
323
324
325 class PutIntoOthersQueueTransport(MockTransport):
326 def __init__(self, keypair, name):
327 super().__init__(name)
328 self.other_mock_transport = None
329 self.privkey = keypair.privkey
330
331 def send_bytes(self, data):
332 self.other_mock_transport.queue.put_nowait(data)
333
334 async def send_bytes_and_drain(self, data):
335 self.send_bytes(data)
336
337
338 def transport_pair(k1, k2, name1, name2):
339 t1 = PutIntoOthersQueueTransport(k1, name1)
340 t2 = PutIntoOthersQueueTransport(k2, name2)
341 t1.other_mock_transport = t2
342 t2.other_mock_transport = t1
343 return t1, t2
344
345
346 def prepare_invoice(
347 w2: MockLNWallet, # receiver
348 *,
349 amount_msat=100_000_000,
350 include_routing_hints=False,
351 payment_preimage: bytes = None,
352 payment_hash: bytes = None,
353 invoice_features: LnFeatures = None,
354 min_final_cltv_delta: int = None,
355 expiry: int = None,
356 ) -> Tuple[BOLT11Addr, Invoice]:
357 amount_btc = amount_msat/Decimal(COIN*1000)
358 if payment_preimage is None and not payment_hash:
359 payment_preimage = os.urandom(32)
360 if payment_hash is None:
361 payment_hash = sha256(payment_preimage)
362 if payment_preimage:
363 w2.save_preimage(payment_hash, payment_preimage)
364 if include_routing_hints:
365 routing_hints = w2.calc_routing_hints_for_invoice(amount_msat)
366 else:
367 routing_hints = []
368 trampoline_hints = []
369 if invoice_features is None:
370 invoice_features = w2.features.for_bolt11_invoice()
371 if invoice_features.supports(LnFeatures.PAYMENT_SECRET_OPT):
372 payment_secret = w2.get_payment_secret(payment_hash)
373 else:
374 payment_secret = None
375 if min_final_cltv_delta is None:
376 min_final_cltv_delta = lnutil.MIN_FINAL_CLTV_DELTA_ACCEPTED
377 info = PaymentInfo(
378 payment_hash=payment_hash,
379 amount_msat=amount_msat,
380 direction=RECEIVED,
381 status=PR_UNPAID,
382 min_final_cltv_delta=min_final_cltv_delta,
383 expiry_delay=expiry or LN_EXPIRY_NEVER,
384 invoice_features=invoice_features,
385 )
386 w2.save_payment_info(info)
387 lnaddr1 = BOLT11Addr(
388 paymenthash=payment_hash,
389 amount=amount_btc,
390 tags=[
391 ('c', min_final_cltv_delta),
392 ('d', 'coffee'),
393 ('9', invoice_features),
394 ('x', expiry or 3600),
395 ] + routing_hints,
396 payment_secret=payment_secret,
397 )
398 invoice = encode_bolt11_invoice(lnaddr1, w2.node_keypair.privkey)
399 lnaddr2 = decode_bolt11_invoice(invoice) # unlike lnaddr1, this now has a pubkey set
400 return lnaddr2, Invoice.from_bech32(invoice)
401
402
403 def prepare_lnwallets(elec_test_case: 'ElectrumTestCase', graph_definition) -> Mapping[str, MockLNWallet]:
404 workers = {} # type: Dict[str, MockLNWallet]
405 for a, definition in graph_definition.items():
406 workers[a] = elec_test_case.create_mock_lnwallet(name=a)
407 return workers
408
409
410 def prepare_chans_and_peers_in_graph(
411 elec_test_case: 'ElectrumTestCase',
412 graph_definition=None,
413 *,
414 workers: Dict[str, MockLNWallet] = None,
415 channels: dict[Tuple[str, str], list[Channel]] = None,
416 ) -> Graph:
417 if graph_definition is None:
418 graph_definition = _GRAPH_DEFINITIONS['single_chan']
419 graph_definition = copy.deepcopy(graph_definition) # paranoia
420
421 # create workers
422 if workers is None:
423 workers = prepare_lnwallets(elec_test_case, graph_definition=graph_definition)
424 keys = {name: w.node_keypair for name, w in workers.items()}
425
426 if channels is None:
427 channels = {} # type: Dict[Tuple[str, str], list[Channel]]
428 transports = {}
429 peers = {} # type: Dict[Tuple[str, str], Peer]
430
431 # create channels
432 for a, definition in graph_definition.items():
433 for b, channel_def_list in definition.get('channels', {}).items():
434 if (a, b) not in channels:
435 channels[(a, b)] = []
436 if (b, a) not in channels:
437 channels[(b, a)] = []
438 assert len(channels[(a, b)]) == len(channels[(b, a)])
439 for chan_idx, channel_def in enumerate(channel_def_list):
440 if chan_idx < len(channels[(a, b)]): # chan already exists
441 # if either chan direction is present, both must be present
442 channel_ab = channels[(a, b)][chan_idx]
443 channel_ba = channels[(b, a)][chan_idx]
444 else: # create new chans now
445 channel_ab, channel_ba = create_test_channels(
446 alice_lnwallet=workers[a],
447 bob_lnwallet=workers[b],
448 local_msat=channel_def['local_balance_msat'],
449 remote_msat=channel_def['remote_balance_msat'],
450 )
451 assert chan_idx == len(channels[(a, b)]) == len(channels[(b, a)])
452 channels[(a, b)].append(channel_ab)
453 channels[(b, a)].append(channel_ba)
454 workers[a]._add_channel(channel_ab)
455 workers[b]._add_channel(channel_ba)
456 transport_ab, transport_ba = transport_pair(keys[a], keys[b], channel_ab.name, channel_ba.name)
457 transports[(a, b)], transports[(b, a)] = transport_ab, transport_ba
458 # set fees
459 if 'local_fee_rate_millionths' in channel_def:
460 channel_ab.forwarding_fee_proportional_millionths = channel_def['local_fee_rate_millionths']
461 if 'local_base_fee_msat' in channel_def:
462 channel_ab.forwarding_fee_base_msat = channel_def['local_base_fee_msat']
463 if 'remote_fee_rate_millionths' in channel_def:
464 channel_ba.forwarding_fee_proportional_millionths = channel_def['remote_fee_rate_millionths']
465 if 'remote_base_fee_msat' in channel_def:
466 channel_ba.forwarding_fee_base_msat = channel_def['remote_base_fee_msat']
467
468 # create peers
469 for ab in channels.keys():
470 peers[ab] = PeerInTests(workers[ab[0]], keys[ab[1]].pubkey, transports[ab])
471
472 # add peers to workers
473 for a, w in workers.items():
474 for ab, peer_ab in peers.items():
475 if ab[0] == a:
476 w.lnpeermgr._peers[peer_ab.pubkey] = peer_ab
477
478 # set forwarding properties
479 for a, definition in graph_definition.items():
480 for property in definition.get('config', {}).items():
481 workers[a].network.config.set_key(*property)
482
483 # mark_open won't work if state is already OPEN.
484 # so set it to FUNDED
485 for chan_list in channels.values():
486 for chan in chan_list:
487 chan._state = ChannelState.FUNDED
488
489 # this populates the channel graph:
490 for ab, peer_ab in peers.items():
491 for chan in channels[ab]:
492 peer_ab.mark_open(chan)
493
494 graph = Graph(
495 workers=workers,
496 peers=peers,
497 channels=channels,
498 )
499 for a in workers:
500 print(f"{a:5s}: {keys[a].pubkey}")
501 print(f" {keys[a].pubkey.hex()}")
502 return graph
503
504
505 def _convert_to_rconfig_from_lconfig(lconfig: LocalConfig) -> RemoteConfig:
506 """converts Alice's local config to Bob's remote config (neutering private keys, etc)"""
507 ctn = 0
508 pcp_secret = lnutil.get_per_commitment_secret_from_seed(
509 lconfig.per_commitment_secret_seed,
510 lnutil.RevocationStore.START_INDEX - ctn)
511 pcp_point = secret_to_pubkey(int.from_bytes(pcp_secret, 'big'))
512 rconfig = RemoteConfig(
513 payment_basepoint=OnlyPubkeyKeypair(pubkey=lconfig.payment_basepoint.pubkey),
514 multisig_key=OnlyPubkeyKeypair(pubkey=lconfig.multisig_key.pubkey),
515 htlc_basepoint=OnlyPubkeyKeypair(pubkey=lconfig.htlc_basepoint.pubkey),
516 delayed_basepoint=OnlyPubkeyKeypair(pubkey=lconfig.delayed_basepoint.pubkey),
517 revocation_basepoint=OnlyPubkeyKeypair(pubkey=lconfig.revocation_basepoint.pubkey),
518 to_self_delay=lconfig.to_self_delay,
519 dust_limit_sat=lconfig.dust_limit_sat,
520 max_htlc_value_in_flight_msat=lconfig.max_htlc_value_in_flight_msat,
521 max_accepted_htlcs=lconfig.max_accepted_htlcs,
522 initial_msat=lconfig.initial_msat,
523 reserve_sat=lconfig.reserve_sat,
524 htlc_minimum_msat=lconfig.htlc_minimum_msat,
525 upfront_shutdown_script=lconfig.upfront_shutdown_script,
526 announcement_node_sig=lconfig.announcement_node_sig,
527 announcement_bitcoin_sig=lconfig.announcement_bitcoin_sig,
528 next_per_commitment_point=pcp_point,
529 current_per_commitment_point=None,
530 )
531 return rconfig
532
533
534 def _create_channel_state(
535 *,
536 funding_txid: str,
537 funding_index: int,
538 funding_sat: int,
539 is_initiator: bool,
540 other_node_id: bytes,
541 channel_type: ChannelType,
542 local_config: LocalConfig,
543 remote_config: RemoteConfig,
544 ):
545 channel_id, _ = lnpeer.channel_id_from_funding_tx(funding_txid, funding_index)
546 state = {
547 "channel_id":channel_id.hex(),
548 "short_channel_id":channel_id[:8],
549 "funding_outpoint":lnpeer.Outpoint(funding_txid, funding_index),
550 "remote_config": remote_config,
551 "local_config": local_config,
552 "constraints":lnpeer.ChannelConstraints(
553 flags=lnchannel.CF_ANNOUNCE_CHANNEL,
554 capacity=funding_sat,
555 is_initiator=is_initiator,
556 funding_txn_minimum_depth=3,
557 ),
558 "node_id":other_node_id.hex(),
559 'onion_keys': {},
560 'data_loss_protect_remote_pcp': {},
561 'state': 'PREOPENING',
562 'log': {},
563 'unfulfilled_htlcs': {},
564 'revocation_store': {},
565 'channel_type': channel_type,
566 }
567 return state
568
569
570 def create_test_channels(
571 *,
572 alice_lnwallet: 'MockLNWallet',
573 bob_lnwallet: 'MockLNWallet',
574 feerate=6000,
575 local_msat=None,
576 remote_msat=None,
577 random_seed=None,
578 local_max_inflight=None,
579 remote_max_inflight=None,
580 max_accepted_htlcs=5,
581 ) -> tuple[Channel, Channel]:
582 if random_seed is None: # needed for deterministic randomness
583 random_seed = os.urandom(32)
584 random_gen = PRNG(random_seed)
585 alice_name = alice_lnwallet.name
586 bob_name = bob_lnwallet.name
587 alice_pubkey = alice_lnwallet.node_keypair.pubkey
588 bob_pubkey = bob_lnwallet.node_keypair.pubkey
589 funding_txid = random_gen.get_bytes(32).hex()
590 funding_index = 0
591 funding_sat = ((local_msat + remote_msat) // 1000) if local_msat is not None and remote_msat is not None else (bitcoin.COIN * 10)
592 local_msat = local_msat if local_msat is not None else (funding_sat * 1000 // 2)
593 remote_msat = remote_msat if remote_msat is not None else (funding_sat * 1000 // 2)
594 local_max_inflight = funding_sat * 1000 if local_max_inflight is None else local_max_inflight
595 remote_max_inflight = funding_sat * 1000 if remote_max_inflight is None else remote_max_inflight
596
597 for config in [alice_lnwallet.config, bob_lnwallet.config]:
598 config.LIGHTNING_MAX_FUNDING_SAT = max(config.LIGHTNING_MAX_FUNDING_SAT, funding_sat)
599
600 peer_features = alice_lnwallet.features | LnFeatures.OPTION_SUPPORT_LARGE_CHANNEL_OPT
601 assert alice_lnwallet.config.TEST_LN_OPEN_SRK_CHANNELS == bob_lnwallet.config.TEST_LN_OPEN_SRK_CHANNELS
602 if alice_lnwallet.config.TEST_LN_OPEN_SRK_CHANNELS:
603 channel_type = ChannelType.OPTION_STATIC_REMOTEKEY
604 else:
605 channel_type = ChannelType.OPTION_STATIC_REMOTEKEY | ChannelType.OPTION_ANCHORS
606 # create alice's local config
607 alice_lconfig = alice_lnwallet.make_local_config_for_new_channel(
608 funding_sat=funding_sat,
609 push_msat=remote_msat,
610 initiator=LOCAL,
611 channel_type=channel_type,
612 multisig_funding_keypair=None,
613 peer_features=peer_features,
614 channel_seed=random_gen.get_bytes(32),
615 )
616 alice_lconfig.funding_locked_received = True
617 alice_lconfig.dust_limit_sat = 200
618 alice_lconfig.to_self_delay = 5
619 alice_lconfig.reserve_sat = 0
620 alice_lconfig.max_accepted_htlcs = max_accepted_htlcs
621 alice_lconfig.max_htlc_value_in_flight_msat = local_max_inflight
622 # create bob's local config
623 bob_lconfig = bob_lnwallet.make_local_config_for_new_channel(
624 funding_sat=funding_sat,
625 push_msat=remote_msat,
626 initiator=REMOTE,
627 channel_type=channel_type,
628 multisig_funding_keypair=None,
629 peer_features=peer_features,
630 channel_seed=random_gen.get_bytes(32),
631 )
632 bob_lconfig.funding_locked_received = True
633 bob_lconfig.dust_limit_sat = 1300
634 bob_lconfig.to_self_delay = 4
635 bob_lconfig.reserve_sat = 0
636 bob_lconfig.max_accepted_htlcs = max_accepted_htlcs
637 bob_lconfig.max_htlc_value_in_flight_msat = remote_max_inflight
638
639 alice, bob = (
640 lnchannel.Channel(
641 _create_channel_state(
642 funding_txid=funding_txid,
643 funding_index=funding_index,
644 funding_sat=funding_sat,
645 is_initiator=True,
646 other_node_id=bob_pubkey,
647 channel_type=channel_type,
648 local_config=alice_lconfig,
649 remote_config=_convert_to_rconfig_from_lconfig(bob_lconfig),
650 ),
651 name=f"{alice_name}->{bob_name}",
652 initial_feerate=feerate,
653 lnworker=alice_lnwallet,
654 ),
655 lnchannel.Channel(
656 _create_channel_state(
657 funding_txid=funding_txid,
658 funding_index=funding_index,
659 funding_sat=funding_sat,
660 is_initiator=False,
661 other_node_id=alice_pubkey,
662 channel_type=channel_type,
663 local_config=bob_lconfig,
664 remote_config=_convert_to_rconfig_from_lconfig(alice_lconfig),
665 ),
666 name=f"{bob_name}->{alice_name}",
667 initial_feerate=feerate,
668 lnworker=bob_lnwallet,
669 )
670 )
671
672 alice.hm.log[LOCAL]['ctn'] = 0
673 bob.hm.log[LOCAL]['ctn'] = 0
674
675 alice._state = ChannelState.OPEN
676 bob._state = ChannelState.OPEN
677
678 a_out = alice.get_latest_commitment(LOCAL).outputs()
679 b_out = bob.get_next_commitment(REMOTE).outputs()
680 assert a_out == b_out, "\n" + pformat((a_out, b_out))
681
682 sig_from_bob, a_htlc_sigs = bob.sign_next_commitment()
683 sig_from_alice, b_htlc_sigs = alice.sign_next_commitment()
684
685 assert len(a_htlc_sigs) == 0
686 assert len(b_htlc_sigs) == 0
687
688 alice.open_with_first_pcp(alice.config[REMOTE].next_per_commitment_point, sig_from_bob)
689 bob.open_with_first_pcp(bob.config[REMOTE].next_per_commitment_point, sig_from_alice)
690
691 alice_second = lnutil.secret_to_pubkey(int.from_bytes(
692 lnutil.get_per_commitment_secret_from_seed(alice.config[LOCAL].per_commitment_secret_seed, lnutil.RevocationStore.START_INDEX - 1), "big"))
693 bob_second = lnutil.secret_to_pubkey(int.from_bytes(
694 lnutil.get_per_commitment_secret_from_seed(bob.config[LOCAL].per_commitment_secret_seed, lnutil.RevocationStore.START_INDEX - 1), "big"))
695
696 # from funding_locked:
697 alice.config[REMOTE].next_per_commitment_point = bob_second
698 bob.config[REMOTE].next_per_commitment_point = alice_second
699
700 alice._fallback_sweep_address = bitcoin.pubkey_to_address('p2wpkh', alice.config[LOCAL].payment_basepoint.pubkey.hex())
701 bob._fallback_sweep_address = bitcoin.pubkey_to_address('p2wpkh', bob.config[LOCAL].payment_basepoint.pubkey.hex())
702
703 assert alice.channel_id == bob.channel_id
704
705 return alice, bob