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 std::sync::{Arc, RwLock};
11
12use bitcoin::{Address, Txid};
13
14use crate::config::Config;
15use crate::error::Error;
16use crate::logger::{log_info, LdkLogger, Logger};
17use crate::types::{ChannelManager, Wallet};
18use crate::wallet::OnchainSendAmount;
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	wallet: Arc<Wallet>,
45	channel_manager: Arc<ChannelManager>,
46	config: Arc<Config>,
47	is_running: Arc<RwLock<bool>>,
48	logger: Arc<Logger>,
49}
50
51impl OnchainPayment {
52	pub(crate) fn new(
53		wallet: Arc<Wallet>, channel_manager: Arc<ChannelManager>, config: Arc<Config>,
54		is_running: Arc<RwLock<bool>>, logger: Arc<Logger>,
55	) -> Self {
56		Self { wallet, channel_manager, config, is_running, 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		if !*self.is_running.read().unwrap() {
79			return Err(Error::NotRunning);
80		}
81
82		let cur_anchor_reserve_sats =
83			crate::total_anchor_channels_reserve_sats(&self.channel_manager, &self.config);
84		let send_amount =
85			OnchainSendAmount::ExactRetainingReserve { amount_sats, cur_anchor_reserve_sats };
86		let fee_rate_opt = maybe_map_fee_rate_opt!(fee_rate);
87		self.wallet.send_to_address(address, send_amount, fee_rate_opt)
88	}
89
90	/// Send an on-chain payment to the given address, draining the available funds.
91	///
92	/// This is useful if you have closed all channels and want to migrate funds to another
93	/// on-chain wallet.
94	///
95	/// Please note that if `retain_reserves` is set to `false` this will **not** retain any on-chain reserves, which might be potentially
96	/// dangerous if you have open Anchor channels for which you can't trust the counterparty to
97	/// spend the Anchor output after channel closure. If `retain_reserves` is set to `true`, this
98	/// will try to send all spendable onchain funds, i.e.,
99	/// [`BalanceDetails::spendable_onchain_balance_sats`].
100	///
101	/// If `fee_rate` is set it will be used on the resulting transaction. Otherwise a reasonable
102	/// we'll retrieve an estimate from the configured chain source.
103	///
104	/// [`BalanceDetails::spendable_onchain_balance_sats`]: crate::balance::BalanceDetails::spendable_onchain_balance_sats
105	pub fn send_all_to_address(
106		&self, address: &bitcoin::Address, retain_reserves: bool, fee_rate: Option<FeeRate>,
107	) -> Result<Txid, Error> {
108		if !*self.is_running.read().unwrap() {
109			return Err(Error::NotRunning);
110		}
111
112		let send_amount = if retain_reserves {
113			let cur_anchor_reserve_sats =
114				crate::total_anchor_channels_reserve_sats(&self.channel_manager, &self.config);
115			OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats }
116		} else {
117			OnchainSendAmount::AllDrainingReserve
118		};
119
120		let fee_rate_opt = maybe_map_fee_rate_opt!(fee_rate);
121		self.wallet.send_to_address(address, send_amount, fee_rate_opt)
122	}
123}