ldk_node/payment/
onchain.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
8//! Holds a payment handler allowing to send and receive on-chain payments.
9
10use crate::config::Config;
11use crate::error::Error;
12use crate::logger::{log_info, LdkLogger, Logger};
13use crate::types::{ChannelManager, Wallet};
14use crate::wallet::OnchainSendAmount;
15
16use bitcoin::{Address, Txid};
17
18use std::sync::{Arc, RwLock};
19
20#[cfg(not(feature = "uniffi"))]
21type FeeRate = bitcoin::FeeRate;
22#[cfg(feature = "uniffi")]
23type FeeRate = Arc<bitcoin::FeeRate>;
24
25macro_rules! maybe_map_fee_rate_opt {
26	($fee_rate_opt: expr) => {{
27		#[cfg(not(feature = "uniffi"))]
28		{
29			$fee_rate_opt
30		}
31		#[cfg(feature = "uniffi")]
32		{
33			$fee_rate_opt.map(|f| *f)
34		}
35	}};
36}
37
38/// A payment handler allowing to send and receive on-chain payments.
39///
40/// Should be retrieved by calling [`Node::onchain_payment`].
41///
42/// [`Node::onchain_payment`]: crate::Node::onchain_payment
43pub struct OnchainPayment {
44	runtime: Arc<RwLock<Option<Arc<tokio::runtime::Runtime>>>>,
45	wallet: Arc<Wallet>,
46	channel_manager: Arc<ChannelManager>,
47	config: Arc<Config>,
48	logger: Arc<Logger>,
49}
50
51impl OnchainPayment {
52	pub(crate) fn new(
53		runtime: Arc<RwLock<Option<Arc<tokio::runtime::Runtime>>>>, wallet: Arc<Wallet>,
54		channel_manager: Arc<ChannelManager>, config: Arc<Config>, logger: Arc<Logger>,
55	) -> Self {
56		Self { runtime, wallet, channel_manager, config, logger }
57	}
58
59	/// Retrieve a new on-chain/funding address.
60	pub fn new_address(&self) -> Result<Address, Error> {
61		let funding_address = self.wallet.get_new_address()?;
62		log_info!(self.logger, "Generated new funding address: {}", funding_address);
63		Ok(funding_address)
64	}
65
66	/// Send an on-chain payment to the given address.
67	///
68	/// This will respect any on-chain reserve we need to keep, i.e., won't allow to cut into
69	/// [`BalanceDetails::total_anchor_channels_reserve_sats`].
70	///
71	/// If `fee_rate` is set it will be used on the resulting transaction. Otherwise we'll retrieve
72	/// a reasonable estimate from the configured chain source.
73	///
74	/// [`BalanceDetails::total_anchor_channels_reserve_sats`]: crate::BalanceDetails::total_anchor_channels_reserve_sats
75	pub fn send_to_address(
76		&self, address: &bitcoin::Address, amount_sats: u64, fee_rate: Option<FeeRate>,
77	) -> Result<Txid, Error> {
78		let rt_lock = self.runtime.read().unwrap();
79		if rt_lock.is_none() {
80			return Err(Error::NotRunning);
81		}
82
83		let cur_anchor_reserve_sats =
84			crate::total_anchor_channels_reserve_sats(&self.channel_manager, &self.config);
85		let send_amount =
86			OnchainSendAmount::ExactRetainingReserve { amount_sats, cur_anchor_reserve_sats };
87		let fee_rate_opt = maybe_map_fee_rate_opt!(fee_rate);
88		self.wallet.send_to_address(address, send_amount, fee_rate_opt)
89	}
90
91	/// Send an on-chain payment to the given address, draining the available funds.
92	///
93	/// This is useful if you have closed all channels and want to migrate funds to another
94	/// on-chain wallet.
95	///
96	/// Please note that if `retain_reserves` is set to `false` this will **not** retain any on-chain reserves, which might be potentially
97	/// dangerous if you have open Anchor channels for which you can't trust the counterparty to
98	/// spend the Anchor output after channel closure. If `retain_reserves` is set to `true`, this
99	/// will try to send all spendable onchain funds, i.e.,
100	/// [`BalanceDetails::spendable_onchain_balance_sats`].
101	///
102	/// If `fee_rate` is set it will be used on the resulting transaction. Otherwise a reasonable
103	/// we'll retrieve an estimate from the configured chain source.
104	///
105	/// [`BalanceDetails::spendable_onchain_balance_sats`]: crate::balance::BalanceDetails::spendable_onchain_balance_sats
106	pub fn send_all_to_address(
107		&self, address: &bitcoin::Address, retain_reserves: bool, fee_rate: Option<FeeRate>,
108	) -> Result<Txid, Error> {
109		let rt_lock = self.runtime.read().unwrap();
110		if rt_lock.is_none() {
111			return Err(Error::NotRunning);
112		}
113
114		let send_amount = if retain_reserves {
115			let cur_anchor_reserve_sats =
116				crate::total_anchor_channels_reserve_sats(&self.channel_manager, &self.config);
117			OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats }
118		} else {
119			OnchainSendAmount::AllDrainingReserve
120		};
121
122		let fee_rate_opt = maybe_map_fee_rate_opt!(fee_rate);
123		self.wallet.send_to_address(address, send_amount, fee_rate_opt)
124	}
125}