ldk_node/
types.rs

1// This file is Copyright its original authors, visible in version control history.
2//
3// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
6// accordance with one or both of these licenses.
7
8use std::fmt;
9use std::sync::{Arc, Mutex};
10
11use bitcoin::secp256k1::PublicKey;
12use bitcoin::OutPoint;
13use lightning::chain::chainmonitor;
14use lightning::impl_writeable_tlv_based;
15use lightning::ln::channel_state::ChannelDetails as LdkChannelDetails;
16use lightning::ln::msgs::{RoutingMessageHandler, SocketAddress};
17use lightning::ln::peer_handler::IgnoringMessageHandler;
18use lightning::ln::types::ChannelId;
19use lightning::routing::gossip;
20use lightning::routing::router::DefaultRouter;
21use lightning::routing::scoring::{CombinedScorer, ProbabilisticScoringFeeParameters};
22use lightning::sign::InMemorySigner;
23use lightning::util::persist::{KVStore, KVStoreSync, MonitorUpdatingPersister};
24use lightning::util::ser::{Readable, Writeable, Writer};
25use lightning::util::sweep::OutputSweeper;
26use lightning_block_sync::gossip::{GossipVerifier, UtxoSource};
27use lightning_liquidity::utils::time::DefaultTimeProvider;
28use lightning_net_tokio::SocketDescriptor;
29
30use crate::chain::ChainSource;
31use crate::config::ChannelConfig;
32use crate::data_store::DataStore;
33use crate::fee_estimator::OnchainFeeEstimator;
34use crate::gossip::RuntimeSpawner;
35use crate::logger::Logger;
36use crate::message_handler::NodeCustomMessageHandler;
37use crate::payment::PaymentDetails;
38
39/// Supported BIP39 mnemonic word counts for entropy generation.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum WordCount {
42	/// 12-word mnemonic (128-bit entropy)
43	Words12,
44	/// 15-word mnemonic (160-bit entropy)
45	Words15,
46	/// 18-word mnemonic (192-bit entropy)
47	Words18,
48	/// 21-word mnemonic (224-bit entropy)
49	Words21,
50	/// 24-word mnemonic (256-bit entropy)
51	Words24,
52}
53
54impl WordCount {
55	/// Returns the word count as a usize value.
56	pub fn word_count(&self) -> usize {
57		match self {
58			WordCount::Words12 => 12,
59			WordCount::Words15 => 15,
60			WordCount::Words18 => 18,
61			WordCount::Words21 => 21,
62			WordCount::Words24 => 24,
63		}
64	}
65}
66
67/// A supertrait that requires that a type implements both [`KVStore`] and [`KVStoreSync`] at the
68/// same time.
69pub trait SyncAndAsyncKVStore: KVStore + KVStoreSync {}
70
71impl<T> SyncAndAsyncKVStore for T
72where
73	T: KVStore,
74	T: KVStoreSync,
75{
76}
77
78/// A type alias for [`SyncAndAsyncKVStore`] with `Sync`/`Send` markers;
79pub type DynStore = dyn SyncAndAsyncKVStore + Sync + Send;
80
81pub type Persister = MonitorUpdatingPersister<
82	Arc<DynStore>,
83	Arc<Logger>,
84	Arc<KeysManager>,
85	Arc<KeysManager>,
86	Arc<Broadcaster>,
87	Arc<OnchainFeeEstimator>,
88>;
89
90pub(crate) type ChainMonitor = chainmonitor::ChainMonitor<
91	InMemorySigner,
92	Arc<ChainSource>,
93	Arc<Broadcaster>,
94	Arc<OnchainFeeEstimator>,
95	Arc<Logger>,
96	Arc<Persister>,
97	Arc<KeysManager>,
98>;
99
100pub(crate) type PeerManager = lightning::ln::peer_handler::PeerManager<
101	SocketDescriptor,
102	Arc<ChannelManager>,
103	Arc<dyn RoutingMessageHandler + Send + Sync>,
104	Arc<OnionMessenger>,
105	Arc<Logger>,
106	Arc<NodeCustomMessageHandler<Arc<Logger>>>,
107	Arc<KeysManager>,
108	Arc<ChainMonitor>,
109>;
110
111pub(crate) type LiquidityManager = lightning_liquidity::LiquidityManager<
112	Arc<KeysManager>,
113	Arc<KeysManager>,
114	Arc<ChannelManager>,
115	Arc<ChainSource>,
116	Arc<DynStore>,
117	DefaultTimeProvider,
118	Arc<Broadcaster>,
119>;
120
121pub(crate) type ChannelManager = lightning::ln::channelmanager::ChannelManager<
122	Arc<ChainMonitor>,
123	Arc<Broadcaster>,
124	Arc<KeysManager>,
125	Arc<KeysManager>,
126	Arc<KeysManager>,
127	Arc<OnchainFeeEstimator>,
128	Arc<Router>,
129	Arc<MessageRouter>,
130	Arc<Logger>,
131>;
132
133pub(crate) type Broadcaster = crate::tx_broadcaster::TransactionBroadcaster<Arc<Logger>>;
134
135pub(crate) type Wallet = crate::wallet::Wallet;
136pub(crate) type KeysManager = crate::wallet::WalletKeysManager;
137
138pub(crate) type Router = DefaultRouter<
139	Arc<Graph>,
140	Arc<Logger>,
141	Arc<KeysManager>,
142	Arc<Mutex<Scorer>>,
143	ProbabilisticScoringFeeParameters,
144	Scorer,
145>;
146pub(crate) type Scorer = CombinedScorer<Arc<Graph>, Arc<Logger>>;
147
148pub(crate) type Graph = gossip::NetworkGraph<Arc<Logger>>;
149
150pub(crate) type UtxoLookup = GossipVerifier<RuntimeSpawner, Arc<dyn UtxoSource>, Arc<Logger>>;
151
152pub(crate) type P2PGossipSync =
153	lightning::routing::gossip::P2PGossipSync<Arc<Graph>, Arc<UtxoLookup>, Arc<Logger>>;
154pub(crate) type RapidGossipSync =
155	lightning_rapid_gossip_sync::RapidGossipSync<Arc<Graph>, Arc<Logger>>;
156
157pub(crate) type GossipSync = lightning_background_processor::GossipSync<
158	Arc<P2PGossipSync>,
159	Arc<RapidGossipSync>,
160	Arc<Graph>,
161	Arc<UtxoLookup>,
162	Arc<Logger>,
163>;
164
165pub(crate) type OnionMessenger = lightning::onion_message::messenger::OnionMessenger<
166	Arc<KeysManager>,
167	Arc<KeysManager>,
168	Arc<Logger>,
169	Arc<ChannelManager>,
170	Arc<MessageRouter>,
171	Arc<ChannelManager>,
172	Arc<ChannelManager>,
173	IgnoringMessageHandler,
174	IgnoringMessageHandler,
175>;
176
177pub(crate) type MessageRouter = lightning::onion_message::messenger::DefaultMessageRouter<
178	Arc<Graph>,
179	Arc<Logger>,
180	Arc<KeysManager>,
181>;
182
183pub(crate) type Sweeper = OutputSweeper<
184	Arc<Broadcaster>,
185	Arc<KeysManager>,
186	Arc<OnchainFeeEstimator>,
187	Arc<ChainSource>,
188	Arc<DynStore>,
189	Arc<Logger>,
190	Arc<KeysManager>,
191>;
192
193pub(crate) type BumpTransactionEventHandler =
194	lightning::events::bump_transaction::BumpTransactionEventHandler<
195		Arc<Broadcaster>,
196		Arc<lightning::events::bump_transaction::Wallet<Arc<Wallet>, Arc<Logger>>>,
197		Arc<KeysManager>,
198		Arc<Logger>,
199	>;
200
201pub(crate) type PaymentStore = DataStore<PaymentDetails, Arc<Logger>>;
202
203/// A local, potentially user-provided, identifier of a channel.
204///
205/// By default, this will be randomly generated for the user to ensure local uniqueness.
206#[derive(Debug, Copy, Clone, PartialEq, Eq)]
207pub struct UserChannelId(pub u128);
208
209impl Writeable for UserChannelId {
210	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), lightning::io::Error> {
211		Ok(self.0.write(writer)?)
212	}
213}
214
215impl Readable for UserChannelId {
216	fn read<R: lightning::io::Read>(
217		reader: &mut R,
218	) -> Result<Self, lightning::ln::msgs::DecodeError> {
219		Ok(Self(Readable::read(reader)?))
220	}
221}
222
223impl fmt::Display for UserChannelId {
224	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225		write!(f, "UserChannelId({})", self.0)
226	}
227}
228
229/// Details of a channel as returned by [`Node::list_channels`].
230///
231/// [`Node::list_channels`]: crate::Node::list_channels
232#[derive(Debug, Clone)]
233pub struct ChannelDetails {
234	/// The channel ID (prior to funding transaction generation, this is a random 32-byte
235	/// identifier, afterwards this is the transaction ID of the funding transaction XOR the
236	/// funding transaction output).
237	///
238	/// Note that this means this value is *not* persistent - it can change once during the
239	/// lifetime of the channel.
240	pub channel_id: ChannelId,
241	/// The node ID of our the channel's counterparty.
242	pub counterparty_node_id: PublicKey,
243	/// The channel's funding transaction output, if we've negotiated the funding transaction with
244	/// our counterparty already.
245	pub funding_txo: Option<OutPoint>,
246	/// The position of the funding transaction in the chain. None if the funding transaction has
247	/// not yet been confirmed and the channel fully opened.
248	///
249	/// Note that if [`inbound_scid_alias`] is set, it will be used for invoices and inbound
250	/// payments instead of this.
251	///
252	/// For channels with [`confirmations_required`] set to `Some(0)`, [`outbound_scid_alias`] may
253	/// be used in place of this in outbound routes.
254	///
255	/// [`inbound_scid_alias`]: Self::inbound_scid_alias
256	/// [`outbound_scid_alias`]: Self::outbound_scid_alias
257	/// [`confirmations_required`]: Self::confirmations_required
258	pub short_channel_id: Option<u64>,
259	/// An optional [`short_channel_id`] alias for this channel, randomly generated by us and
260	/// usable in place of [`short_channel_id`] to reference the channel in outbound routes when
261	/// the channel has not yet been confirmed (as long as [`confirmations_required`] is
262	/// `Some(0)`).
263	///
264	/// This will be `None` as long as the channel is not available for routing outbound payments.
265	///
266	/// [`short_channel_id`]: Self::short_channel_id
267	/// [`confirmations_required`]: Self::confirmations_required
268	pub outbound_scid_alias: Option<u64>,
269	/// An optional [`short_channel_id`] alias for this channel, randomly generated by our
270	/// counterparty and usable in place of [`short_channel_id`] in invoice route hints. Our
271	/// counterparty will recognize the alias provided here in place of the [`short_channel_id`]
272	/// when they see a payment to be routed to us.
273	///
274	/// Our counterparty may choose to rotate this value at any time, though will always recognize
275	/// previous values for inbound payment forwarding.
276	///
277	/// [`short_channel_id`]: Self::short_channel_id
278	pub inbound_scid_alias: Option<u64>,
279	/// The value, in satoshis, of this channel as it appears in the funding output.
280	pub channel_value_sats: u64,
281	/// The value, in satoshis, that must always be held as a reserve in the channel for us. This
282	/// value ensures that if we broadcast a revoked state, our counterparty can punish us by
283	/// claiming at least this value on chain.
284	///
285	/// This value is not included in [`outbound_capacity_msat`] as it can never be spent.
286	///
287	/// This value will be `None` for outbound channels until the counterparty accepts the channel.
288	///
289	/// [`outbound_capacity_msat`]: Self::outbound_capacity_msat
290	pub unspendable_punishment_reserve: Option<u64>,
291	/// The local `user_channel_id` of this channel.
292	pub user_channel_id: UserChannelId,
293	/// The currently negotiated fee rate denominated in satoshi per 1000 weight units,
294	/// which is applied to commitment and HTLC transactions.
295	pub feerate_sat_per_1000_weight: u32,
296	/// The available outbound capacity for sending HTLCs to the remote peer.
297	///
298	/// The amount does not include any pending HTLCs which are not yet resolved (and, thus, whose
299	/// balance is not available for inclusion in new outbound HTLCs). This further does not include
300	/// any pending outgoing HTLCs which are awaiting some other resolution to be sent.
301	pub outbound_capacity_msat: u64,
302	/// The available inbound capacity for receiving HTLCs from the remote peer.
303	///
304	/// The amount does not include any pending HTLCs which are not yet resolved
305	/// (and, thus, whose balance is not available for inclusion in new inbound HTLCs). This further
306	/// does not include any pending incoming HTLCs which are awaiting some other resolution to be
307	/// sent.
308	pub inbound_capacity_msat: u64,
309	/// The number of required confirmations on the funding transactions before the funding is
310	/// considered "locked". The amount is selected by the channel fundee.
311	///
312	/// The value will be `None` for outbound channels until the counterparty accepts the channel.
313	pub confirmations_required: Option<u32>,
314	/// The current number of confirmations on the funding transaction.
315	pub confirmations: Option<u32>,
316	/// Returns `true` if the channel was initiated (and therefore funded) by us.
317	pub is_outbound: bool,
318	/// Returns `true` if both parties have exchanged `channel_ready` messages, and the channel is
319	/// not currently being shut down. Both parties exchange `channel_ready` messages upon
320	/// independently verifying that the required confirmations count provided by
321	/// `confirmations_required` has been reached.
322	pub is_channel_ready: bool,
323	/// Returns `true` if the channel (a) `channel_ready` messages have been exchanged, (b) the
324	/// peer is connected, and (c) the channel is not currently negotiating shutdown.
325	///
326	/// This is a strict superset of `is_channel_ready`.
327	pub is_usable: bool,
328	/// Returns `true` if this channel is (or will be) publicly-announced
329	pub is_announced: bool,
330	/// The difference in the CLTV value between incoming HTLCs and an outbound HTLC forwarded over
331	/// the channel.
332	pub cltv_expiry_delta: Option<u16>,
333	/// The value, in satoshis, that must always be held in the channel for our counterparty. This
334	/// value ensures that if our counterparty broadcasts a revoked state, we can punish them by
335	/// claiming at least this value on chain.
336	///
337	/// This value is not included in [`inbound_capacity_msat`] as it can never be spent.
338	///
339	/// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat
340	pub counterparty_unspendable_punishment_reserve: u64,
341	/// The smallest value HTLC (in msat) the remote peer will accept, for this channel.
342	///
343	/// This field is only `None` before we have received either the `OpenChannel` or
344	/// `AcceptChannel` message from the remote peer.
345	pub counterparty_outbound_htlc_minimum_msat: Option<u64>,
346	/// The largest value HTLC (in msat) the remote peer currently will accept, for this channel.
347	pub counterparty_outbound_htlc_maximum_msat: Option<u64>,
348	/// Base routing fee in millisatoshis.
349	pub counterparty_forwarding_info_fee_base_msat: Option<u32>,
350	/// Proportional fee, in millionths of a satoshi the channel will charge per transferred satoshi.
351	pub counterparty_forwarding_info_fee_proportional_millionths: Option<u32>,
352	/// The minimum difference in CLTV expiry between an ingoing HTLC and its outgoing counterpart,
353	/// such that the outgoing HTLC is forwardable to this counterparty.
354	pub counterparty_forwarding_info_cltv_expiry_delta: Option<u16>,
355	/// The available outbound capacity for sending a single HTLC to the remote peer. This is
356	/// similar to [`ChannelDetails::outbound_capacity_msat`] but it may be further restricted by
357	/// the current state and per-HTLC limit(s). This is intended for use when routing, allowing us
358	/// to use a limit as close as possible to the HTLC limit we can currently send.
359	///
360	/// See also [`ChannelDetails::next_outbound_htlc_minimum_msat`] and
361	/// [`ChannelDetails::outbound_capacity_msat`].
362	pub next_outbound_htlc_limit_msat: u64,
363	/// The minimum value for sending a single HTLC to the remote peer. This is the equivalent of
364	/// [`ChannelDetails::next_outbound_htlc_limit_msat`] but represents a lower-bound, rather than
365	/// an upper-bound. This is intended for use when routing, allowing us to ensure we pick a
366	/// route which is valid.
367	pub next_outbound_htlc_minimum_msat: u64,
368	/// The number of blocks (after our commitment transaction confirms) that we will need to wait
369	/// until we can claim our funds after we force-close the channel. During this time our
370	/// counterparty is allowed to punish us if we broadcasted a stale state. If our counterparty
371	/// force-closes the channel and broadcasts a commitment transaction we do not have to wait any
372	/// time to claim our non-HTLC-encumbered funds.
373	///
374	/// This value will be `None` for outbound channels until the counterparty accepts the channel.
375	pub force_close_spend_delay: Option<u16>,
376	/// The smallest value HTLC (in msat) we will accept, for this channel.
377	pub inbound_htlc_minimum_msat: u64,
378	/// The largest value HTLC (in msat) we currently will accept, for this channel.
379	pub inbound_htlc_maximum_msat: Option<u64>,
380	/// Set of configurable parameters that affect channel operation.
381	pub config: ChannelConfig,
382}
383
384impl From<LdkChannelDetails> for ChannelDetails {
385	fn from(value: LdkChannelDetails) -> Self {
386		ChannelDetails {
387			channel_id: value.channel_id,
388			counterparty_node_id: value.counterparty.node_id,
389			funding_txo: value.funding_txo.map(|o| o.into_bitcoin_outpoint()),
390			short_channel_id: value.short_channel_id,
391			outbound_scid_alias: value.outbound_scid_alias,
392			inbound_scid_alias: value.inbound_scid_alias,
393			channel_value_sats: value.channel_value_satoshis,
394			unspendable_punishment_reserve: value.unspendable_punishment_reserve,
395			user_channel_id: UserChannelId(value.user_channel_id),
396			// unwrap safety: This value will be `None` for objects serialized with LDK versions
397			// prior to 0.0.115.
398			feerate_sat_per_1000_weight: value.feerate_sat_per_1000_weight.unwrap(),
399			outbound_capacity_msat: value.outbound_capacity_msat,
400			inbound_capacity_msat: value.inbound_capacity_msat,
401			confirmations_required: value.confirmations_required,
402			confirmations: value.confirmations,
403			is_outbound: value.is_outbound,
404			is_channel_ready: value.is_channel_ready,
405			is_usable: value.is_usable,
406			is_announced: value.is_announced,
407			cltv_expiry_delta: value.config.map(|c| c.cltv_expiry_delta),
408			counterparty_unspendable_punishment_reserve: value
409				.counterparty
410				.unspendable_punishment_reserve,
411			counterparty_outbound_htlc_minimum_msat: value.counterparty.outbound_htlc_minimum_msat,
412			counterparty_outbound_htlc_maximum_msat: value.counterparty.outbound_htlc_maximum_msat,
413			counterparty_forwarding_info_fee_base_msat: value
414				.counterparty
415				.forwarding_info
416				.as_ref()
417				.map(|f| f.fee_base_msat),
418			counterparty_forwarding_info_fee_proportional_millionths: value
419				.counterparty
420				.forwarding_info
421				.as_ref()
422				.map(|f| f.fee_proportional_millionths),
423			counterparty_forwarding_info_cltv_expiry_delta: value
424				.counterparty
425				.forwarding_info
426				.as_ref()
427				.map(|f| f.cltv_expiry_delta),
428			next_outbound_htlc_limit_msat: value.next_outbound_htlc_limit_msat,
429			next_outbound_htlc_minimum_msat: value.next_outbound_htlc_minimum_msat,
430			force_close_spend_delay: value.force_close_spend_delay,
431			// unwrap safety: This field is only `None` for objects serialized prior to LDK 0.0.107
432			inbound_htlc_minimum_msat: value.inbound_htlc_minimum_msat.unwrap_or(0),
433			inbound_htlc_maximum_msat: value.inbound_htlc_maximum_msat,
434			// unwrap safety: `config` is only `None` for LDK objects serialized prior to 0.0.109.
435			config: value.config.map(|c| c.into()).unwrap(),
436		}
437	}
438}
439
440/// Details of a known Lightning peer as returned by [`Node::list_peers`].
441///
442/// [`Node::list_peers`]: crate::Node::list_peers
443#[derive(Debug, Clone, PartialEq, Eq)]
444pub struct PeerDetails {
445	/// The node ID of the peer.
446	pub node_id: PublicKey,
447	/// The network address of the peer.
448	pub address: SocketAddress,
449	/// Indicates whether we'll try to reconnect to this peer after restarts.
450	pub is_persisted: bool,
451	/// Indicates whether we currently have an active connection with the peer.
452	pub is_connected: bool,
453}
454
455/// Custom TLV entry.
456#[derive(Debug, Clone, PartialEq, Eq)]
457pub struct CustomTlvRecord {
458	/// Type number.
459	pub type_num: u64,
460	/// Serialized value.
461	pub value: Vec<u8>,
462}
463
464impl_writeable_tlv_based!(CustomTlvRecord, {
465	(0, type_num, required),
466	(2, value, required),
467});
468
469impl From<&(u64, Vec<u8>)> for CustomTlvRecord {
470	fn from(tlv: &(u64, Vec<u8>)) -> Self {
471		CustomTlvRecord { type_num: tlv.0, value: tlv.1.clone() }
472	}
473}