Files
purple-electrumwallet/electrum/lnworker.py
T

2597 lines
124 KiB
Python
Raw Normal View History

2018-10-25 19:34:31 +02:00
# Copyright (C) 2018 The Electrum developers
# Distributed under the MIT software license, see the accompanying
# file LICENCE or http://www.opensource.org/licenses/mit-license.php
2018-04-16 10:24:03 +02:00
import asyncio
2018-04-30 23:34:33 +02:00
import os
from decimal import Decimal
2018-07-13 17:05:04 +02:00
import random
import time
2022-05-18 17:07:18 +02:00
import operator
from enum import IntEnum
from typing import (Optional, Sequence, Tuple, List, Set, Dict, TYPE_CHECKING,
2021-07-13 16:44:17 +02:00
NamedTuple, Union, Mapping, Any, Iterable, AsyncGenerator, DefaultDict)
import threading
import socket
import aiohttp
2018-10-25 00:22:42 +02:00
import json
from datetime import datetime, timezone
2018-11-19 18:09:43 +01:00
from functools import partial
from collections import defaultdict
import concurrent
from concurrent import futures
import urllib.parse
import dns.resolver
import dns.exception
2022-02-08 12:34:49 +01:00
from aiorpcx import run_in_thread, NetAddress, ignore_after
2020-04-14 16:12:47 +02:00
from . import constants, util
2018-10-05 15:37:47 +02:00
from . import keystore
2022-02-08 12:34:49 +01:00
from .util import profiler, chunks, OldTaskGroup
from .invoices import Invoice, PR_UNPAID, PR_EXPIRED, PR_PAID, PR_INFLIGHT, PR_FAILED, PR_ROUTING, LN_EXPIRY_NEVER
from .util import NetworkRetryManager, JsonRPCClient, NotEnoughFunds
2022-06-16 12:05:05 +02:00
from .util import EventListener, event_listener
2019-11-13 09:20:19 +01:00
from .lnutil import LN_MAX_FUNDING_SAT
2018-10-05 15:37:47 +02:00
from .keystore import BIP32_KeyStore
2018-10-25 23:30:36 +02:00
from .bitcoin import COIN
from .bitcoin import opcodes, make_op_return, address_to_scripthash
from .transaction import Transaction
2021-03-09 09:55:55 +01:00
from .transaction import get_script_type_from_output_script
2018-10-25 23:30:36 +02:00
from .crypto import sha256
2019-03-06 16:13:28 +01:00
from .bip32 import BIP32Node
2023-02-17 11:35:03 +00:00
from .util import bfh, InvoiceError, resolve_dns_srv, is_ip_address, log_exceptions
2021-03-09 09:55:55 +01:00
from .crypto import chacha20_encrypt, chacha20_decrypt
from .util import ignore_exceptions, make_aiohttp_session
from .util import timestamp_to_datetime, random_shuffled_copy
from .util import MyEncoder, is_private_netaddress, UnrelatedTransactionException
from .logging import Logger
from .lntransport import LNTransport, LNResponderTransport, LNTransportBase
2019-09-05 18:31:51 +02:00
from .lnpeer import Peer, LN_P2P_NETWORK_TIMEOUT
2018-06-29 12:33:16 +02:00
from .lnaddr import lnencode, LnAddr, lndecode
from .ecc import der_sig_from_sig_string
2021-03-16 19:19:26 +01:00
from .lnchannel import Channel, AbstractChannel
from .lnchannel import ChannelState, PeerState, HTLCWithStatus
2020-10-28 08:17:25 +01:00
from .lnrater import LNRater
2019-08-14 21:38:02 +02:00
from . import lnutil
from .lnutil import funding_output_script
from .bitcoin import redeem_script_to_address
2019-09-06 18:09:05 +02:00
from .lnutil import (Outpoint, LNPeerAddr,
get_compressed_pubkey_from_bech32, extract_nodeid,
2018-10-05 15:37:47 +02:00
PaymentFailure, split_host_port, ConnStringFormatError,
2018-10-18 22:56:40 +02:00
generate_keypair, LnKeyFamily, LOCAL, REMOTE,
MIN_FINAL_CLTV_EXPIRY_FOR_INVOICE,
2019-01-21 21:27:27 +01:00
NUM_MAX_EDGES_IN_PAYMENT_PATH, SENT, RECEIVED, HTLCOwner,
UpdateAddHtlc, Direction, LnFeatures, ShortChannelID,
2021-02-19 09:27:28 +01:00
HtlcLog, derive_payment_secret_from_payment_preimage,
NoPathFound, InvalidGossipMsg)
from .lnutil import ln_dummy_address, ln_compare_features, IncompatibleLightningFeatures
2019-11-23 20:50:30 +01:00
from .transaction import PartialTxOutput, PartialTransaction, PartialTxInput
from .lnonion import OnionFailureCode, OnionRoutingFailure
from .lnmsg import decode_msg
from .i18n import _
from .lnrouter import (RouteEdge, LNPaymentRoute, LNPaymentPath, is_route_sane_to_use,
NoChannelPolicy, LNPathInconsistent)
from .address_synchronizer import TX_HEIGHT_LOCAL
from . import lnsweep
2020-04-03 18:54:02 +02:00
from .lnwatcher import LNWalletWatcher
2020-06-16 11:52:08 +02:00
from .crypto import pw_encode_with_version_and_mac, pw_decode_with_version_and_mac
2021-03-09 09:55:55 +01:00
from .lnutil import ImportedChannelBackupStorage, OnchainChannelBackupStorage
2020-03-13 11:44:29 +01:00
from .lnchannel import ChannelBackup
from .channel_db import UpdateStatus
from .channel_db import get_mychannel_info, get_mychannel_policy
2020-05-24 13:42:36 +02:00
from .submarine_swaps import SwapManager
2020-11-11 11:03:31 +01:00
from .channel_db import ChannelInfo, Policy
from .mpp_split import suggest_splits
2022-01-10 15:45:29 +01:00
from .trampoline import create_trampoline_route_and_onion, TRAMPOLINE_FEES, is_legacy_relay
if TYPE_CHECKING:
from .network import Network
from .wallet import Abstract_Wallet
2020-12-20 15:12:36 +01:00
from .channel_db import ChannelDB
from .simple_config import SimpleConfig
SAVED_PR_STATUS = [PR_PAID, PR_UNPAID] # status that are persisted
2020-03-10 13:27:02 +01:00
NUM_PEERS_TARGET = 4
2021-03-09 09:55:55 +01:00
# onchain channel backup data
CB_VERSION = 0
CB_MAGIC_BYTES = bytes([0, 0, 0, CB_VERSION])
FALLBACK_NODE_LIST_TESTNET = (
2019-11-20 17:14:14 +01:00
LNPeerAddr(host='203.132.95.10', port=9735, pubkey=bfh('038863cf8ab91046230f561cd5b386cbff8309fa02e3f0c3ed161a3aeb64a643b9')),
LNPeerAddr(host='2401:d002:4402:0:bf1d:986a:7598:6d49', port=9735, pubkey=bfh('038863cf8ab91046230f561cd5b386cbff8309fa02e3f0c3ed161a3aeb64a643b9')),
2019-11-20 17:14:14 +01:00
LNPeerAddr(host='50.116.3.223', port=9734, pubkey=bfh('03236a685d30096b26692dce0cf0fa7c8528bdf61dbf5363a3ef6d5c92733a3016')),
LNPeerAddr(host='3.16.119.191', port=9735, pubkey=bfh('03d5e17a3c213fe490e1b0c389f8cfcfcea08a29717d50a9f453735e0ab2a7c003')),
LNPeerAddr(host='34.250.234.192', port=9735, pubkey=bfh('03933884aaf1d6b108397e5efe5c86bcf2d8ca8d2f700eda99db9214fc2712b134')),
LNPeerAddr(host='88.99.209.230', port=9735, pubkey=bfh('0260d9119979caedc570ada883ff614c6efb93f7f7382e25d73ecbeba0b62df2d7')),
LNPeerAddr(host='160.16.233.215', port=9735, pubkey=bfh('023ea0a53af875580899da0ab0a21455d9c19160c4ea1b7774c9d4be6810b02d2c')),
LNPeerAddr(host='197.155.6.173', port=9735, pubkey=bfh('0269a94e8b32c005e4336bfb743c08a6e9beb13d940d57c479d95c8e687ccbdb9f')),
LNPeerAddr(host='2c0f:fb18:406::4', port=9735, pubkey=bfh('0269a94e8b32c005e4336bfb743c08a6e9beb13d940d57c479d95c8e687ccbdb9f')),
2019-11-20 17:14:14 +01:00
LNPeerAddr(host='163.172.94.64', port=9735, pubkey=bfh('030f0bf260acdbd3edcad84d7588ec7c5df4711e87e6a23016f989b8d3a4147230')),
LNPeerAddr(host='23.237.77.12', port=9735, pubkey=bfh('02312627fdf07fbdd7e5ddb136611bdde9b00d26821d14d94891395452f67af248')),
LNPeerAddr(host='197.155.6.172', port=9735, pubkey=bfh('02ae2f22b02375e3e9b4b4a2db4f12e1b50752b4062dbefd6e01332acdaf680379')),
LNPeerAddr(host='2c0f:fb18:406::3', port=9735, pubkey=bfh('02ae2f22b02375e3e9b4b4a2db4f12e1b50752b4062dbefd6e01332acdaf680379')),
LNPeerAddr(host='23.239.23.44', port=9740, pubkey=bfh('034fe52e98a0e9d3c21b767e1b371881265d8c7578c21f5afd6d6438da10348b36')),
LNPeerAddr(host='2600:3c01::f03c:91ff:fe05:349c', port=9740, pubkey=bfh('034fe52e98a0e9d3c21b767e1b371881265d8c7578c21f5afd6d6438da10348b36')),
)
2019-03-18 11:03:37 +01:00
FALLBACK_NODE_LIST_MAINNET = [
2019-11-20 17:14:14 +01:00
LNPeerAddr(host='172.81.181.3', port=9735, pubkey=bfh('0214382bdce7750dfcb8126df8e2b12de38536902dc36abcebdaeefdeca1df8284')),
LNPeerAddr(host='35.230.100.60', port=9735, pubkey=bfh('023f5e3582716bed96f6f26cfcd8037e07474d7b4743afdc8b07e692df63464d7e')),
LNPeerAddr(host='40.69.71.114', port=9735, pubkey=bfh('028303182c9885da93b3b25c9621d22cf34475e63c123942e402ab530c0556e675')),
LNPeerAddr(host='94.177.171.73', port=9735, pubkey=bfh('0276e09a267592e7451a939c932cf685f0754de382a3ca85d2fb3a864d4c365ad5')),
LNPeerAddr(host='34.236.113.58', port=9735, pubkey=bfh('02fa50c72ee1e2eb5f1b6d9c3032080c4c864373c4201dfa2966aa34eee1051f97')),
LNPeerAddr(host='52.50.244.44', port=9735, pubkey=bfh('030c3f19d742ca294a55c00376b3b355c3c90d61c6b6b39554dbc7ac19b141c14f')),
LNPeerAddr(host='157.245.68.47', port=9735, pubkey=bfh('03c2abfa93eacec04721c019644584424aab2ba4dff3ac9bdab4e9c97007491dda')),
LNPeerAddr(host='18.221.23.28', port=9735, pubkey=bfh('03abf6f44c355dec0d5aa155bdbdd6e0c8fefe318eff402de65c6eb2e1be55dc3e')),
LNPeerAddr(host='52.224.178.244', port=9735, pubkey=bfh('026b105ac13212c48714c6be9b11577a9ce10f10e1c88a45ce217e6331209faf8b')),
LNPeerAddr(host='34.239.230.56', port=9735, pubkey=bfh('03864ef025fde8fb587d989186ce6a4a186895ee44a926bfc370e2c366597a3f8f')),
LNPeerAddr(host='46.229.165.136', port=9735, pubkey=bfh('0390b5d4492dc2f5318e5233ab2cebf6d48914881a33ef6a9c6bcdbb433ad986d0')),
LNPeerAddr(host='157.230.28.160', port=9735, pubkey=bfh('0279c22ed7a068d10dc1a38ae66d2d6461e269226c60258c021b1ddcdfe4b00bc4')),
LNPeerAddr(host='74.108.13.152', port=9735, pubkey=bfh('0331f80652fb840239df8dc99205792bba2e559a05469915804c08420230e23c7c')),
LNPeerAddr(host='167.172.44.148', port=9735, pubkey=bfh('0395033b252c6f40e3756984162d68174e2bd8060a129c0d3462a9370471c6d28f')),
LNPeerAddr(host='138.68.14.104', port=9735, pubkey=bfh('03bb88ccc444534da7b5b64b4f7b15e1eccb18e102db0e400d4b9cfe93763aa26d')),
LNPeerAddr(host='3.124.63.44', port=9735, pubkey=bfh('0242a4ae0c5bef18048fbecf995094b74bfb0f7391418d71ed394784373f41e4f3')),
LNPeerAddr(host='2001:470:8:2e1::43', port=9735, pubkey=bfh('03baa70886d9200af0ffbd3f9e18d96008331c858456b16e3a9b41e735c6208fef')),
LNPeerAddr(host='2601:186:c100:6bcd:219:d1ff:fe75:dc2f', port=9735, pubkey=bfh('0298f6074a454a1f5345cb2a7c6f9fce206cd0bf675d177cdbf0ca7508dd28852f')),
LNPeerAddr(host='2001:41d0:e:734::1', port=9735, pubkey=bfh('03a503d8e30f2ff407096d235b5db63b4fcf3f89a653acb6f43d3fc492a7674019')),
LNPeerAddr(host='2a01:4f9:2b:2254::2', port=9735, pubkey=bfh('02f3069a342ae2883a6f29e275f06f28a56a6ea2e2d96f5888a3266444dcf542b6')),
LNPeerAddr(host='2a02:8070:24c1:100:528c:2997:6dbc:a054', port=9735, pubkey=bfh('02a45def9ae014fdd2603dd7033d157faa3a55a72b06a63ae22ef46d9fafdc6e8d')),
LNPeerAddr(host='2600:3c01::f03c:91ff:fe05:349c', port=9736, pubkey=bfh('02731b798b39a09f9f14e90ee601afb6ebb796d6e5797de14582a978770b33700f')),
LNPeerAddr(host='2a00:8a60:e012:a00::21', port=9735, pubkey=bfh('027ce055380348d7812d2ae7745701c9f93e70c1adeb2657f053f91df4f2843c71')),
LNPeerAddr(host='2604:a880:400:d1::8bd:1001', port=9735, pubkey=bfh('03649c72a4816f0cd546f84aafbd657e92a30ab474de7ab795e8b5650a427611f7')),
LNPeerAddr(host='2a01:4f8:c0c:7b31::1', port=9735, pubkey=bfh('02c16cca44562b590dd279c942200bdccfd4f990c3a69fad620c10ef2f8228eaff')),
LNPeerAddr(host='2001:41d0:1:b40d::1', port=9735, pubkey=bfh('026726a4b043d413b45b334876d17b8a98848129604429ec65532ba286a42efeac')),
2019-03-18 11:03:37 +01:00
]
2019-09-20 17:15:49 +02:00
from .trampoline import trampolines_by_id, hardcoded_trampoline_nodes, is_hardcoded_trampoline
2020-11-11 11:03:31 +01:00
class PaymentDirection(IntEnum):
2022-06-16 20:51:50 +02:00
SENT = 0
RECEIVED = 1
SELF_PAYMENT = 2
FORWARDING = 3
class PaymentInfo(NamedTuple):
2019-09-20 17:15:49 +02:00
payment_hash: bytes
2021-02-01 14:17:04 +01:00
amount_msat: Optional[int]
2019-09-20 17:15:49 +02:00
direction: int
status: int
class ErrorAddingPeer(Exception): pass
# set some feature flags as baseline for both LNWallet and LNGossip
# note that e.g. DATA_LOSS_PROTECT is needed for LNGossip as many peers require it
BASE_FEATURES = LnFeatures(0)\
| LnFeatures.OPTION_DATA_LOSS_PROTECT_OPT\
| LnFeatures.OPTION_STATIC_REMOTEKEY_OPT\
| LnFeatures.VAR_ONION_OPT\
| LnFeatures.PAYMENT_SECRET_OPT\
| LnFeatures.OPTION_UPFRONT_SHUTDOWN_SCRIPT_OPT\
# we do not want to receive unrequested gossip (see lnpeer.maybe_save_remote_update)
LNWALLET_FEATURES = BASE_FEATURES\
| LnFeatures.OPTION_DATA_LOSS_PROTECT_REQ\
| LnFeatures.OPTION_STATIC_REMOTEKEY_REQ\
2021-01-27 19:27:06 +01:00
| LnFeatures.GOSSIP_QUERIES_REQ\
2020-11-11 11:03:31 +01:00
| LnFeatures.BASIC_MPP_OPT\
| LnFeatures.OPTION_TRAMPOLINE_ROUTING_OPT_ELECTRUM\
2021-10-22 11:59:44 +02:00
| LnFeatures.OPTION_SHUTDOWN_ANYSEGWIT_OPT\
| LnFeatures.OPTION_CHANNEL_TYPE_OPT\
2023-01-07 12:20:03 +01:00
| LnFeatures.OPTION_SCID_ALIAS_OPT\
LNGOSSIP_FEATURES = BASE_FEATURES\
| LnFeatures.GOSSIP_QUERIES_OPT\
| LnFeatures.GOSSIP_QUERIES_REQ\
2022-06-16 12:05:05 +02:00
class LNWorker(Logger, EventListener, NetworkRetryManager[LNPeerAddr]):
INITIAL_TRAMPOLINE_FEE_LEVEL = 1 # only used for trampoline payments. set to 0 in tests.
def __init__(self, xprv, features: LnFeatures):
Logger.__init__(self)
NetworkRetryManager.__init__(
self,
max_retry_delay_normal=3600,
init_retry_delay_normal=600,
max_retry_delay_urgent=300,
init_retry_delay_urgent=4,
)
2020-04-15 21:32:53 +02:00
self.lock = threading.RLock()
2020-02-21 12:18:28 +01:00
self.node_keypair = generate_keypair(BIP32Node.from_xkey(xprv), LnKeyFamily.NODE_KEY)
2021-03-09 09:55:55 +01:00
self.backup_key = generate_keypair(BIP32Node.from_xkey(xprv), LnKeyFamily.BACKUP_CIPHER).privkey
2020-04-15 21:32:53 +02:00
self._peers = {} # type: Dict[bytes, Peer] # pubkey -> Peer # needs self.lock
2022-02-08 12:34:49 +01:00
self.taskgroup = OldTaskGroup()
self.listen_server = None # type: Optional[asyncio.AbstractServer]
self.features = features
2020-12-20 15:12:36 +01:00
self.network = None # type: Optional[Network]
self.config = None # type: Optional[SimpleConfig]
self.stopping_soon = False # whether we are being shut down
self._labels_cache = {} # txid -> str
2022-06-16 12:05:05 +02:00
self.register_callbacks()
2020-04-15 21:41:33 +02:00
2020-11-11 11:03:31 +01:00
@property
def channel_db(self):
return self.network.channel_db if self.network else None
def uses_trampoline(self):
return not bool(self.channel_db)
2020-04-15 21:32:53 +02:00
@property
def peers(self) -> Mapping[bytes, Peer]:
"""Returns a read-only copy of peers."""
with self.lock:
return self._peers.copy()
def channels_for_peer(self, node_id: bytes) -> Dict[bytes, Channel]:
2019-09-08 19:25:35 +02:00
return {}
def get_node_alias(self, node_id: bytes) -> Optional[str]:
"""Returns the alias of the node, or None if unknown."""
node_alias = None
if not self.uses_trampoline():
2020-12-19 15:10:15 +01:00
node_info = self.channel_db.get_node_info_for_node_id(node_id)
if node_info:
node_alias = node_info.alias
2020-12-19 15:10:15 +01:00
else:
2020-11-11 11:03:31 +01:00
for k, v in hardcoded_trampoline_nodes().items():
if v.pubkey.startswith(node_id):
2020-11-11 11:03:31 +01:00
node_alias = k
break
2020-12-19 15:10:15 +01:00
return node_alias
async def maybe_listen(self):
# FIXME: only one LNWorker can listen at a time (single port)
listen_addr = self.config.get('lightning_listen')
if listen_addr:
self.logger.info(f'lightning_listen enabled. will try to bind: {listen_addr!r}')
try:
netaddr = NetAddress.from_string(listen_addr)
except Exception as e:
self.logger.error(f"failed to parse config key 'lightning_listen'. got: {e!r}")
return
addr = str(netaddr.host)
async def cb(reader, writer):
transport = LNResponderTransport(self.node_keypair.privkey, reader, writer)
try:
node_id = await transport.handshake()
except Exception as e:
self.logger.info(f'handshake failure from incoming connection: {e!r}')
return
await self._add_peer_from_transport(node_id=node_id, transport=transport)
try:
self.listen_server = await asyncio.start_server(cb, addr, netaddr.port)
except OSError as e:
self.logger.error(f"cannot listen for lightning p2p. error: {e!r}")
@ignore_exceptions # don't kill outer taskgroup
async def main_loop(self):
2020-02-27 20:22:49 +01:00
self.logger.info("starting taskgroup.")
try:
async with self.taskgroup as group:
await group.spawn(asyncio.Event().wait) # run forever (until cancel)
except Exception as e:
self.logger.exception("taskgroup died.")
2020-02-27 20:22:49 +01:00
finally:
self.logger.info("taskgroup stopped.")
async def _maintain_connectivity(self):
while True:
await asyncio.sleep(1)
if self.stopping_soon:
return
now = time.time()
2020-04-15 21:32:53 +02:00
if len(self._peers) >= NUM_PEERS_TARGET:
continue
2019-06-18 13:49:31 +02:00
peers = await self._get_next_peers_to_try()
for peer in peers:
if self._can_retry_addr(peer, now=now):
try:
await self._add_peer(peer.host, peer.port, peer.pubkey)
except ErrorAddingPeer as e:
self.logger.info(f"failed to add peer: {peer}. exc: {e!r}")
async def _add_peer(self, host: str, port: int, node_id: bytes) -> Peer:
2020-04-15 21:32:53 +02:00
if node_id in self._peers:
return self._peers[node_id]
port = int(port)
peer_addr = LNPeerAddr(host, port, node_id)
self._trying_addr_now(peer_addr)
self.logger.info(f"adding peer {peer_addr}")
if node_id == self.node_keypair.pubkey:
raise ErrorAddingPeer("cannot connect to self")
transport = LNTransport(self.node_keypair.privkey, peer_addr,
proxy=self.network.proxy)
peer = await self._add_peer_from_transport(node_id=node_id, transport=transport)
return peer
async def _add_peer_from_transport(self, *, node_id: bytes, transport: LNTransportBase) -> Peer:
peer = Peer(self, node_id, transport)
2020-04-15 22:41:16 +02:00
with self.lock:
existing_peer = self._peers.get(node_id)
if existing_peer:
existing_peer.close_and_cleanup()
assert node_id not in self._peers
2020-04-15 22:41:16 +02:00
self._peers[node_id] = peer
await self.taskgroup.spawn(peer.main_loop())
return peer
def peer_closed(self, peer: Peer) -> None:
2020-04-15 22:41:16 +02:00
with self.lock:
2021-03-29 20:51:54 +02:00
peer2 = self._peers.get(peer.pubkey)
if peer2 is peer:
self._peers.pop(peer.pubkey)
def num_peers(self) -> int:
return sum([p.is_initialized() for p in self.peers.values()])
def start_network(self, network: 'Network'):
2020-01-09 18:21:48 +01:00
assert network
self.network = network
self.config = network.config
self._add_peers_from_config()
asyncio.run_coroutine_threadsafe(self.main_loop(), self.network.asyncio_loop)
async def stop(self):
if self.listen_server:
self.listen_server.close()
2022-06-16 12:05:05 +02:00
self.unregister_callbacks()
await self.taskgroup.cancel_remaining()
def _add_peers_from_config(self):
peer_list = self.config.get('lightning_peers', [])
for host, port, pubkey in peer_list:
asyncio.run_coroutine_threadsafe(
2019-06-05 11:08:16 +02:00
self._add_peer(host, int(port), bfh(pubkey)),
self.network.asyncio_loop)
def is_good_peer(self, peer: LNPeerAddr) -> bool:
2020-02-21 17:41:20 +01:00
# the purpose of this method is to filter peers that advertise the desired feature bits
# it is disabled for now, because feature bits published in node announcements seem to be unreliable
return True
node_id = peer.pubkey
node = self.channel_db._nodes.get(node_id)
if not node:
return False
try:
ln_compare_features(self.features, node.features)
except IncompatibleLightningFeatures:
return False
#self.logger.info(f'is_good {peer.host}')
return True
def on_peer_successfully_established(self, peer: Peer) -> None:
if isinstance(peer.transport, LNTransport):
peer_addr = peer.transport.peer_addr
# reset connection attempt count
self._on_connection_successfully_established(peer_addr)
if not self.uses_trampoline():
# add into channel db
self.channel_db.add_recent_peer(peer_addr)
# save network address into channels we might have with peer
for chan in peer.channels.values():
chan.add_or_update_peer_addr(peer_addr)
2019-06-18 13:49:31 +02:00
async def _get_next_peers_to_try(self) -> Sequence[LNPeerAddr]:
now = time.time()
2019-09-05 18:32:45 +02:00
await self.channel_db.data_loaded.wait()
# first try from recent peers
recent_peers = self.channel_db.get_recent_peers()
for peer in recent_peers:
if not peer:
continue
2020-04-15 21:32:53 +02:00
if peer.pubkey in self._peers:
2019-06-18 13:49:31 +02:00
continue
if not self._can_retry_addr(peer, now=now):
2019-06-18 13:49:31 +02:00
continue
if not self.is_good_peer(peer):
continue
return [peer]
# try random peer from graph
unconnected_nodes = self.channel_db.get_200_randomly_sorted_nodes_not_in(self.peers.keys())
if unconnected_nodes:
2019-06-18 13:49:31 +02:00
for node_id in unconnected_nodes:
addrs = self.channel_db.get_node_addresses(node_id)
if not addrs:
continue
2019-07-03 08:15:41 +02:00
host, port, timestamp = self.choose_preferred_address(list(addrs))
2019-11-26 00:15:33 +01:00
try:
peer = LNPeerAddr(host, port, node_id)
except ValueError:
continue
if not self._can_retry_addr(peer, now=now):
2019-06-18 13:49:31 +02:00
continue
if not self.is_good_peer(peer):
continue
2019-05-13 22:33:56 +02:00
#self.logger.info('taking random ln peer from our channel db')
return [peer]
# getting desperate... let's try hardcoded fallback list of peers
2021-03-21 00:34:25 -04:00
if constants.net in (constants.BitcoinTestnet,):
fallback_list = FALLBACK_NODE_LIST_TESTNET
2021-03-21 00:34:25 -04:00
elif constants.net in (constants.BitcoinMainnet,):
fallback_list = FALLBACK_NODE_LIST_MAINNET
else:
return [] # regtest??
fallback_list = [peer for peer in fallback_list if self._can_retry_addr(peer, now=now)]
if fallback_list:
return [random.choice(fallback_list)]
# last resort: try dns seeds (BOLT-10)
return await run_in_thread(self._get_peers_from_dns_seeds)
def _get_peers_from_dns_seeds(self) -> Sequence[LNPeerAddr]:
# NOTE: potentially long blocking call, do not run directly on asyncio event loop.
# Return several peers to reduce the number of dns queries.
if not constants.net.LN_DNS_SEEDS:
return []
dns_seed = random.choice(constants.net.LN_DNS_SEEDS)
self.logger.info('asking dns seed "{}" for ln peers'.format(dns_seed))
try:
# note: this might block for several seconds
# this will include bech32-encoded-pubkeys and ports
srv_answers = resolve_dns_srv('r{}.{}'.format(
constants.net.LN_REALM_BYTE, dns_seed))
except dns.exception.DNSException as e:
self.logger.info(f'failed querying (1) dns seed "{dns_seed}" for ln peers: {repr(e)}')
return []
random.shuffle(srv_answers)
num_peers = 2 * NUM_PEERS_TARGET
srv_answers = srv_answers[:num_peers]
# we now have pubkeys and ports but host is still needed
peers = []
for srv_ans in srv_answers:
try:
# note: this might block for several seconds
answers = dns.resolver.resolve(srv_ans['host'])
except dns.exception.DNSException as e:
self.logger.info(f'failed querying (2) dns seed "{dns_seed}" for ln peers: {repr(e)}')
continue
try:
ln_host = str(answers[0])
port = int(srv_ans['port'])
bech32_pubkey = srv_ans['host'].split('.')[0]
pubkey = get_compressed_pubkey_from_bech32(bech32_pubkey)
peers.append(LNPeerAddr(ln_host, port, pubkey))
except Exception as e:
self.logger.info(f'error with parsing peer from dns seed: {repr(e)}')
continue
self.logger.info(f'got {len(peers)} ln peers from dns seed')
return peers
@staticmethod
2019-10-15 15:41:18 +02:00
def choose_preferred_address(addr_list: Sequence[Tuple[str, int, int]]) -> Tuple[str, int, int]:
assert len(addr_list) >= 1
# choose first one that is an IP
2019-06-18 13:49:31 +02:00
for host, port, timestamp in addr_list:
if is_ip_address(host):
2019-06-18 13:49:31 +02:00
return host, port, timestamp
# otherwise choose one at random
# TODO maybe filter out onion if not on tor?
choice = random.choice(addr_list)
2019-06-18 13:49:31 +02:00
return choice
2022-06-16 12:05:05 +02:00
@event_listener
def on_event_proxy_set(self, *args):
2020-04-15 21:41:33 +02:00
for peer in self.peers.values():
peer.close_and_cleanup()
self._clear_addr_retry_times()
2020-04-15 21:41:33 +02:00
@log_exceptions
async def add_peer(self, connect_str: str) -> Peer:
node_id, rest = extract_nodeid(connect_str)
peer = self._peers.get(node_id)
if not peer:
if rest is not None:
host, port = split_host_port(rest)
else:
if self.uses_trampoline():
2020-11-11 11:03:31 +01:00
addr = trampolines_by_id().get(node_id)
if not addr:
2023-02-17 11:35:03 +00:00
raise ConnStringFormatError(_('Address unknown for node:') + ' ' + node_id.hex())
2020-11-11 11:03:31 +01:00
host, port = addr.host, addr.port
else:
addrs = self.channel_db.get_node_addresses(node_id)
if not addrs:
2023-02-17 11:35:03 +00:00
raise ConnStringFormatError(_('Don\'t know any addresses for node:') + ' ' + node_id.hex())
2020-11-11 11:03:31 +01:00
host, port, timestamp = self.choose_preferred_address(list(addrs))
port = int(port)
# Try DNS-resolving the host (if needed). This is simply so that
# the caller gets a nice exception if it cannot be resolved.
try:
await asyncio.get_running_loop().getaddrinfo(host, port)
except socket.gaierror:
raise ConnStringFormatError(_('Hostname does not resolve (getaddrinfo failed)'))
# add peer
peer = await self._add_peer(host, port, node_id)
return peer
class LNGossip(LNWorker):
max_age = 14*24*3600
2020-04-12 12:29:46 +02:00
LOGGING_SHORTCUT = 'g'
2020-04-14 16:12:47 +02:00
def __init__(self):
seed = os.urandom(32)
node = BIP32Node.from_rootseed(seed, xtype='standard')
xprv = node.to_xprv()
super().__init__(xprv, LNGOSSIP_FEATURES)
2019-05-13 22:33:56 +02:00
self.unknown_ids = set()
def start_network(self, network: 'Network'):
super().start_network(network)
for coro in [
self._maintain_connectivity(),
self.maintain_db(),
]:
tg_coro = self.taskgroup.spawn(coro)
asyncio.run_coroutine_threadsafe(tg_coro, self.network.asyncio_loop)
async def maintain_db(self):
2020-10-08 06:36:02 +02:00
await self.channel_db.data_loaded.wait()
while True:
2019-07-11 13:50:21 +02:00
if len(self.unknown_ids) == 0:
self.channel_db.prune_old_policies(self.max_age)
self.channel_db.prune_orphaned_channels()
await asyncio.sleep(120)
async def add_new_ids(self, ids: Iterable[bytes]):
2019-06-18 13:49:31 +02:00
known = self.channel_db.get_channel_ids()
2019-05-15 16:09:23 +02:00
new = set(ids) - set(known)
2019-05-13 22:33:56 +02:00
self.unknown_ids.update(new)
2020-04-14 16:12:47 +02:00
util.trigger_callback('unknown_channels', len(self.unknown_ids))
util.trigger_callback('gossip_peers', self.num_peers())
util.trigger_callback('ln_gossip_sync_progress')
def get_ids_to_query(self) -> Sequence[bytes]:
2019-07-11 13:50:21 +02:00
N = 500
2019-05-13 22:33:56 +02:00
l = list(self.unknown_ids)
self.unknown_ids = set(l[N:])
2020-04-14 16:12:47 +02:00
util.trigger_callback('unknown_channels', len(self.unknown_ids))
util.trigger_callback('ln_gossip_sync_progress')
2019-05-13 22:33:56 +02:00
return l[0:N]
2020-10-28 08:17:25 +01:00
def get_sync_progress_estimate(self) -> Tuple[Optional[int], Optional[int], Optional[int]]:
"""Estimates the gossip synchronization process and returns the number
of synchronized channels, the total channels in the network and a
rescaled percentage of the synchronization process."""
if self.num_peers() == 0:
2020-10-28 08:17:25 +01:00
return None, None, None
nchans_with_0p, nchans_with_1p, nchans_with_2p = self.channel_db.get_num_channels_partitioned_by_policy_count()
num_db_channels = nchans_with_0p + nchans_with_1p + nchans_with_2p
# some channels will never have two policies (only one is in gossip?...)
# so if we have at least 1 policy for a channel, we consider that channel "complete" here
current_est = num_db_channels - nchans_with_0p
total_est = len(self.unknown_ids) + num_db_channels
2020-10-28 08:17:25 +01:00
progress = current_est / total_est if total_est and current_est else 0
progress_percent = (1.0 / 0.95 * progress) * 100
progress_percent = min(progress_percent, 100)
progress_percent = round(progress_percent)
# take a minimal number of synchronized channels to get a more accurate
# percentage estimate
if current_est < 200:
progress_percent = 0
return current_est, total_est, progress_percent
async def process_gossip(self, chan_anns, node_anns, chan_upds):
# note: we run in the originating peer's TaskGroup, so we can safely raise here
# and disconnect only from that peer
await self.channel_db.data_loaded.wait()
self.logger.debug(f'process_gossip {len(chan_anns)} {len(node_anns)} {len(chan_upds)}')
# channel announcements
2021-03-15 20:37:49 +01:00
def process_chan_anns():
for payload in chan_anns:
self.channel_db.verify_channel_announcement(payload)
self.channel_db.add_channel_announcements(chan_anns)
await run_in_thread(process_chan_anns)
# node announcements
2021-03-15 20:37:49 +01:00
def process_node_anns():
for payload in node_anns:
self.channel_db.verify_node_announcement(payload)
self.channel_db.add_node_announcements(node_anns)
await run_in_thread(process_node_anns)
# channel updates
2021-03-15 20:37:49 +01:00
categorized_chan_upds = await run_in_thread(partial(
self.channel_db.add_channel_updates,
chan_upds,
max_age=self.max_age))
orphaned = categorized_chan_upds.orphaned
if orphaned:
self.logger.info(f'adding {len(orphaned)} unknown channel ids')
orphaned_ids = [c['short_channel_id'] for c in orphaned]
await self.add_new_ids(orphaned_ids)
if categorized_chan_upds.good:
self.logger.debug(f'process_gossip: {len(categorized_chan_upds.good)}/{len(chan_upds)}')
class LNWallet(LNWorker):
lnwatcher: Optional['LNWalletWatcher']
2021-03-10 17:09:07 +01:00
MPP_EXPIRY = 120
2021-03-11 20:35:21 +01:00
TIMEOUT_SHUTDOWN_FAIL_PENDING_HTLCS = 3 # seconds
PAYMENT_TIMEOUT = 120
2020-06-18 18:18:33 +02:00
def __init__(self, wallet: 'Abstract_Wallet', xprv):
self.wallet = wallet
2020-02-05 15:13:37 +01:00
self.db = wallet.db
Logger.__init__(self)
LNWorker.__init__(self, xprv, LNWALLET_FEATURES)
2020-12-20 15:12:36 +01:00
self.config = wallet.config
self.lnwatcher = None
2020-10-28 08:17:25 +01:00
self.lnrater: LNRater = None
2022-06-14 12:50:04 +02:00
self.payment_info = self.db.get_dict('lightning_payments') # RHASH -> amount, direction, is_paid
2020-02-05 15:13:37 +01:00
self.preimages = self.db.get_dict('lightning_preimages') # RHASH -> preimage
# note: this sweep_address is only used as fallback; as it might result in address-reuse
self.logs = defaultdict(list) # type: Dict[str, List[HtlcLog]] # key is RHASH # (not persisted)
# used in tests
self.enable_htlc_settle = True
self.enable_htlc_forwarding = True
# note: accessing channels (besides simple lookup) needs self.lock!
self._channels = {} # type: Dict[bytes, Channel]
2020-02-05 15:13:37 +01:00
channels = self.db.get_dict("channels")
for channel_id, c in random_shuffled_copy(channels.items()):
self._channels[bfh(channel_id)] = Channel(c, lnworker=self)
2020-02-04 13:35:58 +01:00
2021-03-16 19:19:26 +01:00
self._channel_backups = {} # type: Dict[bytes, ChannelBackup]
2021-03-09 09:55:55 +01:00
# order is important: imported should overwrite onchain
for name in ["onchain_channel_backups", "imported_channel_backups"]:
channel_backups = self.db.get_dict(name)
for channel_id, storage in channel_backups.items():
self._channel_backups[bfh(channel_id)] = ChannelBackup(storage, lnworker=self)
2021-02-05 17:09:47 +01:00
self.sent_htlcs = defaultdict(asyncio.Queue) # type: Dict[bytes, asyncio.Queue[HtlcLog]]
self.sent_htlcs_info = dict() # (RHASH, scid, htlc_id) -> route, payment_secret, amount_msat, bucket_msat, trampoline_fee_level
self.sent_buckets = dict() # payment_secret -> (amount_sent, amount_failed)
2021-03-11 16:53:55 +01:00
self.received_mpp_htlcs = dict() # RHASH -> mpp_status, htlc_set
2019-01-26 17:57:00 +01:00
self.swap_manager = SwapManager(wallet=self.wallet, lnworker=self)
# detect inflight payments
2021-02-05 11:33:45 +01:00
self.inflight_payments = set() # (not persisted) keys of invoices that are in PR_INFLIGHT state
for payment_hash in self.get_payments(status='inflight').keys():
self.set_invoice_status(payment_hash.hex(), PR_INFLIGHT)
2021-02-09 15:09:27 +01:00
self.trampoline_forwarding_failures = {} # todo: should be persisted
2021-11-04 19:16:02 +01:00
# map forwarded htlcs (fw_info=(scid_hex, htlc_id)) to originating peer pubkeys
self.downstream_htlc_to_upstream_peer_map = {} # type: Dict[Tuple[str, int], bytes]
2021-02-09 15:09:27 +01:00
def has_deterministic_node_id(self) -> bool:
2021-03-09 09:55:55 +01:00
return bool(self.db.get('lightning_xprv'))
def can_have_recoverable_channels(self) -> bool:
return (self.has_deterministic_node_id()
and not (self.config.get('lightning_listen')))
def has_recoverable_channels(self) -> bool:
"""Whether *future* channels opened by this wallet would be recoverable
from seed (via putting OP_RETURN outputs into funding txs).
"""
return (self.can_have_recoverable_channels()
and self.config.get('use_recoverable_channels', True))
2021-03-09 09:55:55 +01:00
@property
def channels(self) -> Mapping[bytes, Channel]:
"""Returns a read-only copy of channels."""
with self.lock:
return self._channels.copy()
@property
2021-03-16 19:19:26 +01:00
def channel_backups(self) -> Mapping[bytes, ChannelBackup]:
"""Returns a read-only copy of channels."""
with self.lock:
return self._channel_backups.copy()
def get_channel_objects(self) -> Mapping[bytes, AbstractChannel]:
r = self.channel_backups
r.update(self.channels)
return r
def get_channel_by_id(self, channel_id: bytes) -> Optional[Channel]:
return self._channels.get(channel_id, None)
2022-07-13 10:14:34 +02:00
def get_channel_by_scid(self, scid: bytes) -> Optional[Channel]:
for chan in self._channels.values():
if chan.short_channel_id == scid:
return chan
def diagnostic_name(self):
return self.wallet.diagnostic_name()
2019-07-05 14:42:09 +02:00
@ignore_exceptions
@log_exceptions
async def sync_with_local_watchtower(self):
watchtower = self.network.local_watchtower
if watchtower:
while True:
for chan in self.channels.values():
await self.sync_channel_with_watchtower(chan, watchtower.sweepstore)
2019-07-05 14:42:09 +02:00
await asyncio.sleep(5)
@ignore_exceptions
@log_exceptions
async def sync_with_remote_watchtower(self):
while True:
# periodically poll if the user updated 'watchtower_url'
2019-07-05 14:42:09 +02:00
await asyncio.sleep(5)
watchtower_url = self.config.get('watchtower_url')
if not watchtower_url:
continue
parsed_url = urllib.parse.urlparse(watchtower_url)
if not (parsed_url.scheme == 'https' or is_private_netaddress(parsed_url.hostname)):
self.logger.warning(f"got watchtower URL for remote tower but we won't use it! "
f"can only use HTTPS (except if private IP): not using {watchtower_url!r}")
continue
# try to sync with the remote watchtower
try:
async with make_aiohttp_session(proxy=self.network.proxy) as session:
watchtower = JsonRPCClient(session, watchtower_url)
watchtower.add_method('get_ctn')
watchtower.add_method('add_sweep_tx')
for chan in self.channels.values():
await self.sync_channel_with_watchtower(chan, watchtower)
except aiohttp.client_exceptions.ClientConnectorError:
self.logger.info(f'could not contact remote watchtower {watchtower_url}')
2019-07-05 14:42:09 +02:00
async def sync_channel_with_watchtower(self, chan: Channel, watchtower):
2019-07-05 14:42:09 +02:00
outpoint = chan.funding_outpoint.to_str()
addr = chan.get_funding_address()
current_ctn = chan.get_oldest_unrevoked_ctn(REMOTE)
watchtower_ctn = await watchtower.get_ctn(outpoint, addr)
2019-07-05 14:42:09 +02:00
for ctn in range(watchtower_ctn + 1, current_ctn):
sweeptxs = chan.create_sweeptxs(ctn)
for tx in sweeptxs:
2019-10-23 17:09:41 +02:00
await watchtower.add_sweep_tx(outpoint, ctn, tx.inputs()[0].prevout.to_str(), tx.serialize())
2019-07-05 14:42:09 +02:00
2019-01-26 17:57:00 +01:00
def start_network(self, network: 'Network'):
super().start_network(network)
self.lnwatcher = LNWalletWatcher(self, network)
self.swap_manager.start_network(network=network, lnwatcher=self.lnwatcher)
2020-10-28 08:17:25 +01:00
self.lnrater = LNRater(self, network)
2020-03-13 11:44:29 +01:00
for chan in self.channels.values():
2022-08-15 13:54:24 +00:00
if not chan.is_redeemed():
self.lnwatcher.add_channel(chan.funding_outpoint.to_str(), chan.get_funding_address())
for cb in self.channel_backups.values():
2022-08-15 13:54:24 +00:00
if not cb.is_redeemed():
self.lnwatcher.add_channel(cb.funding_outpoint.to_str(), cb.get_funding_address())
2019-06-18 13:49:31 +02:00
for coro in [
self.maybe_listen(),
self.lnwatcher.trigger_callbacks(), # shortcut (don't block) if funding tx locked and verified
2019-07-05 14:42:09 +02:00
self.reestablish_peers_and_channels(),
self.sync_with_local_watchtower(),
self.sync_with_remote_watchtower(),
]:
tg_coro = self.taskgroup.spawn(coro)
asyncio.run_coroutine_threadsafe(tg_coro, self.network.asyncio_loop)
async def stop(self):
self.stopping_soon = True
if self.listen_server: # stop accepting new peers
self.listen_server.close()
2021-03-11 20:35:21 +01:00
async with ignore_after(self.TIMEOUT_SHUTDOWN_FAIL_PENDING_HTLCS):
await self.wait_for_received_pending_htlcs_to_get_removed()
2021-03-11 20:35:21 +01:00
await LNWorker.stop(self)
if self.lnwatcher:
await self.lnwatcher.stop()
self.lnwatcher = None
async def wait_for_received_pending_htlcs_to_get_removed(self):
assert self.stopping_soon is True
# We try to fail pending MPP HTLCs, and wait a bit for them to get removed.
# Note: even without MPP, if we just failed/fulfilled an HTLC, it is good
# to wait a bit for it to become irrevocably removed.
# Note: we don't wait for *all htlcs* to get removed, only for those
# that we can already fail/fulfill. e.g. forwarded htlcs cannot be removed
2022-02-08 12:34:49 +01:00
async with OldTaskGroup() as group:
for peer in self.peers.values():
await group.spawn(peer.wait_one_htlc_switch_iteration())
while True:
if all(not peer.received_htlcs_pending_removal for peer in self.peers.values()):
break
2022-02-08 12:34:49 +01:00
async with OldTaskGroup(wait=any) as group:
for peer in self.peers.values():
await group.spawn(peer.received_htlc_removed_event.wait())
2019-05-13 22:33:56 +02:00
def peer_closed(self, peer):
for chan in self.channels_for_peer(peer.pubkey).values():
chan.peer_state = PeerState.DISCONNECTED
util.trigger_callback('channel', self.wallet, chan)
super().peer_closed(peer)
2019-05-13 22:33:56 +02:00
def get_payments(self, *, status=None) -> Mapping[bytes, List[HTLCWithStatus]]:
out = defaultdict(list)
for chan in self.channels.values():
d = chan.get_payments(status=status)
for payment_hash, plist in d.items():
out[payment_hash] += plist
2019-01-29 19:01:04 +01:00
return out
def get_payment_value(
2022-06-16 20:51:50 +02:00
self, info: Optional['PaymentInfo'],
plist: List[HTLCWithStatus]) -> Tuple[PaymentDirection, int, Optional[int], int]:
2022-06-16 20:51:50 +02:00
""" fee_msat is included in amount_msat"""
assert plist
2022-06-16 20:51:50 +02:00
amount_msat = sum(int(x.direction) * x.htlc.amount_msat for x in plist)
if all(x.direction == SENT for x in plist):
direction = PaymentDirection.SENT
2022-06-29 13:33:04 +02:00
fee_msat = (- info.amount_msat - amount_msat) if info else None
2022-06-16 20:51:50 +02:00
elif all(x.direction == RECEIVED for x in plist):
direction = PaymentDirection.RECEIVED
fee_msat = None
elif amount_msat < 0:
direction = PaymentDirection.SELF_PAYMENT
fee_msat = - amount_msat
else:
direction = PaymentDirection.FORWARDING
fee_msat = - amount_msat
timestamp = min([htlc_with_status.htlc.timestamp for htlc_with_status in plist])
2022-06-16 20:51:50 +02:00
return direction, amount_msat, fee_msat, timestamp
2020-05-27 09:59:53 +02:00
def get_lightning_history(self):
out = {}
for payment_hash, plist in self.get_payments(status='settled').items():
if len(plist) == 0:
continue
key = payment_hash.hex()
2020-05-06 12:32:33 +02:00
info = self.get_payment_info(payment_hash)
2022-06-16 20:51:50 +02:00
direction, amount_msat, fee_msat, timestamp = self.get_payment_value(info, plist)
label = self.wallet.get_label_for_rhash(key)
if not label and direction == PaymentDirection.FORWARDING:
label = _('Forwarding')
2020-02-18 12:34:09 +01:00
preimage = self.get_preimage(payment_hash).hex()
item = {
'type': 'payment',
'label': label,
'timestamp': timestamp or 0,
'date': timestamp_to_datetime(timestamp),
'direction': direction,
'amount_msat': amount_msat,
'fee_msat': fee_msat,
2019-09-20 17:15:49 +02:00
'payment_hash': key,
2020-02-18 12:34:09 +01:00
'preimage': preimage,
}
# add group_id to swap transactions
2020-05-28 10:59:20 +02:00
swap = self.swap_manager.get_swap(payment_hash)
if swap:
if swap.is_reverse:
item['group_id'] = swap.spending_txid
item['group_label'] = 'Reverse swap' + ' ' + self.config.format_amount_and_units(swap.lightning_amount)
2020-05-26 10:02:27 +02:00
else:
item['group_id'] = swap.funding_txid
item['group_label'] = 'Forward swap' + ' ' + self.config.format_amount_and_units(swap.onchain_amount)
2020-05-26 10:02:27 +02:00
# done
out[payment_hash] = item
return out
def get_label_for_txid(self, txid: str) -> str:
return self._labels_cache.get(txid)
def get_onchain_history(self):
current_height = self.wallet.adb.get_local_height()
out = {}
# add funding events
for chan in self.channels.values():
item = chan.get_funding_height()
2019-08-12 18:14:21 +02:00
if item is None:
continue
funding_txid, funding_height, funding_timestamp = item
tx_height = self.wallet.adb.get_tx_height(funding_txid)
self._labels_cache[funding_txid] = _('Open channel') + ' ' + chan.get_id_for_log()
item = {
2023-02-17 11:35:03 +00:00
'channel_id': chan.channel_id.hex(),
'type': 'channel_opening',
'label': self.get_label_for_txid(funding_txid),
'txid': funding_txid,
'amount_msat': chan.balance(LOCAL, ctn=0),
'direction': PaymentDirection.RECEIVED,
2021-03-12 16:28:42 +01:00
'timestamp': tx_height.timestamp,
'date': timestamp_to_datetime(tx_height.timestamp),
2021-03-12 16:38:48 +01:00
'fee_sat': None,
'fee_msat': None,
2021-03-12 16:28:42 +01:00
'height': tx_height.height,
'confirmations': tx_height.conf,
}
out[funding_txid] = item
item = chan.get_closing_height()
if item is None:
continue
closing_txid, closing_height, closing_timestamp = item
tx_height = self.wallet.adb.get_tx_height(closing_txid)
self._labels_cache[closing_txid] = _('Close channel') + ' ' + chan.get_id_for_log()
item = {
2023-02-17 11:35:03 +00:00
'channel_id': chan.channel_id.hex(),
2019-03-01 05:29:42 +01:00
'txid': closing_txid,
'label': self.get_label_for_txid(closing_txid),
'type': 'channel_closure',
2019-05-06 15:58:12 +02:00
'amount_msat': -chan.balance_minus_outgoing_htlcs(LOCAL),
'direction': PaymentDirection.SENT,
2021-03-12 16:28:42 +01:00
'timestamp': tx_height.timestamp,
'date': timestamp_to_datetime(tx_height.timestamp),
2021-03-12 16:38:48 +01:00
'fee_sat': None,
'fee_msat': None,
2021-03-12 16:28:42 +01:00
'height': tx_height.height,
'confirmations': tx_height.conf,
}
out[closing_txid] = item
# add info about submarine swaps
settled_payments = self.get_payments(status='settled')
for payment_hash_hex, swap in self.swap_manager.swaps.items():
txid = swap.spending_txid if swap.is_reverse else swap.funding_txid
if txid is None:
continue
payment_hash = bytes.fromhex(payment_hash_hex)
if payment_hash in settled_payments:
plist = settled_payments[payment_hash]
info = self.get_payment_info(payment_hash)
2022-06-16 20:51:50 +02:00
direction, amount_msat, fee_msat, timestamp = self.get_payment_value(info, plist)
else:
amount_msat = 0
label = 'Reverse swap' if swap.is_reverse else 'Forward swap'
delta = current_height - swap.locktime
2023-01-24 14:45:55 +01:00
if self.wallet.adb.is_mine(swap.lockup_address):
tx_height = self.wallet.adb.get_tx_height(swap.funding_txid)
if swap.is_reverse and tx_height.height <= 0:
label += ' (%s)' % _('waiting for funding tx confirmation')
if not swap.is_reverse and not swap.is_redeemed and swap.spending_txid is None and delta < 0:
label += f' (refundable in {-delta} blocks)' # fixme: only if unspent
self._labels_cache[txid] = label
out[txid] = {
'txid': txid,
'group_id': txid,
'amount_msat': 0,
#'amount_msat': amount_msat, # must not be added
'type': 'swap',
'label': self.get_label_for_txid(txid),
}
return out
def get_history(self):
out = list(self.get_lightning_history().values()) + list(self.get_onchain_history().values())
2019-02-01 21:22:39 +01:00
# sort by timestamp
out.sort(key=lambda x: (x.get('timestamp') or float("inf")))
balance_msat = 0
for item in out:
balance_msat += item['amount_msat']
item['balance_msat'] = balance_msat
return out
2020-10-28 08:17:25 +01:00
def channel_peers(self) -> List[bytes]:
node_ids = [chan.node_id for chan in self.channels.values() if not chan.is_closed()]
return node_ids
def channels_for_peer(self, node_id):
assert type(node_id) is bytes
return {chan_id: chan for (chan_id, chan) in self.channels.items()
if chan.node_id == node_id}
def channel_state_changed(self, chan: Channel):
if type(chan) is Channel:
self.save_channel(chan)
util.trigger_callback('channel', self.wallet, chan)
2020-04-10 19:50:20 +02:00
def save_channel(self, chan: Channel):
assert type(chan) is Channel
if chan.config[REMOTE].next_per_commitment_point == chan.config[REMOTE].current_per_commitment_point:
2018-06-20 15:46:22 +02:00
raise Exception("Tried to save channel with next_point == current_point, this should not happen")
2020-02-05 15:13:37 +01:00
self.wallet.save_db()
util.trigger_callback('channel', self.wallet, chan)
2021-03-16 19:19:26 +01:00
def channel_by_txo(self, txo: str) -> Optional[AbstractChannel]:
for chan in self.channels.values():
if chan.funding_outpoint.to_str() == txo:
2018-12-04 20:50:24 +01:00
return chan
for chan in self.channel_backups.values():
if chan.funding_outpoint.to_str() == txo:
return chan
2018-12-04 20:50:24 +01:00
async def handle_onchain_state(self, chan: Channel):
if type(chan) is ChannelBackup:
util.trigger_callback('channel', self.wallet, chan)
return
if (chan.get_state() in (ChannelState.OPEN, ChannelState.SHUTDOWN)
and chan.should_be_closed_due_to_expiring_htlcs(self.network.get_local_height())):
2019-11-22 15:06:37 +01:00
self.logger.info(f"force-closing due to expiring htlcs")
await self.schedule_force_closing(chan.channel_id)
2019-10-29 08:02:14 +01:00
elif chan.get_state() == ChannelState.FUNDED:
2020-04-15 21:32:53 +02:00
peer = self._peers.get(chan.node_id)
if peer and peer.is_initialized():
2023-01-07 12:20:03 +01:00
peer.send_channel_ready(chan)
2019-10-29 08:02:14 +01:00
elif chan.get_state() == ChannelState.OPEN:
2020-04-15 21:32:53 +02:00
peer = self._peers.get(chan.node_id)
if peer:
await peer.maybe_update_fee(chan)
conf = self.lnwatcher.adb.get_tx_height(chan.funding_outpoint.txid).conf
peer.on_network_update(chan, conf)
2019-10-29 08:02:14 +01:00
elif chan.get_state() == ChannelState.FORCE_CLOSING:
2020-02-16 12:59:09 +01:00
force_close_tx = chan.force_close_tx()
txid = force_close_tx.txid()
height = self.lnwatcher.adb.get_tx_height(txid).height
2019-11-22 15:06:37 +01:00
if height == TX_HEIGHT_LOCAL:
self.logger.info('REBROADCASTING CLOSING TX')
2020-02-16 12:59:09 +01:00
await self.network.try_broadcasting(force_close_tx, 'force-close')
2019-11-22 15:06:37 +01:00
2019-08-15 13:17:16 +02:00
@log_exceptions
async def _open_channel_coroutine(
self, *,
connect_str: str,
funding_tx: PartialTransaction,
funding_sat: int,
push_sat: int,
password: Optional[str]) -> Tuple[Channel, PartialTransaction]:
2019-06-18 13:49:31 +02:00
peer = await self.add_peer(connect_str)
coro = peer.channel_establishment_flow(
2019-11-13 09:20:19 +01:00
funding_tx=funding_tx,
funding_sat=funding_sat,
push_msat=push_sat * 1000,
temp_channel_id=os.urandom(32))
chan, funding_tx = await asyncio.wait_for(coro, LN_P2P_NETWORK_TIMEOUT)
2020-04-14 16:12:47 +02:00
util.trigger_callback('channels_updated', self.wallet)
self.wallet.adb.add_transaction(funding_tx) # save tx as local into the wallet
self.wallet.sign_transaction(funding_tx, password)
self.wallet.set_label(funding_tx.txid(), _('Open channel'))
if funding_tx.is_complete():
await self.network.try_broadcasting(funding_tx, 'open_channel')
return chan, funding_tx
2018-05-28 11:55:20 +02:00
def add_channel(self, chan: Channel):
2020-02-04 13:35:58 +01:00
with self.lock:
self._channels[chan.channel_id] = chan
self.lnwatcher.add_channel(chan.funding_outpoint.to_str(), chan.get_funding_address())
def add_new_channel(self, chan: Channel):
self.add_channel(chan)
channels_db = self.db.get_dict('channels')
channels_db[chan.channel_id.hex()] = chan.storage
for addr in chan.get_wallet_addresses_channel_might_want_reserved():
self.wallet.set_reserved_state_of_address(addr, reserved=True)
try:
self.save_channel(chan)
except:
chan.set_state(ChannelState.REDEEMED)
self.remove_channel(chan.channel_id)
raise
2020-02-04 13:35:58 +01:00
2021-03-09 09:55:55 +01:00
def cb_data(self, node_id):
return CB_MAGIC_BYTES + node_id[0:16]
def decrypt_cb_data(self, encrypted_data, funding_address):
funding_scripthash = bytes.fromhex(address_to_scripthash(funding_address))
nonce = funding_scripthash[0:12]
2021-03-09 09:55:55 +01:00
return chacha20_decrypt(key=self.backup_key, data=encrypted_data, nonce=nonce)
def encrypt_cb_data(self, data, funding_address):
funding_scripthash = bytes.fromhex(address_to_scripthash(funding_address))
nonce = funding_scripthash[0:12]
2021-03-09 09:55:55 +01:00
return chacha20_encrypt(key=self.backup_key, data=data, nonce=nonce)
def mktx_for_open_channel(
self, *,
coins: Sequence[PartialTxInput],
funding_sat: int,
2021-03-09 09:55:55 +01:00
node_id: bytes,
fee_est=None) -> PartialTransaction:
2021-03-09 09:55:55 +01:00
outputs = [PartialTxOutput.from_address_and_value(ln_dummy_address(), funding_sat)]
if self.has_recoverable_channels():
dummy_scriptpubkey = make_op_return(self.cb_data(node_id))
outputs.append(PartialTxOutput(scriptpubkey=dummy_scriptpubkey, value=0))
2019-11-13 09:20:19 +01:00
tx = self.wallet.make_unsigned_transaction(
coins=coins,
outputs=outputs,
fee=fee_est)
tx.set_rbf(False)
return tx
def suggest_funding_amount(self, amount_to_pay, coins):
""" wether we can pay amount_sat after opening a new channel"""
num_sats_can_send = int(self.num_sats_can_send())
lightning_needed = amount_to_pay - num_sats_can_send
assert lightning_needed > 0
min_funding_sat = lightning_needed + (lightning_needed // 20) + 1000 # safety margin
min_funding_sat = max(min_funding_sat, 100_000) # at least 1mBTC
if min_funding_sat > LN_MAX_FUNDING_SAT:
return
fee_est = partial(self.config.estimate_fee, allow_fallback_to_static_rates=True) # to avoid NoDynamicFeeEstimates
try:
self.mktx_for_open_channel(coins=coins, funding_sat=min_funding_sat, node_id=bytes(32), fee_est=fee_est)
funding_sat = min_funding_sat
except NotEnoughFunds:
return
# if available, suggest twice that amount:
if 2 * min_funding_sat <= LN_MAX_FUNDING_SAT:
try:
self.mktx_for_open_channel(coins=coins, funding_sat=2*min_funding_sat, node_id=bytes(32), fee_est=fee_est)
funding_sat = 2 * min_funding_sat
except NotEnoughFunds:
pass
return funding_sat, min_funding_sat
def open_channel(self, *, connect_str: str, funding_tx: PartialTransaction,
funding_sat: int, push_amt_sat: int, password: str = None) -> Tuple[Channel, PartialTransaction]:
2019-11-23 20:50:30 +01:00
if funding_sat > LN_MAX_FUNDING_SAT:
raise Exception(_("Requested channel capacity is over protocol allowed maximum."))
coro = self._open_channel_coroutine(
connect_str=connect_str, funding_tx=funding_tx, funding_sat=funding_sat,
push_sat=push_amt_sat, password=password)
2019-06-05 11:08:16 +02:00
fut = asyncio.run_coroutine_threadsafe(coro, self.network.asyncio_loop)
try:
chan, funding_tx = fut.result()
2019-06-05 11:08:16 +02:00
except concurrent.futures.TimeoutError:
raise Exception(_("open_channel timed out"))
return chan, funding_tx
2018-05-28 18:22:45 +02:00
2020-05-06 04:02:59 +02:00
def get_channel_by_short_id(self, short_channel_id: bytes) -> Optional[Channel]:
for chan in self.channels.values():
if chan.short_channel_id == short_channel_id:
return chan
2019-02-02 22:47:45 +01:00
def can_pay_invoice(self, invoice: Invoice) -> bool:
assert invoice.is_lightning()
return (invoice.get_amount_sat() or 0) <= self.num_sats_can_send()
@log_exceptions
async def pay_invoice(
self, invoice: str, *,
2020-06-22 22:37:58 +02:00
amount_msat: int = None,
attempts: int = None, # used only in unit tests
full_path: LNPaymentPath = None,
channels: Optional[Sequence[Channel]] = None,
) -> Tuple[bool, List[HtlcLog]]:
2020-06-22 22:37:58 +02:00
lnaddr = self._check_invoice(invoice, amount_msat=amount_msat)
min_cltv_expiry = lnaddr.get_min_final_cltv_expiry()
payment_hash = lnaddr.paymenthash
key = payment_hash.hex()
payment_secret = lnaddr.payment_secret
invoice_pubkey = lnaddr.pubkey.serialize()
2021-03-08 21:36:27 +01:00
invoice_features = lnaddr.get_features()
r_tags = lnaddr.get_routing_info('r')
2021-02-05 17:09:47 +01:00
amount_to_pay = lnaddr.get_amount_msat()
status = self.get_payment_status(payment_hash)
2019-09-20 17:15:49 +02:00
if status == PR_PAID:
2019-08-15 13:17:16 +02:00
raise PaymentFailure(_("This invoice has been paid already"))
2019-10-11 10:11:41 +02:00
if status == PR_INFLIGHT:
raise PaymentFailure(_("A payment was already initiated for this invoice"))
if payment_hash in self.get_payments(status='inflight'):
raise PaymentFailure(_("A previous attempt to pay this invoice did not clear"))
2021-02-05 17:09:47 +01:00
info = PaymentInfo(payment_hash, amount_to_pay, SENT, PR_UNPAID)
self.save_payment_info(info)
2019-09-20 17:15:49 +02:00
self.wallet.set_label(key, lnaddr.get_description())
2020-11-11 11:03:31 +01:00
self.logger.info(f"pay_invoice starting session for RHASH={payment_hash.hex()}")
self.set_invoice_status(key, PR_INFLIGHT)
success = False
try:
await self.pay_to_node(
node_pubkey=invoice_pubkey,
payment_hash=payment_hash,
payment_secret=payment_secret,
amount_to_pay=amount_to_pay,
min_cltv_expiry=min_cltv_expiry,
r_tags=r_tags,
invoice_features=invoice_features,
attempts=attempts,
full_path=full_path,
channels=channels)
success = True
except PaymentFailure as e:
self.logger.info(f'payment failure: {e!r}')
reason = str(e)
finally:
self.logger.info(f"pay_invoice ending session for RHASH={payment_hash.hex()}. {success=}")
if success:
self.set_invoice_status(key, PR_PAID)
util.trigger_callback('payment_succeeded', self.wallet, key)
else:
self.set_invoice_status(key, PR_UNPAID)
util.trigger_callback('payment_failed', self.wallet, key, reason)
log = self.logs[key]
return success, log
async def pay_to_node(
self, *,
node_pubkey: bytes,
payment_hash: bytes,
payment_secret: Optional[bytes],
amount_to_pay: int, # in msat
min_cltv_expiry: int,
r_tags,
invoice_features: int,
attempts: int = None,
full_path: LNPaymentPath = None,
2021-03-03 20:36:48 +01:00
fwd_trampoline_onion=None,
fwd_trampoline_fee=None,
fwd_trampoline_cltv_delta=None,
channels: Optional[Sequence[Channel]] = None,
) -> None:
2021-02-09 15:09:27 +01:00
2021-03-03 20:36:48 +01:00
if fwd_trampoline_onion:
2021-02-09 15:09:27 +01:00
# todo: compare to the fee of the actual route we found
if fwd_trampoline_fee < 1000:
2021-02-09 15:09:27 +01:00
raise OnionRoutingFailure(code=OnionFailureCode.TRAMPOLINE_FEE_INSUFFICIENT, data=b'')
if fwd_trampoline_cltv_delta < 576:
2021-02-09 15:09:27 +01:00
raise OnionRoutingFailure(code=OnionFailureCode.TRAMPOLINE_EXPIRY_TOO_SOON, data=b'')
self.logs[payment_hash.hex()] = log = []
2022-01-10 15:45:29 +01:00
# when encountering trampoline forwarding difficulties in the legacy case, we
# sometimes need to fall back to a single trampoline forwarder, at the expense
# of privacy
use_two_trampolines = True
2022-09-03 17:51:11 +02:00
self.trampoline_fee_level = self.INITIAL_TRAMPOLINE_FEE_LEVEL
self.failed_trampoline_routes = []
start_time = time.time()
amount_inflight = 0 # what we sent in htlcs (that receiver gets, without fees)
while True:
amount_to_send = amount_to_pay - amount_inflight
if amount_to_send > 0:
# 1. create a set of routes for remaining amount.
# note: path-finding runs in a separate thread so that we don't block the asyncio loop
# graph updates might occur during the computation
routes = self.create_routes_for_payment(
2021-02-27 09:45:19 +01:00
amount_msat=amount_to_send,
final_total_msat=amount_to_pay,
2021-02-27 09:45:19 +01:00
invoice_pubkey=node_pubkey,
min_cltv_expiry=min_cltv_expiry,
r_tags=r_tags,
invoice_features=invoice_features,
full_path=full_path,
payment_hash=payment_hash,
2021-03-03 20:36:48 +01:00
payment_secret=payment_secret,
2022-09-03 17:51:11 +02:00
trampoline_fee_level=self.trampoline_fee_level,
use_two_trampolines=use_two_trampolines,
fwd_trampoline_onion=fwd_trampoline_onion,
channels=channels,
)
# 2. send htlcs
async for route, amount_msat, total_msat, amount_receiver_msat, cltv_delta, bucket_payment_secret, trampoline_onion, trampoline_route in routes:
amount_inflight += amount_receiver_msat
if amount_inflight > amount_to_pay: # safety belts
raise Exception(f"amount_inflight={amount_inflight} > amount_to_pay={amount_to_pay}")
await self.pay_to_route(
route=route,
amount_msat=amount_msat,
2021-02-27 09:45:19 +01:00
total_msat=total_msat,
2021-03-06 10:45:52 +01:00
amount_receiver_msat=amount_receiver_msat,
payment_hash=payment_hash,
2021-02-27 09:45:19 +01:00
payment_secret=bucket_payment_secret,
min_cltv_expiry=cltv_delta,
trampoline_onion=trampoline_onion,
trampoline_fee_level=self.trampoline_fee_level,
trampoline_route=trampoline_route)
# invoice_status is triggered in self.set_invoice_status when it actally changes.
# It is also triggered here to update progress for a lightning payment in the GUI
# (e.g. attempt counter)
util.trigger_callback('invoice_status', self.wallet, payment_hash.hex(), PR_INFLIGHT)
# 3. await a queue
2021-03-06 10:45:52 +01:00
self.logger.info(f"amount inflight {amount_inflight}")
2021-02-05 17:09:47 +01:00
htlc_log = await self.sent_htlcs[payment_hash].get()
amount_inflight -= htlc_log.amount_msat
if amount_inflight < 0:
raise Exception(f"amount_inflight={amount_inflight} < 0")
log.append(htlc_log)
if htlc_log.success:
2021-04-26 08:43:50 +02:00
if self.network.path_finder:
# TODO: report every route to liquidity hints for mpp
# in the case of success, we report channels of the
# route as being able to send the same amount in the future,
# as we assume to not know the capacity
2021-04-26 08:43:50 +02:00
self.network.path_finder.update_liquidity_hints(htlc_log.route, htlc_log.amount_msat)
# remove inflight htlcs from liquidity hints
2021-06-10 18:49:42 +02:00
self.network.path_finder.update_inflight_htlcs(htlc_log.route, add_htlcs=False)
return
# htlc failed
if (attempts is not None and len(log) >= attempts) or (attempts is None and time.time() - start_time > self.PAYMENT_TIMEOUT):
raise PaymentFailure('Giving up after %d attempts'%len(log))
# if we get a tmp channel failure, it might work to split the amount and try more routes
# if we get a channel update, we might retry the same route and amount
route = htlc_log.route
sender_idx = htlc_log.sender_idx
2021-07-13 16:44:17 +02:00
erring_node_id = route[sender_idx].node_id
failure_msg = htlc_log.failure_msg
code, data = failure_msg.code, failure_msg.data
self.logger.info(f"UPDATE_FAIL_HTLC. code={repr(code)}. "
2021-03-23 17:30:40 +01:00
f"decoded_data={failure_msg.decode_data()}. data={data.hex()!r}")
2023-02-17 11:35:03 +00:00
self.logger.info(f"error reported by {erring_node_id.hex()}")
if code == OnionFailureCode.MPP_TIMEOUT:
raise PaymentFailure(failure_msg.code_name())
# trampoline
if self.uses_trampoline():
def maybe_raise_trampoline_fee(htlc_log):
2022-09-03 17:51:11 +02:00
if htlc_log.trampoline_fee_level == self.trampoline_fee_level:
self.trampoline_fee_level += 1
self.failed_trampoline_routes = []
2022-09-03 17:51:11 +02:00
self.logger.info(f'raising trampoline fee level {self.trampoline_fee_level}')
else:
self.logger.info(f'NOT raising trampoline fee level, already at {self.trampoline_fee_level}')
2021-07-02 18:44:39 +02:00
# FIXME The trampoline nodes in the path are chosen randomly.
# Some of the errors might depend on how we have chosen them.
# Having more attempts is currently useful in part because of the randomness,
# instead we should give feedback to create_routes_for_payment.
# Sometimes the trampoline node fails to send a payment and returns
# TEMPORARY_CHANNEL_FAILURE, while it succeeds with a higher trampoline fee.
if code in (
OnionFailureCode.TRAMPOLINE_FEE_INSUFFICIENT,
OnionFailureCode.TRAMPOLINE_EXPIRY_TOO_SOON,
OnionFailureCode.TEMPORARY_CHANNEL_FAILURE):
2022-01-10 15:45:29 +01:00
# TODO: parse the node policy here (not returned by eclair yet)
# TODO: erring node is always the first trampoline even if second
# trampoline demands more fees, we can't influence this
maybe_raise_trampoline_fee(htlc_log)
continue
elif use_two_trampolines:
use_two_trampolines = False
elif code in (
OnionFailureCode.UNKNOWN_NEXT_PEER,
OnionFailureCode.TEMPORARY_NODE_FAILURE):
trampoline_route = htlc_log.route
r = [hop.end_node.hex() for hop in trampoline_route]
self.logger.info(f'failed trampoline route: {r}')
assert r not in self.failed_trampoline_routes
self.failed_trampoline_routes.append(r)
2021-07-02 18:44:39 +02:00
continue
else:
raise PaymentFailure(failure_msg.code_name())
else:
self.handle_error_code_from_failed_htlc(
2021-03-09 08:47:30 +01:00
route=route, sender_idx=sender_idx, failure_msg=failure_msg, amount=htlc_log.amount_msat)
async def pay_to_route(
self, *,
route: LNPaymentRoute,
amount_msat: int,
total_msat: int,
2021-03-06 10:45:52 +01:00
amount_receiver_msat:int,
payment_hash: bytes,
payment_secret: Optional[bytes],
min_cltv_expiry: int,
trampoline_onion: bytes = None,
trampoline_fee_level: int,
trampoline_route: Optional[List]) -> None:
# send a single htlc
short_channel_id = route[0].short_channel_id
2019-02-02 22:47:45 +01:00
chan = self.get_channel_by_short_id(short_channel_id)
2023-01-07 12:20:03 +01:00
assert chan, ShortChannelID(short_channel_id)
2020-04-15 21:32:53 +02:00
peer = self._peers.get(route[0].node_id)
if not peer:
raise PaymentFailure('Dropped peer')
2020-03-04 11:54:42 +01:00
await peer.initialized
htlc = peer.pay(
route=route,
chan=chan,
amount_msat=amount_msat,
total_msat=total_msat,
payment_hash=payment_hash,
min_final_cltv_expiry=min_cltv_expiry,
2021-02-09 15:09:27 +01:00
payment_secret=payment_secret,
2021-02-27 09:45:19 +01:00
trampoline_onion=trampoline_onion)
key = (payment_hash, short_channel_id, htlc.htlc_id)
self.sent_htlcs_info[key] = route, payment_secret, amount_msat, total_msat, amount_receiver_msat, trampoline_fee_level, trampoline_route
# if we sent MPP to a trampoline, add item to sent_buckets
if self.uses_trampoline() and amount_msat != total_msat:
if payment_secret not in self.sent_buckets:
self.sent_buckets[payment_secret] = (0, 0)
amount_sent, amount_failed = self.sent_buckets[payment_secret]
amount_sent += amount_receiver_msat
self.sent_buckets[payment_secret] = amount_sent, amount_failed
2021-06-10 18:49:42 +02:00
if self.network.path_finder:
# add inflight htlcs to liquidity hints
self.network.path_finder.update_inflight_htlcs(route, add_htlcs=True)
2020-06-21 05:16:27 +02:00
util.trigger_callback('htlc_added', chan, htlc, SENT)
def handle_error_code_from_failed_htlc(
self,
*,
route: LNPaymentRoute,
sender_idx: int,
2021-03-09 08:47:30 +01:00
failure_msg: OnionRoutingFailure,
amount: int) -> None:
2021-06-10 18:49:42 +02:00
assert self.channel_db # cannot be in trampoline mode
assert self.network.path_finder
# remove inflight htlcs from liquidity hints
self.network.path_finder.update_inflight_htlcs(route, add_htlcs=False)
code, data = failure_msg.code, failure_msg.data
2021-03-23 17:30:40 +01:00
# TODO can we use lnmsg.OnionWireSerializer here?
# TODO update onion_wire.csv
# handle some specific error codes
failure_codes = {
OnionFailureCode.TEMPORARY_CHANNEL_FAILURE: 0,
OnionFailureCode.AMOUNT_BELOW_MINIMUM: 8,
OnionFailureCode.FEE_INSUFFICIENT: 8,
OnionFailureCode.INCORRECT_CLTV_EXPIRY: 4,
OnionFailureCode.EXPIRY_TOO_SOON: 0,
OnionFailureCode.CHANNEL_DISABLED: 2,
}
2021-03-09 08:47:30 +01:00
if sender_idx is None:
raise PaymentFailure(failure_msg.code_name())
try:
failing_channel = route[sender_idx + 1].short_channel_id
2021-03-09 08:47:30 +01:00
except IndexError:
raise PaymentFailure(f'payment destination reported error: {failure_msg.code_name()}') from None
# TODO: handle unknown next peer?
# handle failure codes that include a channel update
if code in failure_codes:
offset = failure_codes[code]
channel_update_len = int.from_bytes(data[offset:offset+2], byteorder="big")
channel_update_as_received = data[offset+2: offset+2+channel_update_len]
payload = self._decode_channel_update_msg(channel_update_as_received)
if payload is None:
2021-03-09 08:47:30 +01:00
self.logger.info(f'could not decode channel_update for failed htlc: '
f'{channel_update_as_received.hex()}')
blacklist = True
elif payload.get('short_channel_id') != failing_channel:
self.logger.info(f'short_channel_id in channel_update does not match our route')
blacklist = True
else:
2021-03-09 08:47:30 +01:00
# apply the channel update or get blacklisted
blacklist, update = self._handle_chanupd_from_failed_htlc(
payload, route=route, sender_idx=sender_idx)
2021-03-09 08:47:30 +01:00
# we interpret a temporary channel failure as a liquidity issue
# in the channel and update our liquidity hints accordingly
if code == OnionFailureCode.TEMPORARY_CHANNEL_FAILURE:
self.network.path_finder.update_liquidity_hints(
route,
amount,
failing_channel=ShortChannelID(failing_channel))
2021-03-09 08:47:30 +01:00
# if we can't decide on some action, we are stuck
if not (blacklist or update):
raise PaymentFailure(failure_msg.code_name())
# for errors that do not include a channel update
else:
blacklist = True
if blacklist:
self.network.path_finder.liquidity_hints.add_to_blacklist(failing_channel)
def _handle_chanupd_from_failed_htlc(self, payload, *, route, sender_idx) -> Tuple[bool, bool]:
blacklist = False
update = False
try:
r = self.channel_db.add_channel_update(payload, verify=True)
except InvalidGossipMsg:
return True, False # blacklist
short_channel_id = ShortChannelID(payload['short_channel_id'])
if r == UpdateStatus.GOOD:
self.logger.info(f"applied channel update to {short_channel_id}")
# TODO: add test for this
# FIXME: this does not work for our own unannounced channels.
for chan in self.channels.values():
if chan.short_channel_id == short_channel_id:
chan.set_remote_update(payload)
update = True
elif r == UpdateStatus.ORPHANED:
# maybe it is a private channel (and data in invoice was outdated)
self.logger.info(f"Could not find {short_channel_id}. maybe update is for private channel?")
start_node_id = route[sender_idx].node_id
update = self.channel_db.add_channel_update_for_private_channel(payload, start_node_id)
blacklist = not update
elif r == UpdateStatus.EXPIRED:
blacklist = True
elif r == UpdateStatus.DEPRECATED:
self.logger.info(f'channel update is not more recent.')
blacklist = True
elif r == UpdateStatus.UNCHANGED:
blacklist = True
return blacklist, update
@classmethod
def _decode_channel_update_msg(cls, chan_upd_msg: bytes) -> Optional[Dict[str, Any]]:
channel_update_as_received = chan_upd_msg
channel_update_typed = (258).to_bytes(length=2, byteorder="big") + channel_update_as_received
# note: some nodes put channel updates in error msgs with the leading msg_type already there.
# we try decoding both ways here.
try:
message_type, payload = decode_msg(channel_update_typed)
if payload['chain_hash'] != constants.net.rev_genesis_bytes(): raise Exception()
payload['raw'] = channel_update_typed
return payload
except: # FIXME: too broad
try:
message_type, payload = decode_msg(channel_update_as_received)
if payload['chain_hash'] != constants.net.rev_genesis_bytes(): raise Exception()
payload['raw'] = channel_update_as_received
return payload
except:
return None
@staticmethod
2020-06-22 22:37:58 +02:00
def _check_invoice(invoice: str, *, amount_msat: int = None) -> LnAddr:
addr = lndecode(invoice)
2019-08-02 11:43:05 +02:00
if addr.is_expired():
raise InvoiceError(_("This invoice has expired"))
2020-06-23 15:38:06 +02:00
if amount_msat: # replace amt in invoice. main usecase is paying zero amt invoices
existing_amt_msat = addr.get_amount_msat()
if existing_amt_msat and amount_msat < existing_amt_msat:
raise Exception("cannot pay lower amt than what is originally in LN invoice")
2020-06-22 22:37:58 +02:00
addr.amount = Decimal(amount_msat) / COIN / 1000
if addr.amount is None:
raise InvoiceError(_("Missing amount"))
2020-03-30 01:42:14 +02:00
if addr.get_min_final_cltv_expiry() > lnutil.NBLOCK_CLTV_EXPIRY_TOO_FAR_INTO_FUTURE:
raise InvoiceError("{}\n{}".format(
_("Invoice wants us to risk locking funds for unreasonably long."),
f"min_final_cltv_expiry: {addr.get_min_final_cltv_expiry()}"))
return addr
def is_trampoline_peer(self, node_id: bytes) -> bool:
2020-11-11 11:03:31 +01:00
# until trampoline is advertised in lnfeatures, check against hardcoded list
if is_hardcoded_trampoline(node_id):
return True
peer = self._peers.get(node_id)
if not peer:
return False
return (peer.their_features.supports(LnFeatures.OPTION_TRAMPOLINE_ROUTING_OPT_ECLAIR)\
or peer.their_features.supports(LnFeatures.OPTION_TRAMPOLINE_ROUTING_OPT_ELECTRUM))
2020-11-11 11:03:31 +01:00
def suggest_peer(self) -> Optional[bytes]:
if not self.uses_trampoline():
return self.lnrater.suggest_peer()
else:
return random.choice(list(hardcoded_trampoline_nodes().values())).pubkey
2020-11-11 11:03:31 +01:00
def suggest_splits(self, amount_msat: int, my_active_channels, invoice_features, r_tags):
channels_with_funds = {
(chan.channel_id, chan.node_id): int(chan.available_to_spend(HTLCOwner.LOCAL))
for chan in my_active_channels
}
self.logger.info(f"channels_with_funds: {channels_with_funds}")
if self.uses_trampoline():
# in the case of a legacy payment, we don't allow splitting via different
# trampoline nodes, because of https://github.com/ACINQ/eclair/issues/2127
is_legacy, _ = is_legacy_relay(invoice_features, r_tags)
exclude_multinode_payments = is_legacy
# we don't split within a channel when sending to a trampoline node,
# the trampoline node will split for us
exclude_single_channel_splits = True
else:
exclude_multinode_payments = False
exclude_single_channel_splits = False
split_configurations = suggest_splits(
amount_msat,
channels_with_funds,
exclude_single_part_payments=False,
exclude_multinode_payments=exclude_multinode_payments,
exclude_single_channel_splits=exclude_single_channel_splits
)
self.logger.info(f'suggest_split {amount_msat} returned {len(split_configurations)} configurations')
return split_configurations
async def create_routes_for_payment(
2021-02-27 09:45:19 +01:00
self, *,
amount_msat: int, # part of payment amount we want routes for now
final_total_msat: int, # total payment amount final receiver will get
invoice_pubkey,
min_cltv_expiry,
r_tags,
invoice_features: int,
2021-02-27 09:45:19 +01:00
payment_hash,
payment_secret,
2022-01-10 15:45:29 +01:00
trampoline_fee_level: int,
use_two_trampolines: bool,
2022-01-10 15:45:29 +01:00
fwd_trampoline_onion=None,
full_path: LNPaymentPath = None,
channels: Optional[Sequence[Channel]] = None,
) -> AsyncGenerator[Tuple[LNPaymentRoute, int], None]:
2021-02-27 09:45:19 +01:00
"""Creates multiple routes for splitting a payment over the available
private channels.
We first try to conduct the payment over a single channel. If that fails
and mpp is supported by the receiver, we will split the payment."""
invoice_features = LnFeatures(invoice_features)
2021-02-27 09:45:19 +01:00
trampoline_features = LnFeatures.VAR_ONION_OPT
local_height = self.network.get_local_height()
if channels:
my_active_channels = channels
else:
my_active_channels = [
chan for chan in self.channels.values() if
chan.is_active() and not chan.is_frozen_for_sending()]
# try random order
random.shuffle(my_active_channels)
split_configurations = self.suggest_splits(amount_msat, my_active_channels, invoice_features, r_tags)
for sc in split_configurations:
is_mpp = len(sc.config.items()) > 1
routes = []
if is_mpp and not invoice_features.supports(LnFeatures.BASIC_MPP_OPT):
continue
self.logger.info(f"trying split configuration: {sc.config.values()} rating: {sc.rating}")
try:
if self.uses_trampoline():
per_trampoline_channel_amounts = defaultdict(list)
# categorize by trampoline nodes for trampolin mpp construction
for (chan_id, _), part_amounts_msat in sc.config.items():
chan = self.channels[chan_id]
for part_amount_msat in part_amounts_msat:
per_trampoline_channel_amounts[chan.node_id].append((chan_id, part_amount_msat))
# for each trampoline forwarder, construct mpp trampoline
for trampoline_node_id, trampoline_parts in per_trampoline_channel_amounts.items():
per_trampoline_amount = sum([x[1] for x in trampoline_parts])
if trampoline_node_id == invoice_pubkey:
trampoline_route = None
trampoline_onion = None
per_trampoline_secret = payment_secret
per_trampoline_amount_with_fees = amount_msat
per_trampoline_cltv_delta = min_cltv_expiry
per_trampoline_fees = 0
else:
trampoline_route, trampoline_onion, per_trampoline_amount_with_fees, per_trampoline_cltv_delta = create_trampoline_route_and_onion(
amount_msat=per_trampoline_amount,
total_msat=final_total_msat,
min_cltv_expiry=min_cltv_expiry,
my_pubkey=self.node_keypair.pubkey,
invoice_pubkey=invoice_pubkey,
invoice_features=invoice_features,
node_id=trampoline_node_id,
r_tags=r_tags,
payment_hash=payment_hash,
payment_secret=payment_secret,
local_height=local_height,
trampoline_fee_level=trampoline_fee_level,
use_two_trampolines=use_two_trampolines,
failed_routes=self.failed_trampoline_routes)
# node_features is only used to determine is_tlv
per_trampoline_secret = os.urandom(32)
per_trampoline_fees = per_trampoline_amount_with_fees - per_trampoline_amount
self.logger.info(f'created route with trampoline fee level={trampoline_fee_level}')
self.logger.info(f'trampoline hops: {[hop.end_node.hex() for hop in trampoline_route]}')
self.logger.info(f'per trampoline fees: {per_trampoline_fees}')
for chan_id, part_amount_msat in trampoline_parts:
chan = self.channels[chan_id]
margin = chan.available_to_spend(LOCAL, strict=True) - part_amount_msat
delta_fee = min(per_trampoline_fees, margin)
# TODO: distribute trampoline fee over several channels?
part_amount_msat_with_fees = part_amount_msat + delta_fee
per_trampoline_fees -= delta_fee
route = [
RouteEdge(
start_node=self.node_keypair.pubkey,
end_node=trampoline_node_id,
short_channel_id=chan.short_channel_id,
fee_base_msat=0,
fee_proportional_millionths=0,
cltv_expiry_delta=0,
node_features=trampoline_features)
]
self.logger.info(f'adding route {part_amount_msat} {delta_fee} {margin}')
routes.append((route, part_amount_msat_with_fees, per_trampoline_amount_with_fees, part_amount_msat, per_trampoline_cltv_delta, per_trampoline_secret, trampoline_onion, trampoline_route))
if per_trampoline_fees != 0:
self.logger.info('not enough margin to pay trampoline fee')
raise NoPathFound()
else:
# We atomically loop through a split configuration. If there was
# a failure to find a path for a single part, we try the next configuration
2021-07-13 16:44:17 +02:00
for (chan_id, _), part_amounts_msat in sc.config.items():
for part_amount_msat in part_amounts_msat:
channel = self.channels[chan_id]
route = await run_in_thread(
partial(
self.create_route_for_payment,
amount_msat=part_amount_msat,
invoice_pubkey=invoice_pubkey,
min_cltv_expiry=min_cltv_expiry,
r_tags=r_tags,
invoice_features=invoice_features,
my_sending_channels=[channel] if is_mpp else my_active_channels,
full_path=full_path,
)
)
routes.append((route, part_amount_msat, final_total_msat, part_amount_msat, min_cltv_expiry, payment_secret, fwd_trampoline_onion, None))
except NoPathFound:
continue
for route in routes:
yield route
return
raise NoPathFound()
@profiler
def create_route_for_payment(
2021-02-27 09:45:19 +01:00
self, *,
amount_msat: int,
invoice_pubkey: bytes,
min_cltv_expiry: int,
r_tags,
invoice_features: int,
2021-07-29 15:58:09 +02:00
my_sending_channels: List[Channel],
full_path: Optional[LNPaymentPath]) -> LNPaymentRoute:
2021-02-09 15:09:27 +01:00
2023-01-07 12:20:03 +01:00
my_sending_aliases = set(chan.get_local_alias() for chan in my_sending_channels)
2021-07-29 15:58:09 +02:00
my_sending_channels = {chan.short_channel_id: chan for chan in my_sending_channels
if chan.short_channel_id is not None}
# Collect all private edges from route hints.
# Note: if some route hints are multiple edges long, and these paths cross each other,
# we allow our path finding to cross the paths; i.e. the route hints are not isolated.
private_route_edges = {} # type: Dict[ShortChannelID, RouteEdge]
for private_path in r_tags:
# we need to shift the node pubkey by one towards the destination:
private_path_nodes = [edge[0] for edge in private_path][1:] + [invoice_pubkey]
private_path_rest = [edge[1:] for edge in private_path]
start_node = private_path[0][0]
2023-01-07 12:20:03 +01:00
# remove aliases from direct routes
if len(private_path) == 1 and private_path[0][1] in my_sending_aliases:
self.logger.info(f'create_route: skipping alias {ShortChannelID(private_path[0][1])}')
continue
for end_node, edge_rest in zip(private_path_nodes, private_path_rest):
short_channel_id, fee_base_msat, fee_proportional_millionths, cltv_expiry_delta = edge_rest
short_channel_id = ShortChannelID(short_channel_id)
# if we have a routing policy for this edge in the db, that takes precedence,
# as it is likely from a previous failure
channel_policy = self.channel_db.get_policy_for_node(
short_channel_id=short_channel_id,
node_id=start_node,
2021-07-29 15:58:09 +02:00
my_channels=my_sending_channels)
if channel_policy:
fee_base_msat = channel_policy.fee_base_msat
fee_proportional_millionths = channel_policy.fee_proportional_millionths
cltv_expiry_delta = channel_policy.cltv_expiry_delta
node_info = self.channel_db.get_node_info_for_node_id(node_id=end_node)
route_edge = RouteEdge(
start_node=start_node,
end_node=end_node,
2021-02-24 15:00:23 +01:00
short_channel_id=short_channel_id,
fee_base_msat=fee_base_msat,
fee_proportional_millionths=fee_proportional_millionths,
cltv_expiry_delta=cltv_expiry_delta,
node_features=node_info.features if node_info else 0)
2021-03-09 08:47:30 +01:00
private_route_edges[route_edge.short_channel_id] = route_edge
start_node = end_node
# now find a route, end to end: between us and the recipient
try:
route = self.network.path_finder.find_route(
nodeA=self.node_keypair.pubkey,
nodeB=invoice_pubkey,
invoice_amount_msat=amount_msat,
path=full_path,
2021-07-29 15:58:09 +02:00
my_sending_channels=my_sending_channels,
private_route_edges=private_route_edges)
except NoChannelPolicy as e:
raise NoPathFound() from e
if not route:
raise NoPathFound()
# test sanity
if not is_route_sane_to_use(route, amount_msat, min_cltv_expiry):
self.logger.info(f"rejecting insane route {route}")
2021-02-24 15:00:23 +01:00
raise NoPathFound()
assert len(route) > 0
if route[-1].end_node != invoice_pubkey:
raise LNPathInconsistent("last node_id != invoice pubkey")
# add features from invoice
route[-1].node_features |= invoice_features
2021-02-27 09:45:19 +01:00
return route
def create_invoice(
2021-03-03 10:03:29 +01:00
self, *,
amount_msat: Optional[int],
2021-03-03 10:03:29 +01:00
message: str,
expiry: int,
2022-06-22 02:26:54 +02:00
fallback_address: Optional[str],
write_to_disk: bool = True,
channels: Optional[Sequence[Channel]] = None,
) -> Tuple[LnAddr, str]:
2021-03-03 10:03:29 +01:00
assert amount_msat is None or amount_msat > 0
2019-09-20 17:15:49 +02:00
timestamp = int(time.time())
routing_hints, trampoline_hints = self.calc_routing_hints_for_invoice(amount_msat, channels=channels)
2018-10-17 17:32:58 +02:00
if not routing_hints:
2021-03-03 10:03:29 +01:00
self.logger.info(
"Warning. No routing hints added to invoice. "
"Other clients will likely not be able to send to us.")
2020-11-11 11:03:31 +01:00
invoice_features = self.features.for_invoice()
2019-09-20 17:15:49 +02:00
payment_preimage = os.urandom(32)
payment_hash = sha256(payment_preimage)
2021-02-01 14:17:04 +01:00
info = PaymentInfo(payment_hash, amount_msat, RECEIVED, PR_UNPAID)
amount_btc = amount_msat/Decimal(COIN*1000) if amount_msat else None
2020-03-04 14:24:07 +01:00
if expiry == 0:
expiry = LN_EXPIRY_NEVER
2021-03-03 10:03:29 +01:00
lnaddr = LnAddr(
paymenthash=payment_hash,
amount=amount_btc,
tags=[
('d', message),
('c', MIN_FINAL_CLTV_EXPIRY_FOR_INVOICE),
('x', expiry),
2022-03-29 10:36:36 +02:00
('9', invoice_features),
('f', fallback_address),
]
2021-03-03 10:03:29 +01:00
+ routing_hints
+ trampoline_hints,
date=timestamp,
payment_secret=derive_payment_secret_from_payment_preimage(payment_preimage))
2019-09-20 17:15:49 +02:00
invoice = lnencode(lnaddr, self.node_keypair.privkey)
self.save_preimage(payment_hash, payment_preimage, write_to_disk=False)
self.save_payment_info(info, write_to_disk=False)
if write_to_disk:
self.wallet.save_db()
return lnaddr, invoice
2022-06-22 02:26:54 +02:00
def add_request(
self,
*,
amount_sat: Optional[int],
message: str,
expiry: int,
fallback_address: Optional[str],
) -> str:
2022-03-15 13:03:34 +01:00
# passed expiry is relative, it is absolute in the lightning invoice
amount_msat = amount_sat * 1000 if amount_sat else None
lnaddr, invoice = self.create_invoice(
amount_msat=amount_msat,
message=message,
expiry=expiry,
2022-03-29 10:36:36 +02:00
fallback_address=fallback_address,
write_to_disk=False,
)
2022-03-29 18:17:38 +02:00
return invoice
def save_preimage(self, payment_hash: bytes, preimage: bytes, *, write_to_disk: bool = True):
assert sha256(preimage) == payment_hash
2023-02-17 11:35:03 +00:00
self.preimages[payment_hash.hex()] = preimage.hex()
if write_to_disk:
self.wallet.save_db()
2020-05-03 12:13:08 +02:00
def get_preimage(self, payment_hash: bytes) -> Optional[bytes]:
2023-02-17 11:35:03 +00:00
r = self.preimages.get(payment_hash.hex())
2020-05-03 12:13:08 +02:00
return bfh(r) if r else None
2019-01-29 19:01:04 +01:00
2020-05-03 12:13:08 +02:00
def get_payment_info(self, payment_hash: bytes) -> Optional[PaymentInfo]:
2020-05-05 15:40:13 +02:00
"""returns None if payment_hash is a payment we are forwarding"""
2019-09-20 17:15:49 +02:00
key = payment_hash.hex()
with self.lock:
2022-06-14 12:50:04 +02:00
if key in self.payment_info:
amount_msat, direction, status = self.payment_info[key]
2021-02-01 14:17:04 +01:00
return PaymentInfo(payment_hash, amount_msat, direction, status)
2019-08-11 14:47:06 +02:00
def save_payment_info(self, info: PaymentInfo, *, write_to_disk: bool = True) -> None:
2019-09-20 17:15:49 +02:00
key = info.payment_hash.hex()
2020-03-10 13:27:02 +01:00
assert info.status in SAVED_PR_STATUS
2019-09-06 18:27:47 +02:00
with self.lock:
2022-06-14 12:50:04 +02:00
self.payment_info[key] = info.amount_msat, info.direction, info.status
if write_to_disk:
self.wallet.save_db()
2021-03-11 16:53:55 +01:00
def check_received_mpp_htlc(self, payment_secret, short_channel_id, htlc: UpdateAddHtlc, expected_msat: int) -> Optional[bool]:
""" return MPP status: True (accepted), False (expired) or None """
payment_hash = htlc.payment_hash
2021-03-11 16:53:55 +01:00
is_expired, is_accepted, htlc_set = self.received_mpp_htlcs.get(payment_secret, (False, False, set()))
if self.get_payment_status(payment_hash) == PR_PAID:
# payment_status is persisted
is_accepted = True
is_expired = False
key = (short_channel_id, htlc)
if key not in htlc_set:
htlc_set.add(key)
if not is_accepted and not is_expired:
total = sum([_htlc.amount_msat for scid, _htlc in htlc_set])
first_timestamp = min([_htlc.timestamp for scid, _htlc in htlc_set])
if self.stopping_soon:
is_expired = True # try to time out pending HTLCs before shutting down
elif time.time() - first_timestamp > self.MPP_EXPIRY:
is_expired = True
elif total == expected_msat:
is_accepted = True
if is_accepted or is_expired:
htlc_set.remove(key)
if len(htlc_set) > 0:
2021-03-11 16:53:55 +01:00
self.received_mpp_htlcs[payment_secret] = is_expired, is_accepted, htlc_set
elif payment_secret in self.received_mpp_htlcs:
self.received_mpp_htlcs.pop(payment_secret)
return True if is_accepted else (False if is_expired else None)
2021-01-27 19:27:06 +01:00
2021-03-08 21:36:27 +01:00
def get_payment_status(self, payment_hash: bytes) -> int:
info = self.get_payment_info(payment_hash)
return info.status if info else PR_UNPAID
2019-10-11 10:11:41 +02:00
2022-03-15 13:03:34 +01:00
def get_invoice_status(self, invoice: Invoice) -> int:
invoice_id = invoice.rhash
if invoice_id in self.inflight_payments:
2021-02-05 11:33:45 +01:00
return PR_INFLIGHT
# status may be PR_FAILED
status = self.get_payment_status(bytes.fromhex(invoice_id))
if status == PR_UNPAID and invoice_id in self.logs:
status = PR_FAILED
return status
2021-03-08 21:36:27 +01:00
def set_invoice_status(self, key: str, status: int) -> None:
2021-02-05 11:33:45 +01:00
if status == PR_INFLIGHT:
self.inflight_payments.add(key)
elif key in self.inflight_payments:
self.inflight_payments.remove(key)
2020-03-10 13:27:02 +01:00
if status in SAVED_PR_STATUS:
2020-03-10 13:51:08 +01:00
self.set_payment_status(bfh(key), status)
util.trigger_callback('invoice_status', self.wallet, key, status)
self.logger.info(f"invoice status triggered (2) for key {key} and status {status}")
2020-03-10 13:27:02 +01:00
def set_request_status(self, payment_hash: bytes, status: int) -> None:
2022-06-14 12:50:04 +02:00
if self.get_payment_status(payment_hash) == status:
return
self.set_payment_status(payment_hash, status)
request_id = payment_hash.hex()
req = self.wallet.get_request(request_id)
2022-06-14 20:33:19 +02:00
if req is None:
return
util.trigger_callback('request_status', self.wallet, request_id, status)
2021-03-08 21:36:27 +01:00
def set_payment_status(self, payment_hash: bytes, status: int) -> None:
info = self.get_payment_info(payment_hash)
if info is None:
2019-09-20 17:15:49 +02:00
# if we are forwarding
2019-08-11 14:47:06 +02:00
return
2019-09-20 17:15:49 +02:00
info = info._replace(status=status)
self.save_payment_info(info)
2019-10-11 10:11:41 +02:00
2021-11-04 19:16:02 +01:00
def _on_maybe_forwarded_htlc_resolved(self, chan: Channel, htlc_id: int) -> None:
"""Called when an HTLC we offered on chan gets irrevocably fulfilled or failed.
If we find this was a forwarded HTLC, the upstream peer is notified.
"""
fw_info = chan.short_channel_id.hex(), htlc_id
upstream_peer_pubkey = self.downstream_htlc_to_upstream_peer_map.get(fw_info)
if not upstream_peer_pubkey:
return
upstream_peer = self.peers.get(upstream_peer_pubkey)
if not upstream_peer:
return
upstream_peer.downstream_htlc_resolved_event.set()
upstream_peer.downstream_htlc_resolved_event.clear()
def htlc_fulfilled(self, chan: Channel, payment_hash: bytes, htlc_id: int):
util.trigger_callback('htlc_fulfilled', payment_hash, chan, htlc_id)
2021-11-04 19:16:02 +01:00
self._on_maybe_forwarded_htlc_resolved(chan=chan, htlc_id=htlc_id)
q = self.sent_htlcs.get(payment_hash)
if q:
route, payment_secret, amount_msat, bucket_msat, amount_receiver_msat, trampoline_fee_level, trampoline_route = self.sent_htlcs_info[(payment_hash, chan.short_channel_id, htlc_id)]
htlc_log = HtlcLog(
success=True,
route=route,
amount_msat=amount_receiver_msat,
trampoline_fee_level=trampoline_fee_level)
q.put_nowait(htlc_log)
else:
key = payment_hash.hex()
self.set_invoice_status(key, PR_PAID)
util.trigger_callback('payment_succeeded', self.wallet, key)
def htlc_failed(
self,
chan: Channel,
payment_hash: bytes,
htlc_id: int,
error_bytes: Optional[bytes],
2021-02-10 13:16:33 +01:00
failure_message: Optional['OnionRoutingFailure']):
util.trigger_callback('htlc_failed', payment_hash, chan, htlc_id)
2021-11-04 19:16:02 +01:00
self._on_maybe_forwarded_htlc_resolved(chan=chan, htlc_id=htlc_id)
q = self.sent_htlcs.get(payment_hash)
if q:
2021-02-27 09:45:19 +01:00
# detect if it is part of a bucket
# if yes, wait until the bucket completely failed
key = (payment_hash, chan.short_channel_id, htlc_id)
route, payment_secret, amount_msat, bucket_msat, amount_receiver_msat, trampoline_fee_level, trampoline_route = self.sent_htlcs_info[key]
if error_bytes:
# TODO "decode_onion_error" might raise, catch and maybe blacklist/penalise someone?
try:
failure_message, sender_idx = chan.decode_onion_error(error_bytes, route, htlc_id)
except Exception as e:
sender_idx = None
failure_message = OnionRoutingFailure(-1, str(e))
else:
# probably got "update_fail_malformed_htlc". well... who to penalise now?
assert failure_message is not None
sender_idx = None
self.logger.info(f"htlc_failed {failure_message}")
2021-02-27 09:45:19 +01:00
# check sent_buckets if we use trampoline
if self.uses_trampoline() and payment_secret in self.sent_buckets:
amount_sent, amount_failed = self.sent_buckets[payment_secret]
amount_failed += amount_receiver_msat
self.sent_buckets[payment_secret] = amount_sent, amount_failed
2021-03-08 17:45:00 +01:00
if amount_sent != amount_failed:
self.logger.info('bucket still active...')
return
self.logger.info('bucket failed')
2021-03-08 17:45:00 +01:00
amount_receiver_msat = amount_sent
if trampoline_route:
route = trampoline_route
htlc_log = HtlcLog(
success=False,
route=route,
2021-03-08 17:45:00 +01:00
amount_msat=amount_receiver_msat,
error_bytes=error_bytes,
failure_msg=failure_message,
sender_idx=sender_idx,
trampoline_fee_level=trampoline_fee_level)
q.put_nowait(htlc_log)
else:
self.logger.info(f"received unknown htlc_failed, probably from previous session")
key = payment_hash.hex()
self.set_invoice_status(key, PR_UNPAID)
util.trigger_callback('payment_failed', self.wallet, key, '')
2019-06-10 14:05:02 +02:00
def calc_routing_hints_for_invoice(self, amount_msat: Optional[int], channels=None):
"""calculate routing hints (BOLT-11 'r' field)"""
routing_hints = []
if channels is None:
channels = list(self.get_channels_for_receiving(amount_msat))
random.shuffle(channels) # let's not leak channel order
scid_to_my_channels = {chan.short_channel_id: chan for chan in channels
if chan.short_channel_id is not None}
for chan in channels:
2023-01-07 12:20:03 +01:00
alias_or_scid = chan.get_remote_alias() or chan.short_channel_id
assert isinstance(alias_or_scid, bytes), alias_or_scid
channel_info = get_mychannel_info(chan.short_channel_id, scid_to_my_channels)
# note: as a fallback, if we don't have a channel update for the
# incoming direction of our private channel, we fill the invoice with garbage.
# the sender should still be able to pay us, but will incur an extra round trip
# (they will get the channel update from the onion error)
# at least, that's the theory. https://github.com/lightningnetwork/lnd/issues/2066
fee_base_msat = fee_proportional_millionths = 0
cltv_expiry_delta = 1 # lnd won't even try with zero
missing_info = True
if channel_info:
policy = get_mychannel_policy(channel_info.short_channel_id, chan.node_id, scid_to_my_channels)
if policy:
fee_base_msat = policy.fee_base_msat
fee_proportional_millionths = policy.fee_proportional_millionths
cltv_expiry_delta = policy.cltv_expiry_delta
missing_info = False
if missing_info:
2021-03-03 10:03:29 +01:00
self.logger.info(
2023-01-07 12:20:03 +01:00
f"Warning. Missing channel update for our channel {chan.short_channel_id}; "
2021-03-03 10:03:29 +01:00
f"filling invoice with incorrect data.")
routing_hints.append(('r', [(
chan.node_id,
2023-01-07 12:20:03 +01:00
alias_or_scid,
2021-03-03 10:03:29 +01:00
fee_base_msat,
fee_proportional_millionths,
cltv_expiry_delta)]))
2022-05-18 17:07:18 +02:00
trampoline_hints = []
for r in routing_hints:
node_id, short_channel_id, fee_base_msat, fee_proportional_millionths, cltv_expiry_delta = r[1][0]
if len(r[1])== 1 and self.is_trampoline_peer(node_id):
trampoline_hints.append(('t', (node_id, fee_base_msat, fee_proportional_millionths, cltv_expiry_delta)))
return routing_hints, trampoline_hints
2022-06-14 12:50:04 +02:00
def delete_payment_info(self, payment_hash_hex: str):
# This method is called when an invoice or request is deleted by the user.
# The GUI only lets the user delete invoices or requests that have not been paid.
# Once an invoice/request has been paid, it is part of the history,
# and get_lightning_history assumes that payment_info is there.
assert self.get_payment_status(bytes.fromhex(payment_hash_hex)) != PR_PAID
with self.lock:
self.payment_info.pop(payment_hash_hex, None)
def get_balance(self, frozen=False):
with self.lock:
2021-03-03 10:03:29 +01:00
return Decimal(sum(
chan.balance(LOCAL) if not chan.is_closed() and (chan.is_frozen_for_sending() if frozen else True) else 0
2021-03-03 10:03:29 +01:00
for chan in self.channels.values())) / 1000
def get_channels_for_sending(self):
for c in self.channels.values():
if c.is_active() and not c.is_frozen_for_sending():
if self.channel_db or self.is_trampoline_peer(c.node_id):
yield c
def fee_estimate(self, amount_sat):
# Here we have to guess a fee, because some callers (submarine swaps)
# use this method to initiate a payment, which would otherwise fail.
fee_base_msat = TRAMPOLINE_FEES[3]['fee_base_msat']
fee_proportional_millionths = TRAMPOLINE_FEES[3]['fee_proportional_millionths']
# inverse of fee_for_edge_msat
amount_msat = amount_sat * 1000
amount_minus_fees = (amount_msat - fee_base_msat) * 1_000_000 // ( 1_000_000 + fee_proportional_millionths)
return Decimal(amount_msat - amount_minus_fees) / 1000
def num_sats_can_send(self, deltas=None) -> Decimal:
"""
without trampoline, sum of all channel capacity
with trampoline, MPP must use a single trampoline
"""
if deltas is None:
deltas = {}
def send_capacity(chan):
if chan in deltas:
delta_msat = deltas[chan] * 1000
if delta_msat > chan.available_to_spend(REMOTE):
delta_msat = 0
else:
delta_msat = 0
return chan.available_to_spend(LOCAL) + delta_msat
can_send_dict = defaultdict(int)
with self.lock:
for c in self.get_channels_for_sending():
if not self.uses_trampoline():
can_send_dict[0] += send_capacity(c)
else:
can_send_dict[c.node_id] += send_capacity(c)
can_send = max(can_send_dict.values()) if can_send_dict else 0
can_send_sat = Decimal(can_send)/1000
can_send_sat -= self.fee_estimate(can_send_sat)
return max(can_send_sat, 0)
def get_channels_for_receiving(self, amount_msat=None) -> Sequence[Channel]:
if not amount_msat: # assume we want to recv a large amt, e.g. finding max.
amount_msat = float('inf')
with self.lock:
channels = list(self.channels.values())
# we exclude channels that cannot *right now* receive (e.g. peer offline)
channels = [chan for chan in channels
if (chan.is_active() and not chan.is_frozen_for_receiving())]
# Filter out nodes that have low receive capacity compared to invoice amt.
# Even with MPP, below a certain threshold, including these channels probably
# hurts more than help, as they lead to many failed attempts for the sender.
channels = sorted(channels, key=lambda chan: -chan.available_to_spend(REMOTE))
selected_channels = []
running_sum = 0
cutoff_factor = 0.2 # heuristic
for chan in channels:
recv_capacity = chan.available_to_spend(REMOTE)
chan_can_handle_payment_as_single_part = recv_capacity >= amount_msat
chan_small_compared_to_running_sum = recv_capacity < cutoff_factor * running_sum
if not chan_can_handle_payment_as_single_part and chan_small_compared_to_running_sum:
2022-05-18 17:07:18 +02:00
break
running_sum += recv_capacity
selected_channels.append(chan)
channels = selected_channels
del selected_channels
# cap max channels to include to keep QR code reasonably scannable
channels = channels[:10]
return channels
2022-05-18 17:07:18 +02:00
def num_sats_can_receive(self, deltas=None) -> Decimal:
"""Return a conservative estimate of max sat value we can realistically receive
in a single payment. (MPP is allowed)
The theoretical max would be `sum(chan.available_to_spend(REMOTE) for chan in self.channels)`,
but that would require a sender using MPP to magically guess all our channel liquidities.
"""
if deltas is None:
deltas = {}
def recv_capacity(chan):
if chan in deltas:
delta_msat = deltas[chan] * 1000
if delta_msat > chan.available_to_spend(LOCAL):
delta_msat = 0
else:
delta_msat = 0
return chan.available_to_spend(REMOTE) + delta_msat
with self.lock:
recv_channels = self.get_channels_for_receiving()
recv_chan_msats = [recv_capacity(chan) for chan in recv_channels]
if not recv_chan_msats:
return Decimal(0)
can_receive_msat = max(
max(recv_chan_msats), # single-part payment baseline
sum(recv_chan_msats) // 2, # heuristic for MPP
)
2022-05-18 17:07:18 +02:00
return Decimal(can_receive_msat) / 1000
def _suggest_channels_for_rebalance(self, direction, amount_sat) -> Sequence[Tuple[Channel, int]]:
"""
Suggest a channel and amount to send/receive with that channel, so that we will be able to receive/send amount_sat
This is used when suggesting a swap or rebalance in order to receive a payment
"""
with self.lock:
func = self.num_sats_can_send if direction == SENT else self.num_sats_can_receive
suggestions = []
channels = self.get_channels_for_sending() if direction == SENT else self.get_channels_for_receiving()
for chan in channels:
available_sat = chan.available_to_spend(LOCAL if direction == SENT else REMOTE) // 1000
delta = amount_sat - available_sat
delta += self.fee_estimate(amount_sat)
# add safety margin
delta += delta // 100 + 1
if func(deltas={chan:delta}) >= amount_sat:
suggestions.append((chan, delta))
elif direction==RECEIVED and func(deltas={chan:2*delta}) >= amount_sat:
# MPP heuristics has a 0.5 slope
suggestions.append((chan, 2*delta))
if not suggestions:
raise NotEnoughFunds
return suggestions
def _suggest_rebalance(self, direction, amount_sat):
"""
Suggest a rebalance in order to be able to send or receive amount_sat.
Returns (from_channel, to_channel, amount to shuffle)
"""
try:
suggestions = self._suggest_channels_for_rebalance(direction, amount_sat)
except NotEnoughFunds:
return False
for chan2, delta in suggestions:
# margin for fee caused by rebalancing
delta += self.fee_estimate(amount_sat)
# find other channel or trampoline that can send delta
for chan1 in self.channels.values():
if chan1.is_frozen_for_sending() or not chan1.is_active():
continue
if chan1 == chan2:
continue
if self.uses_trampoline() and chan1.node_id == chan2.node_id:
continue
if direction == SENT:
if chan1.can_pay(delta*1000):
return (chan1, chan2, delta)
else:
if chan1.can_receive(delta*1000):
return (chan2, chan1, delta)
else:
continue
else:
return False
2022-05-29 18:39:18 +02:00
def num_sats_can_rebalance(self, chan1, chan2):
# TODO: we should be able to spend 'max', with variable fee
n1 = chan1.available_to_spend(LOCAL)
n1 -= self.fee_estimate(n1)
n2 = chan2.available_to_spend(REMOTE)
amount_sat = min(n1, n2) // 1000
return amount_sat
def suggest_rebalance_to_send(self, amount_sat):
return self._suggest_rebalance(SENT, amount_sat)
def suggest_rebalance_to_receive(self, amount_sat):
return self._suggest_rebalance(RECEIVED, amount_sat)
def suggest_swap_to_send(self, amount_sat, coins):
# fixme: if swap_amount_sat is lower than the minimum swap amount, we need to propose a higher value
assert amount_sat > self.num_sats_can_send()
try:
suggestions = self._suggest_channels_for_rebalance(SENT, amount_sat)
except NotEnoughFunds:
return
for chan, swap_recv_amount in suggestions:
# check that we can send onchain
swap_server_mining_fee = 10000 # guessing, because we have not called get_pairs yet
swap_funding_sat = swap_recv_amount + swap_server_mining_fee
swap_output = PartialTxOutput.from_address_and_value(ln_dummy_address(), int(swap_funding_sat))
if not self.wallet.can_pay_onchain([swap_output], coins=coins):
continue
return (chan, swap_recv_amount)
def suggest_swap_to_receive(self, amount_sat):
assert amount_sat > self.num_sats_can_receive()
try:
suggestions = self._suggest_channels_for_rebalance(RECEIVED, amount_sat)
except NotEnoughFunds:
return
for chan, swap_recv_amount in suggestions:
return (chan, swap_recv_amount)
async def rebalance_channels(self, chan1, chan2, amount_msat):
2022-07-13 10:14:34 +02:00
if chan1 == chan2:
raise Exception('Rebalance requires two different channels')
if self.uses_trampoline() and chan1.node_id == chan2.node_id:
2022-07-13 10:14:34 +02:00
raise Exception('Rebalance requires channels from different trampolines')
lnaddr, invoice = self.create_invoice(
amount_msat=amount_msat,
message='rebalance',
expiry=3600,
fallback_address=None,
channels = [chan2]
)
2022-07-13 10:14:34 +02:00
return await self.pay_invoice(
invoice, channels=[chan1])
def num_sats_can_receive_no_mpp(self) -> Decimal:
with self.lock:
2021-04-07 17:21:48 +02:00
channels = [
c for c in self.channels.values()
if c.is_active() and not c.is_frozen_for_receiving()
]
can_receive = max([c.available_to_spend(REMOTE) for c in channels]) if channels else 0
return Decimal(can_receive) / 1000
2022-03-15 13:03:34 +01:00
def can_receive_invoice(self, invoice: Invoice) -> bool:
assert invoice.is_lightning()
return (invoice.get_amount_sat() or 0) <= self.num_sats_can_receive()
async def close_channel(self, chan_id):
chan = self._channels[chan_id]
2020-04-15 21:32:53 +02:00
peer = self._peers[chan.node_id]
2018-10-24 18:26:05 +02:00
return await peer.close_channel(chan_id)
2018-10-24 17:36:07 +02:00
def _force_close_channel(self, chan_id: bytes) -> Transaction:
chan = self._channels[chan_id]
tx = chan.force_close_tx()
# We set the channel state to make sure we won't sign new commitment txs.
# We expect the caller to try to broadcast this tx, after which it is
# not safe to keep using the channel even if the broadcast errors (server could be lying).
# Until the tx is seen in the mempool, there will be automatic rebroadcasts.
chan.set_state(ChannelState.FORCE_CLOSING)
# Add local tx to wallet to also allow manual rebroadcasts.
try:
self.wallet.adb.add_transaction(tx)
except UnrelatedTransactionException:
pass # this can happen if (~all the balance goes to REMOTE)
return tx
async def force_close_channel(self, chan_id: bytes) -> str:
"""Force-close the channel. Network-related exceptions are propagated to the caller.
(automatic rebroadcasts will be scheduled)
"""
# note: as we are async, it can take a few event loop iterations between the caller
# "calling us" and us getting to run, and we only set the channel state now:
tx = self._force_close_channel(chan_id)
await self.network.broadcast_transaction(tx)
return tx.txid()
def schedule_force_closing(self, chan_id: bytes) -> 'asyncio.Task[None]':
"""Schedules a task to force-close the channel and returns it.
Network-related exceptions are suppressed.
(automatic rebroadcasts will be scheduled)
Note: this method is intentionally not async so that callers have a guarantee
that the channel state is set immediately.
"""
tx = self._force_close_channel(chan_id)
return asyncio.create_task(self.network.try_broadcasting(tx, 'force-close'))
2018-07-13 17:05:04 +02:00
def remove_channel(self, chan_id):
2021-03-22 19:28:24 +01:00
chan = self.channels[chan_id]
assert chan.can_be_deleted()
with self.lock:
self._channels.pop(chan_id)
2020-02-05 15:13:37 +01:00
self.db.get('channels').pop(chan_id.hex())
for addr in chan.get_wallet_addresses_channel_might_want_reserved():
self.wallet.set_reserved_state_of_address(addr, reserved=False)
2020-02-04 13:35:58 +01:00
2020-04-14 16:12:47 +02:00
util.trigger_callback('channels_updated', self.wallet)
util.trigger_callback('wallet_updated', self.wallet)
2019-11-26 00:15:33 +01:00
@ignore_exceptions
@log_exceptions
async def reestablish_peer_for_given_channel(self, chan: Channel) -> None:
now = time.time()
peer_addresses = []
if self.uses_trampoline():
2020-11-11 11:03:31 +01:00
addr = trampolines_by_id().get(chan.node_id)
if addr:
peer_addresses.append(addr)
else:
# will try last good address first, from gossip
last_good_addr = self.channel_db.get_last_good_address(chan.node_id)
if last_good_addr:
peer_addresses.append(last_good_addr)
# will try addresses for node_id from gossip
addrs_from_gossip = self.channel_db.get_node_addresses(chan.node_id) or []
for host, port, ts in addrs_from_gossip:
peer_addresses.append(LNPeerAddr(host, port, chan.node_id))
# will try addresses stored in channel storage
peer_addresses += list(chan.get_peer_addresses())
# Done gathering addresses.
# Now select first one that has not failed recently.
for peer in peer_addresses:
if self._can_retry_addr(peer, urgent=True, now=now):
await self._add_peer(peer.host, peer.port, peer.pubkey)
return
async def reestablish_peers_and_channels(self):
while True:
await asyncio.sleep(1)
if self.stopping_soon:
return
for chan in self.channels.values():
2020-02-26 09:04:54 +01:00
if chan.is_closed():
continue
2019-10-29 08:02:14 +01:00
# reestablish
if not chan.should_try_to_reestablish_peer():
continue
2020-04-15 21:32:53 +02:00
peer = self._peers.get(chan.node_id, None)
if peer:
await peer.taskgroup.spawn(peer.reestablish_channel(chan))
else:
await self.taskgroup.spawn(self.reestablish_peer_for_given_channel(chan))
2019-01-25 20:16:11 +01:00
def current_feerate_per_kw(self):
from .simple_config import FEE_LN_ETA_TARGET, FEERATE_FALLBACK_STATIC_FEE, FEERATE_REGTEST_HARDCODED
from .simple_config import FEERATE_PER_KW_MIN_RELAY_LIGHTNING
2019-01-25 20:16:11 +01:00
if constants.net is constants.BitcoinRegtest:
return FEERATE_REGTEST_HARDCODED // 4
feerate_per_kvbyte = self.network.config.eta_target_to_fee(FEE_LN_ETA_TARGET)
if feerate_per_kvbyte is None:
feerate_per_kvbyte = FEERATE_FALLBACK_STATIC_FEE
return max(FEERATE_PER_KW_MIN_RELAY_LIGHTNING, feerate_per_kvbyte // 4)
2020-03-13 11:44:29 +01:00
def create_channel_backup(self, channel_id):
chan = self._channels[channel_id]
# do not backup old-style channels
assert chan.is_static_remotekey_enabled()
2020-03-13 11:44:29 +01:00
peer_addresses = list(chan.get_peer_addresses())
peer_addr = peer_addresses[0]
2021-03-09 09:55:55 +01:00
return ImportedChannelBackupStorage(
2020-03-13 11:44:29 +01:00
node_id = chan.node_id,
privkey = self.node_keypair.privkey,
funding_txid = chan.funding_outpoint.txid,
funding_index = chan.funding_outpoint.output_index,
funding_address = chan.get_funding_address(),
host = peer_addr.host,
port = peer_addr.port,
is_initiator = chan.constraints.is_initiator,
channel_seed = chan.config[LOCAL].channel_seed,
local_delay = chan.config[LOCAL].to_self_delay,
remote_delay = chan.config[REMOTE].to_self_delay,
remote_revocation_pubkey = chan.config[REMOTE].revocation_basepoint.pubkey,
remote_payment_pubkey = chan.config[REMOTE].payment_basepoint.pubkey)
def export_channel_backup(self, channel_id):
xpub = self.wallet.get_fingerprint()
backup_bytes = self.create_channel_backup(channel_id).to_bytes()
2021-03-09 09:55:55 +01:00
assert backup_bytes == ImportedChannelBackupStorage.from_bytes(backup_bytes).to_bytes(), "roundtrip failed"
2020-06-16 11:52:08 +02:00
encrypted = pw_encode_with_version_and_mac(backup_bytes, xpub)
assert backup_bytes == pw_decode_with_version_and_mac(encrypted, xpub), "encrypt failed"
2020-06-16 10:42:47 +02:00
return 'channel_backup:' + encrypted
2020-03-13 11:44:29 +01:00
async def request_force_close(self, channel_id: bytes, *, connect_str=None) -> None:
if channel_id in self.channels:
2021-03-16 19:19:26 +01:00
chan = self.channels[channel_id]
2021-03-16 17:27:37 +01:00
peer = self._peers.get(chan.node_id)
if not peer:
raise Exception('Peer not found')
chan.should_request_force_close = True
peer.close_and_cleanup()
elif connect_str:
peer = await self.add_peer(connect_str)
await peer.request_force_close(channel_id)
2021-03-16 17:27:37 +01:00
elif channel_id in self.channel_backups:
await self._request_force_close_from_backup(channel_id)
2021-03-16 17:27:37 +01:00
else:
raise Exception(f'Unknown channel {channel_id.hex()}')
2020-06-16 10:42:47 +02:00
def import_channel_backup(self, data):
assert data.startswith('channel_backup:')
encrypted = data[15:]
2020-03-13 11:44:29 +01:00
xpub = self.wallet.get_fingerprint()
2020-06-16 11:52:08 +02:00
decrypted = pw_decode_with_version_and_mac(encrypted, xpub)
2021-03-09 09:55:55 +01:00
cb_storage = ImportedChannelBackupStorage.from_bytes(decrypted)
channel_id = cb_storage.channel_id()
if channel_id.hex() in self.db.get_dict("channels"):
2020-03-13 11:44:29 +01:00
raise Exception('Channel already in wallet')
self.logger.info(f'importing channel backup: {channel_id.hex()}')
2021-03-09 09:55:55 +01:00
d = self.db.get_dict("imported_channel_backups")
d[channel_id.hex()] = cb_storage
with self.lock:
cb = ChannelBackup(cb_storage, lnworker=self)
self._channel_backups[channel_id] = cb
2020-03-13 11:44:29 +01:00
self.wallet.save_db()
2020-04-14 16:12:47 +02:00
util.trigger_callback('channels_updated', self.wallet)
2020-04-10 19:50:20 +02:00
self.lnwatcher.add_channel(cb.funding_outpoint.to_str(), cb.get_funding_address())
2020-03-13 11:44:29 +01:00
def has_conflicting_backup_with(self, remote_node_id: bytes):
""" Returns whether we have an active channel with this node on another device, using same local node id. """
channel_backup_peers = [
cb.node_id for cb in self.channel_backups.values()
if (not cb.is_closed() and cb.get_local_pubkey() == self.node_keypair.pubkey)]
return any(remote_node_id.startswith(cb_peer_nodeid) for cb_peer_nodeid in channel_backup_peers)
2020-03-13 11:44:29 +01:00
def remove_channel_backup(self, channel_id):
2021-03-22 19:28:24 +01:00
chan = self.channel_backups[channel_id]
assert chan.can_be_deleted()
found = False
2021-03-22 19:28:24 +01:00
onchain_backups = self.db.get_dict("onchain_channel_backups")
2021-03-29 18:18:30 +02:00
imported_backups = self.db.get_dict("imported_channel_backups")
2021-03-22 19:28:24 +01:00
if channel_id.hex() in onchain_backups:
onchain_backups.pop(channel_id.hex())
found = True
if channel_id.hex() in imported_backups:
2021-03-22 19:28:24 +01:00
imported_backups.pop(channel_id.hex())
found = True
if not found:
2020-03-13 11:44:29 +01:00
raise Exception('Channel not found')
with self.lock:
self._channel_backups.pop(channel_id)
2020-03-13 11:44:29 +01:00
self.wallet.save_db()
2020-04-14 16:12:47 +02:00
util.trigger_callback('channels_updated', self.wallet)
2020-03-13 11:44:29 +01:00
@log_exceptions
async def _request_force_close_from_backup(self, channel_id: bytes):
cb = self.channel_backups.get(channel_id)
if not cb:
raise Exception(f'channel backup not found {self.channel_backups}')
cb = cb.cb # storage
self.logger.info(f'requesting channel force close: {channel_id.hex()}')
2021-03-09 09:55:55 +01:00
if isinstance(cb, ImportedChannelBackupStorage):
node_id = cb.node_id
privkey = cb.privkey
2021-03-09 09:55:55 +01:00
addresses = [(cb.host, cb.port, 0)]
else:
assert isinstance(cb, OnchainChannelBackupStorage)
privkey = self.node_keypair.privkey
2022-07-08 16:44:03 +02:00
for pubkey, peer_addr in trampolines_by_id().items():
if pubkey.startswith(cb.node_id_prefix):
node_id = pubkey
addresses = [(peer_addr.host, peer_addr.port, 0)]
break
else:
# we will try with gossip (see below)
addresses = []
async def _request_fclose(addresses):
for host, port, timestamp in addresses:
peer_addr = LNPeerAddr(host, port, node_id)
transport = LNTransport(privkey, peer_addr, proxy=self.network.proxy)
peer = Peer(self, node_id, transport, is_channel_backup=True)
try:
async with OldTaskGroup(wait=any) as group:
await group.spawn(peer._message_loop())
await group.spawn(peer.request_force_close(channel_id))
return True
except Exception as e:
self.logger.info(f'failed to connect {host} {e}')
continue
else:
return False
# try first without gossip db
success = await _request_fclose(addresses)
if success:
return
# try with gossip db
if self.uses_trampoline():
2022-07-08 16:44:03 +02:00
raise Exception(_('Please enable gossip'))
node_id = self.network.channel_db.get_node_by_prefix(cb.node_id_prefix)
addresses_from_gossip = self.network.channel_db.get_node_addresses(node_id)
if not addresses_from_gossip:
raise Exception('Peer not found in gossip database')
success = await _request_fclose(addresses_from_gossip)
if not success:
2021-03-09 09:55:55 +01:00
raise Exception('failed to connect')
def maybe_add_backup_from_tx(self, tx):
funding_address = None
node_id_prefix = None
for i, o in enumerate(tx.outputs()):
script_type = get_script_type_from_output_script(o.scriptpubkey)
if script_type == 'p2wsh':
funding_index = i
funding_address = o.address
for o2 in tx.outputs():
if o2.scriptpubkey.startswith(bytes([opcodes.OP_RETURN])):
encrypted_data = o2.scriptpubkey[2:]
data = self.decrypt_cb_data(encrypted_data, funding_address)
if data.startswith(CB_MAGIC_BYTES):
node_id_prefix = data[4:]
if node_id_prefix is None:
return
funding_txid = tx.txid()
cb_storage = OnchainChannelBackupStorage(
node_id_prefix = node_id_prefix,
funding_txid = funding_txid,
funding_index = funding_index,
funding_address = funding_address,
is_initiator = True)
channel_id = cb_storage.channel_id().hex()
if channel_id in self.db.get_dict("channels"):
return
self.logger.info(f"adding backup from tx")
d = self.db.get_dict("onchain_channel_backups")
d[channel_id] = cb_storage
cb = ChannelBackup(cb_storage, lnworker=self)
2021-03-09 09:55:55 +01:00
self.wallet.save_db()
with self.lock:
self._channel_backups[bfh(channel_id)] = cb
util.trigger_callback('channels_updated', self.wallet)
self.lnwatcher.add_channel(cb.funding_outpoint.to_str(), cb.get_funding_address())