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