Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -161,7 +161,7 @@ interface OnchainPayment {
[Throws=NodeError]
Txid send_to_address([ByRef]Address address, u64 amount_sats);
[Throws=NodeError]
Txid send_all_to_address([ByRef]Address address);
Txid send_all_to_address([ByRef]Address address, boolean retain_reserve);
};

interface UnifiedQrPayment {
Expand Down
7 changes: 6 additions & 1 deletion src/chain/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -993,11 +993,16 @@ impl ChainSource {
Err(e) => match e {
esplora_client::Error::Reqwest(err) => {
if err.status() == reqwest::StatusCode::from_u16(400).ok() {
// Ignore 400, as this just means bitcoind already knows the
// Log 400 at lesser level, as this often just means bitcoind already knows the
// transaction.
// FIXME: We can further differentiate here based on the error
// message which will be available with rust-esplora-client 0.7 and
// later.
log_trace!(
logger,
"Failed to broadcast due to HTTP connection error: {}",
err
);
} else {
log_error!(
logger,
Expand Down
14 changes: 12 additions & 2 deletions src/error.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@

use bdk_chain::bitcoin::psbt::ExtractTxError as BdkExtractTxError;
use bdk_chain::local_chain::CannotConnectError as BdkChainConnectionError;
use bdk_chain::tx_graph::CalculateFeeError as BdkChainCalculateFeeError;
use bdk_wallet::error::CreateTxError as BdkCreateTxError;
use bdk_wallet::signer::SignerError as BdkSignerError;

Expand DownExpand Up@@ -196,8 +197,11 @@ impl From<BdkSignerError> for Error {
}

impl From<BdkCreateTxError> for Error {
fn from(_: BdkCreateTxError) -> Self {
Self::OnchainTxCreationFailed
fn from(e: BdkCreateTxError) -> Self {
match e {
BdkCreateTxError::CoinSelection(_) => Self::InsufficientFunds,
_ => Self::OnchainTxCreationFailed,
}
}
}

Expand All@@ -213,6 +217,12 @@ impl From<BdkChainConnectionError> for Error {
}
}

impl From<BdkChainCalculateFeeError> for Error {
fn from(_: BdkChainCalculateFeeError) -> Self {
Self::WalletOperationFailed
}
}

impl From<lightning_transaction_sync::TxSyncError> for Error {
fn from(_e: lightning_transaction_sync::TxSyncError) -> Self {
Self::TxSyncFailed
Expand Down
45 changes: 25 additions & 20 deletions src/payment/onchain.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,10 +9,11 @@

use crate::config::Config;
use crate::error::Error;
use crate::logger::{log_error, log_info, FilesystemLogger, Logger};
use crate::logger::{log_info, FilesystemLogger, Logger};
use crate::types::{ChannelManager, Wallet};
use crate::wallet::OnchainSendAmount;

use bitcoin::{Address, Amount, Txid};
use bitcoin::{Address, Txid};

use std::sync::{Arc, RwLock};

Expand DownExpand Up@@ -60,35 +61,39 @@ impl OnchainPayment {

let cur_anchor_reserve_sats =
crate::total_anchor_channels_reserve_sats(&self.channel_manager, &self.config);
let spendable_amount_sats =
self.wallet.get_spendable_amount_sats(cur_anchor_reserve_sats).unwrap_or(0);

if spendable_amount_sats < amount_sats {
log_error!(self.logger,
"Unable to send payment due to insufficient funds. Available: {}sats, Required: {}sats",
spendable_amount_sats, amount_sats
);
return Err(Error::InsufficientFunds);
}

let amount = Amount::from_sat(amount_sats);
self.wallet.send_to_address(address, Some(amount))
let send_amount =
OnchainSendAmount::ExactRetainingReserve { amount_sats, cur_anchor_reserve_sats };
self.wallet.send_to_address(address, send_amount)
}

/// Send an on-chain payment to the given address, draining all the available funds.
/// Send an on-chain payment to the given address, draining the available funds.
///
/// This is useful if you have closed all channels and want to migrate funds to another
/// on-chain wallet.
///
/// Please note that this will **not** retain any on-chain reserves, which might be potentially
/// Please note that if `retain_reserves` is set to `false` this will **not** retain any on-chain reserves, which might be potentially
/// dangerous if you have open Anchor channels for which you can't trust the counterparty to
/// spend the Anchor output after channel closure.
pub fn send_all_to_address(&self, address: &bitcoin::Address) -> Result<Txid, Error> {
/// spend the Anchor output after channel closure. If `retain_reserves` is set to `true`, this
/// will try to send all spendable onchain funds, i.e.,
/// [`BalanceDetails::spendable_onchain_balance_sats`].
///
/// [`BalanceDetails::spendable_onchain_balance_sats`]: crate::balance::BalanceDetails::spendable_onchain_balance_sats
pub fn send_all_to_address(
&self, address: &bitcoin::Address, retain_reserves: bool,
) -> Result<Txid, Error> {
let rt_lock = self.runtime.read().unwrap();
if rt_lock.is_none() {
return Err(Error::NotRunning);
}

self.wallet.send_to_address(address, None)
let send_amount = if retain_reserves {
let cur_anchor_reserve_sats =
crate::total_anchor_channels_reserve_sats(&self.channel_manager, &self.config);
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats }
} else {
OnchainSendAmount::AllDrainingReserve
};

self.wallet.send_to_address(address, send_amount)
}
}
209 changes: 174 additions & 35 deletions src/wallet/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ use lightning_invoice::RawBolt11Invoice;

use bdk_chain::spk_client::{FullScanRequest, SyncRequest};
use bdk_chain::ChainPosition;
use bdk_wallet::{KeychainKind, PersistedWallet, SignOptions, Update};
use bdk_wallet::{Balance, KeychainKind, PersistedWallet, SignOptions, Update};

use bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
use bitcoin::blockdata::locktime::absolute::LockTime;
Expand All@@ -45,6 +45,12 @@ use bitcoin::{
use std::ops::Deref;
use std::sync::{Arc, Mutex};

pub(crate) enum OnchainSendAmount {
ExactRetainingReserve { amount_sats: u64, cur_anchor_reserve_sats: u64 },
AllRetainingReserve { cur_anchor_reserve_sats: u64 },
AllDrainingReserve,
}

pub(crate) mod persist;
pub(crate) mod ser;

Expand DownExpand Up@@ -215,6 +221,12 @@ where
);
}

self.get_balances_inner(balance, total_anchor_channels_reserve_sats)
}

fn get_balances_inner(
&self, balance: Balance, total_anchor_channels_reserve_sats: u64,
) -> Result<(u64, u64), Error> {
let (total, spendable) = (
balance.total().to_sat(),
balance.trusted_spendable().to_sat().saturating_sub(total_anchor_channels_reserve_sats),
Expand All@@ -229,32 +241,95 @@ where
self.get_balances(total_anchor_channels_reserve_sats).map(|(_, s)| s)
}

/// Send funds to the given address.
///
/// If `amount_msat_or_drain` is `None` the wallet will be drained, i.e., all available funds will be
/// spent.
pub(crate) fn send_to_address(
&self, address: &bitcoin::Address, amount_or_drain: Option<Amount>,
&self, address: &bitcoin::Address, send_amount: OnchainSendAmount,
) -> Result<Txid, Error> {
let confirmation_target = ConfirmationTarget::OnchainPayment;
let fee_rate = self.fee_estimator.estimate_fee_rate(confirmation_target);

let tx = {
let mut locked_wallet = self.inner.lock().unwrap();
let mut tx_builder = locked_wallet.build_tx();

if let Some(amount) = amount_or_drain {
tx_builder
.add_recipient(address.script_pubkey(), amount)
.fee_rate(fee_rate)
.enable_rbf();
} else {
tx_builder
.drain_wallet()
.drain_to(address.script_pubkey())
.fee_rate(fee_rate)
.enable_rbf();
}

// Prepare the tx_builder. We properly check the reserve requirements (again) further down.
let tx_builder = match send_amount {
OnchainSendAmount::ExactRetainingReserve { amount_sats, .. } => {
let mut tx_builder = locked_wallet.build_tx();
let amount = Amount::from_sat(amount_sats);
tx_builder
.add_recipient(address.script_pubkey(), amount)
.fee_rate(fee_rate)
.enable_rbf();
tx_builder
},
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats } => {
let change_address_info = locked_wallet.peek_address(KeychainKind::Internal, 0);
let balance = locked_wallet.balance();
let spendable_amount_sats = self
.get_balances_inner(balance, cur_anchor_reserve_sats)
.map(|(_, s)| s)
.unwrap_or(0);
Comment thread
jkczyz marked this conversation as resolved.
let tmp_tx = {
let mut tmp_tx_builder = locked_wallet.build_tx();
tmp_tx_builder
.drain_wallet()
.drain_to(address.script_pubkey())
.add_recipient(
change_address_info.address.script_pubkey(),
Amount::from_sat(cur_anchor_reserve_sats),
)
.fee_rate(fee_rate)
.enable_rbf();
match tmp_tx_builder.finish() {
Ok(psbt) => psbt.unsigned_tx,
Err(err) => {
log_error!(
self.logger,
"Failed to create temporary transaction: {}",
err
);
return Err(err.into());
},
}
};

let estimated_tx_fee = locked_wallet.calculate_fee(&tmp_tx).map_err(|e| {
log_error!(
self.logger,
"Failed to calculate fee of temporary transaction: {}",
e
);
e
})?;
let estimated_spendable_amount = Amount::from_sat(
spendable_amount_sats.saturating_sub(estimated_tx_fee.to_sat()),
);

if estimated_spendable_amount == Amount::ZERO {
log_error!(self.logger,
"Unable to send payment without infringing on Anchor reserves. Available: {}sats, estimated fee required: {}sats.",
spendable_amount_sats,
estimated_tx_fee,
);
return Err(Error::InsufficientFunds);
}

let mut tx_builder = locked_wallet.build_tx();
tx_builder
.add_recipient(address.script_pubkey(), estimated_spendable_amount)
.fee_absolute(estimated_tx_fee)
.enable_rbf();
tx_builder
},
OnchainSendAmount::AllDrainingReserve => {
let mut tx_builder = locked_wallet.build_tx();
tx_builder
.drain_wallet()
.drain_to(address.script_pubkey())
.fee_rate(fee_rate)
.enable_rbf();
tx_builder
},
};

let mut psbt = match tx_builder.finish() {
Ok(psbt) => {
Expand All@@ -267,6 +342,58 @@ where
},
};

// Check the reserve requirements (again) and return an error if they aren't met.
match send_amount {
OnchainSendAmount::ExactRetainingReserve {
amount_sats,
cur_anchor_reserve_sats,
} => {
let balance = locked_wallet.balance();
let spendable_amount_sats = self
.get_balances_inner(balance, cur_anchor_reserve_sats)
.map(|(_, s)| s)
.unwrap_or(0);
let tx_fee_sats = locked_wallet
.calculate_fee(&psbt.unsigned_tx)
.map_err(|e| {
log_error!(
self.logger,
"Failed to calculate fee of candidate transaction: {}",
e
);
e
})?
.to_sat();
if spendable_amount_sats < amount_sats.saturating_add(tx_fee_sats) {
log_error!(self.logger,
"Unable to send payment due to insufficient funds. Available: {}sats, Required: {}sats + {}sats fee",
spendable_amount_sats,
amount_sats,
tx_fee_sats,
);
return Err(Error::InsufficientFunds);
}
},
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats } => {
let balance = locked_wallet.balance();
let spendable_amount_sats = self
.get_balances_inner(balance, cur_anchor_reserve_sats)
.map(|(_, s)| s)
.unwrap_or(0);
let (sent, received) = locked_wallet.sent_and_received(&psbt.unsigned_tx);
let drain_amount = sent - received;
if spendable_amount_sats < drain_amount.to_sat() {
log_error!(self.logger,
"Unable to send payment due to insufficient funds. Available: {}sats, Required: {}",
spendable_amount_sats,
drain_amount,
);
return Err(Error::InsufficientFunds);
}
},
_ => {},
}

match locked_wallet.sign(&mut psbt, SignOptions::default()) {
Ok(finalized) => {
if !finalized {
Expand DownExpand Up@@ -295,21 +422,33 @@ where

let txid = tx.compute_txid();

if let Some(amount) = amount_or_drain {
log_info!(
self.logger,
"Created new transaction {} sending {}sats on-chain to address {}",
txid,
amount.to_sat(),
address
);
} else {
log_info!(
self.logger,
"Created new transaction {} sending all available on-chain funds to address {}",
txid,
address
);
match send_amount {
OnchainSendAmount::ExactRetainingReserve { amount_sats, .. } => {
log_info!(
self.logger,
"Created new transaction {} sending {}sats on-chain to address {}",
txid,
amount_sats,
address
);
},
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats } => {
log_info!(
self.logger,
"Created new transaction {} sending available on-chain funds retaining a reserve of {}sats to address {}",
txid,
cur_anchor_reserve_sats,
address,
);
},
OnchainSendAmount::AllDrainingReserve => {
log_info!(
self.logger,
"Created new transaction {} sending all available on-chain funds to address {}",
txid,
address
);
},
}

Ok(txid)
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Allow honoring reserve in `send_all_to_address` by tnull · Pull Request #345 · lightningdevkit/ldk-node · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -161,7 +161,7 @@ interface OnchainPayment {
[Throws=NodeError]
Txid send_to_address([ByRef]Address address, u64 amount_sats);
[Throws=NodeError]
Txid send_all_to_address([ByRef]Address address);
Txid send_all_to_address([ByRef]Address address, boolean retain_reserve);
};

interface UnifiedQrPayment {
Expand Down
7 changes: 6 additions & 1 deletion src/chain/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -993,11 +993,16 @@ impl ChainSource {
Err(e) => match e {
esplora_client::Error::Reqwest(err) => {
if err.status() == reqwest::StatusCode::from_u16(400).ok() {
// Ignore 400, as this just means bitcoind already knows the
// Log 400 at lesser level, as this often just means bitcoind already knows the
// transaction.
// FIXME: We can further differentiate here based on the error
// message which will be available with rust-esplora-client 0.7 and
// later.
log_trace!(
logger,
"Failed to broadcast due to HTTP connection error: {}",
err
);
} else {
log_error!(
logger,
Expand Down
14 changes: 12 additions & 2 deletions src/error.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@

use bdk_chain::bitcoin::psbt::ExtractTxError as BdkExtractTxError;
use bdk_chain::local_chain::CannotConnectError as BdkChainConnectionError;
use bdk_chain::tx_graph::CalculateFeeError as BdkChainCalculateFeeError;
use bdk_wallet::error::CreateTxError as BdkCreateTxError;
use bdk_wallet::signer::SignerError as BdkSignerError;

Expand DownExpand Up@@ -196,8 +197,11 @@ impl From<BdkSignerError> for Error {
}

impl From<BdkCreateTxError> for Error {
fn from(_: BdkCreateTxError) -> Self {
Self::OnchainTxCreationFailed
fn from(e: BdkCreateTxError) -> Self {
match e {
BdkCreateTxError::CoinSelection(_) => Self::InsufficientFunds,
_ => Self::OnchainTxCreationFailed,
}
}
}

Expand All@@ -213,6 +217,12 @@ impl From<BdkChainConnectionError> for Error {
}
}

impl From<BdkChainCalculateFeeError> for Error {
fn from(_: BdkChainCalculateFeeError) -> Self {
Self::WalletOperationFailed
}
}

impl From<lightning_transaction_sync::TxSyncError> for Error {
fn from(_e: lightning_transaction_sync::TxSyncError) -> Self {
Self::TxSyncFailed
Expand Down
45 changes: 25 additions & 20 deletions src/payment/onchain.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,10 +9,11 @@

use crate::config::Config;
use crate::error::Error;
use crate::logger::{log_error, log_info, FilesystemLogger, Logger};
use crate::logger::{log_info, FilesystemLogger, Logger};
use crate::types::{ChannelManager, Wallet};
use crate::wallet::OnchainSendAmount;

use bitcoin::{Address, Amount, Txid};
use bitcoin::{Address, Txid};

use std::sync::{Arc, RwLock};

Expand DownExpand Up@@ -60,35 +61,39 @@ impl OnchainPayment {

let cur_anchor_reserve_sats =
crate::total_anchor_channels_reserve_sats(&self.channel_manager, &self.config);
let spendable_amount_sats =
self.wallet.get_spendable_amount_sats(cur_anchor_reserve_sats).unwrap_or(0);

if spendable_amount_sats < amount_sats {
log_error!(self.logger,
"Unable to send payment due to insufficient funds. Available: {}sats, Required: {}sats",
spendable_amount_sats, amount_sats
);
return Err(Error::InsufficientFunds);
}

let amount = Amount::from_sat(amount_sats);
self.wallet.send_to_address(address, Some(amount))
let send_amount =
OnchainSendAmount::ExactRetainingReserve { amount_sats, cur_anchor_reserve_sats };
self.wallet.send_to_address(address, send_amount)
}

/// Send an on-chain payment to the given address, draining all the available funds.
/// Send an on-chain payment to the given address, draining the available funds.
///
/// This is useful if you have closed all channels and want to migrate funds to another
/// on-chain wallet.
///
/// Please note that this will **not** retain any on-chain reserves, which might be potentially
/// Please note that if `retain_reserves` is set to `false` this will **not** retain any on-chain reserves, which might be potentially
/// dangerous if you have open Anchor channels for which you can't trust the counterparty to
/// spend the Anchor output after channel closure.
pub fn send_all_to_address(&self, address: &bitcoin::Address) -> Result<Txid, Error> {
/// spend the Anchor output after channel closure. If `retain_reserves` is set to `true`, this
/// will try to send all spendable onchain funds, i.e.,
/// [`BalanceDetails::spendable_onchain_balance_sats`].
///
/// [`BalanceDetails::spendable_onchain_balance_sats`]: crate::balance::BalanceDetails::spendable_onchain_balance_sats
pub fn send_all_to_address(
&self, address: &bitcoin::Address, retain_reserves: bool,
) -> Result<Txid, Error> {
let rt_lock = self.runtime.read().unwrap();
if rt_lock.is_none() {
return Err(Error::NotRunning);
}

self.wallet.send_to_address(address, None)
let send_amount = if retain_reserves {
let cur_anchor_reserve_sats =
crate::total_anchor_channels_reserve_sats(&self.channel_manager, &self.config);
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats }
} else {
OnchainSendAmount::AllDrainingReserve
};

self.wallet.send_to_address(address, send_amount)
}
}
209 changes: 174 additions & 35 deletions src/wallet/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ use lightning_invoice::RawBolt11Invoice;

use bdk_chain::spk_client::{FullScanRequest, SyncRequest};
use bdk_chain::ChainPosition;
use bdk_wallet::{KeychainKind, PersistedWallet, SignOptions, Update};
use bdk_wallet::{Balance, KeychainKind, PersistedWallet, SignOptions, Update};

use bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
use bitcoin::blockdata::locktime::absolute::LockTime;
Expand All@@ -45,6 +45,12 @@ use bitcoin::{
use std::ops::Deref;
use std::sync::{Arc, Mutex};

pub(crate) enum OnchainSendAmount {
ExactRetainingReserve { amount_sats: u64, cur_anchor_reserve_sats: u64 },
AllRetainingReserve { cur_anchor_reserve_sats: u64 },
AllDrainingReserve,
}

pub(crate) mod persist;
pub(crate) mod ser;

Expand DownExpand Up@@ -215,6 +221,12 @@ where
);
}

self.get_balances_inner(balance, total_anchor_channels_reserve_sats)
}

fn get_balances_inner(
&self, balance: Balance, total_anchor_channels_reserve_sats: u64,
) -> Result<(u64, u64), Error> {
let (total, spendable) = (
balance.total().to_sat(),
balance.trusted_spendable().to_sat().saturating_sub(total_anchor_channels_reserve_sats),
Expand All@@ -229,32 +241,95 @@ where
self.get_balances(total_anchor_channels_reserve_sats).map(|(_, s)| s)
}

/// Send funds to the given address.
///
/// If `amount_msat_or_drain` is `None` the wallet will be drained, i.e., all available funds will be
/// spent.
pub(crate) fn send_to_address(
&self, address: &bitcoin::Address, amount_or_drain: Option<Amount>,
&self, address: &bitcoin::Address, send_amount: OnchainSendAmount,
) -> Result<Txid, Error> {
let confirmation_target = ConfirmationTarget::OnchainPayment;
let fee_rate = self.fee_estimator.estimate_fee_rate(confirmation_target);

let tx = {
let mut locked_wallet = self.inner.lock().unwrap();
let mut tx_builder = locked_wallet.build_tx();

if let Some(amount) = amount_or_drain {
tx_builder
.add_recipient(address.script_pubkey(), amount)
.fee_rate(fee_rate)
.enable_rbf();
} else {
tx_builder
.drain_wallet()
.drain_to(address.script_pubkey())
.fee_rate(fee_rate)
.enable_rbf();
}

// Prepare the tx_builder. We properly check the reserve requirements (again) further down.
let tx_builder = match send_amount {
OnchainSendAmount::ExactRetainingReserve { amount_sats, .. } => {
let mut tx_builder = locked_wallet.build_tx();
let amount = Amount::from_sat(amount_sats);
tx_builder
.add_recipient(address.script_pubkey(), amount)
.fee_rate(fee_rate)
.enable_rbf();
tx_builder
},
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats } => {
let change_address_info = locked_wallet.peek_address(KeychainKind::Internal, 0);
let balance = locked_wallet.balance();
let spendable_amount_sats = self
.get_balances_inner(balance, cur_anchor_reserve_sats)
.map(|(_, s)| s)
.unwrap_or(0);
Comment thread
jkczyz marked this conversation as resolved.
let tmp_tx = {
let mut tmp_tx_builder = locked_wallet.build_tx();
tmp_tx_builder
.drain_wallet()
.drain_to(address.script_pubkey())
.add_recipient(
change_address_info.address.script_pubkey(),
Amount::from_sat(cur_anchor_reserve_sats),
)
.fee_rate(fee_rate)
.enable_rbf();
match tmp_tx_builder.finish() {
Ok(psbt) => psbt.unsigned_tx,
Err(err) => {
log_error!(
self.logger,
"Failed to create temporary transaction: {}",
err
);
return Err(err.into());
},
}
};

let estimated_tx_fee = locked_wallet.calculate_fee(&tmp_tx).map_err(|e| {
log_error!(
self.logger,
"Failed to calculate fee of temporary transaction: {}",
e
);
e
})?;
let estimated_spendable_amount = Amount::from_sat(
spendable_amount_sats.saturating_sub(estimated_tx_fee.to_sat()),
);

if estimated_spendable_amount == Amount::ZERO {
log_error!(self.logger,
"Unable to send payment without infringing on Anchor reserves. Available: {}sats, estimated fee required: {}sats.",
spendable_amount_sats,
estimated_tx_fee,
);
return Err(Error::InsufficientFunds);
}

let mut tx_builder = locked_wallet.build_tx();
tx_builder
.add_recipient(address.script_pubkey(), estimated_spendable_amount)
.fee_absolute(estimated_tx_fee)
.enable_rbf();
tx_builder
},
OnchainSendAmount::AllDrainingReserve => {
let mut tx_builder = locked_wallet.build_tx();
tx_builder
.drain_wallet()
.drain_to(address.script_pubkey())
.fee_rate(fee_rate)
.enable_rbf();
tx_builder
},
};

let mut psbt = match tx_builder.finish() {
Ok(psbt) => {
Expand All@@ -267,6 +342,58 @@ where
},
};

// Check the reserve requirements (again) and return an error if they aren't met.
match send_amount {
OnchainSendAmount::ExactRetainingReserve {
amount_sats,
cur_anchor_reserve_sats,
} => {
let balance = locked_wallet.balance();
let spendable_amount_sats = self
.get_balances_inner(balance, cur_anchor_reserve_sats)
.map(|(_, s)| s)
.unwrap_or(0);
let tx_fee_sats = locked_wallet
.calculate_fee(&psbt.unsigned_tx)
.map_err(|e| {
log_error!(
self.logger,
"Failed to calculate fee of candidate transaction: {}",
e
);
e
})?
.to_sat();
if spendable_amount_sats < amount_sats.saturating_add(tx_fee_sats) {
log_error!(self.logger,
"Unable to send payment due to insufficient funds. Available: {}sats, Required: {}sats + {}sats fee",
spendable_amount_sats,
amount_sats,
tx_fee_sats,
);
return Err(Error::InsufficientFunds);
}
},
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats } => {
let balance = locked_wallet.balance();
let spendable_amount_sats = self
.get_balances_inner(balance, cur_anchor_reserve_sats)
.map(|(_, s)| s)
.unwrap_or(0);
let (sent, received) = locked_wallet.sent_and_received(&psbt.unsigned_tx);
let drain_amount = sent - received;
if spendable_amount_sats < drain_amount.to_sat() {
log_error!(self.logger,
"Unable to send payment due to insufficient funds. Available: {}sats, Required: {}",
spendable_amount_sats,
drain_amount,
);
return Err(Error::InsufficientFunds);
}
},
_ => {},
}

match locked_wallet.sign(&mut psbt, SignOptions::default()) {
Ok(finalized) => {
if !finalized {
Expand DownExpand Up@@ -295,21 +422,33 @@ where

let txid = tx.compute_txid();

if let Some(amount) = amount_or_drain {
log_info!(
self.logger,
"Created new transaction {} sending {}sats on-chain to address {}",
txid,
amount.to_sat(),
address
);
} else {
log_info!(
self.logger,
"Created new transaction {} sending all available on-chain funds to address {}",
txid,
address
);
match send_amount {
OnchainSendAmount::ExactRetainingReserve { amount_sats, .. } => {
log_info!(
self.logger,
"Created new transaction {} sending {}sats on-chain to address {}",
txid,
amount_sats,
address
);
},
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats } => {
log_info!(
self.logger,
"Created new transaction {} sending available on-chain funds retaining a reserve of {}sats to address {}",
txid,
cur_anchor_reserve_sats,
address,
);
},
OnchainSendAmount::AllDrainingReserve => {
log_info!(
self.logger,
"Created new transaction {} sending all available on-chain funds to address {}",
txid,
address
);
},
}

Ok(txid)
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Allow honoring reserve in `send_all_to_address` by tnull · Pull Request #345 · lightningdevkit/ldk-node · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -161,7 +161,7 @@ interface OnchainPayment {
[Throws=NodeError]
Txid send_to_address([ByRef]Address address, u64 amount_sats);
[Throws=NodeError]
Txid send_all_to_address([ByRef]Address address);
Txid send_all_to_address([ByRef]Address address, boolean retain_reserve);
};

interface UnifiedQrPayment {
Expand Down
7 changes: 6 additions & 1 deletion src/chain/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -993,11 +993,16 @@ impl ChainSource {
Err(e) => match e {
esplora_client::Error::Reqwest(err) => {
if err.status() == reqwest::StatusCode::from_u16(400).ok() {
// Ignore 400, as this just means bitcoind already knows the
// Log 400 at lesser level, as this often just means bitcoind already knows the
// transaction.
// FIXME: We can further differentiate here based on the error
// message which will be available with rust-esplora-client 0.7 and
// later.
log_trace!(
logger,
"Failed to broadcast due to HTTP connection error: {}",
err
);
} else {
log_error!(
logger,
Expand Down
14 changes: 12 additions & 2 deletions src/error.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@

use bdk_chain::bitcoin::psbt::ExtractTxError as BdkExtractTxError;
use bdk_chain::local_chain::CannotConnectError as BdkChainConnectionError;
use bdk_chain::tx_graph::CalculateFeeError as BdkChainCalculateFeeError;
use bdk_wallet::error::CreateTxError as BdkCreateTxError;
use bdk_wallet::signer::SignerError as BdkSignerError;

Expand DownExpand Up@@ -196,8 +197,11 @@ impl From<BdkSignerError> for Error {
}

impl From<BdkCreateTxError> for Error {
fn from(_: BdkCreateTxError) -> Self {
Self::OnchainTxCreationFailed
fn from(e: BdkCreateTxError) -> Self {
match e {
BdkCreateTxError::CoinSelection(_) => Self::InsufficientFunds,
_ => Self::OnchainTxCreationFailed,
}
}
}

Expand All@@ -213,6 +217,12 @@ impl From<BdkChainConnectionError> for Error {
}
}

impl From<BdkChainCalculateFeeError> for Error {
fn from(_: BdkChainCalculateFeeError) -> Self {
Self::WalletOperationFailed
}
}

impl From<lightning_transaction_sync::TxSyncError> for Error {
fn from(_e: lightning_transaction_sync::TxSyncError) -> Self {
Self::TxSyncFailed
Expand Down
45 changes: 25 additions & 20 deletions src/payment/onchain.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,10 +9,11 @@

use crate::config::Config;
use crate::error::Error;
use crate::logger::{log_error, log_info, FilesystemLogger, Logger};
use crate::logger::{log_info, FilesystemLogger, Logger};
use crate::types::{ChannelManager, Wallet};
use crate::wallet::OnchainSendAmount;

use bitcoin::{Address, Amount, Txid};
use bitcoin::{Address, Txid};

use std::sync::{Arc, RwLock};

Expand DownExpand Up@@ -60,35 +61,39 @@ impl OnchainPayment {

let cur_anchor_reserve_sats =
crate::total_anchor_channels_reserve_sats(&self.channel_manager, &self.config);
let spendable_amount_sats =
self.wallet.get_spendable_amount_sats(cur_anchor_reserve_sats).unwrap_or(0);

if spendable_amount_sats < amount_sats {
log_error!(self.logger,
"Unable to send payment due to insufficient funds. Available: {}sats, Required: {}sats",
spendable_amount_sats, amount_sats
);
return Err(Error::InsufficientFunds);
}

let amount = Amount::from_sat(amount_sats);
self.wallet.send_to_address(address, Some(amount))
let send_amount =
OnchainSendAmount::ExactRetainingReserve { amount_sats, cur_anchor_reserve_sats };
self.wallet.send_to_address(address, send_amount)
}

/// Send an on-chain payment to the given address, draining all the available funds.
/// Send an on-chain payment to the given address, draining the available funds.
///
/// This is useful if you have closed all channels and want to migrate funds to another
/// on-chain wallet.
///
/// Please note that this will **not** retain any on-chain reserves, which might be potentially
/// Please note that if `retain_reserves` is set to `false` this will **not** retain any on-chain reserves, which might be potentially
/// dangerous if you have open Anchor channels for which you can't trust the counterparty to
/// spend the Anchor output after channel closure.
pub fn send_all_to_address(&self, address: &bitcoin::Address) -> Result<Txid, Error> {
/// spend the Anchor output after channel closure. If `retain_reserves` is set to `true`, this
/// will try to send all spendable onchain funds, i.e.,
/// [`BalanceDetails::spendable_onchain_balance_sats`].
///
/// [`BalanceDetails::spendable_onchain_balance_sats`]: crate::balance::BalanceDetails::spendable_onchain_balance_sats
pub fn send_all_to_address(
&self, address: &bitcoin::Address, retain_reserves: bool,
) -> Result<Txid, Error> {
let rt_lock = self.runtime.read().unwrap();
if rt_lock.is_none() {
return Err(Error::NotRunning);
}

self.wallet.send_to_address(address, None)
let send_amount = if retain_reserves {
let cur_anchor_reserve_sats =
crate::total_anchor_channels_reserve_sats(&self.channel_manager, &self.config);
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats }
} else {
OnchainSendAmount::AllDrainingReserve
};

self.wallet.send_to_address(address, send_amount)
}
}
209 changes: 174 additions & 35 deletions src/wallet/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ use lightning_invoice::RawBolt11Invoice;

use bdk_chain::spk_client::{FullScanRequest, SyncRequest};
use bdk_chain::ChainPosition;
use bdk_wallet::{KeychainKind, PersistedWallet, SignOptions, Update};
use bdk_wallet::{Balance, KeychainKind, PersistedWallet, SignOptions, Update};

use bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
use bitcoin::blockdata::locktime::absolute::LockTime;
Expand All@@ -45,6 +45,12 @@ use bitcoin::{
use std::ops::Deref;
use std::sync::{Arc, Mutex};

pub(crate) enum OnchainSendAmount {
ExactRetainingReserve { amount_sats: u64, cur_anchor_reserve_sats: u64 },
AllRetainingReserve { cur_anchor_reserve_sats: u64 },
AllDrainingReserve,
}

pub(crate) mod persist;
pub(crate) mod ser;

Expand DownExpand Up@@ -215,6 +221,12 @@ where
);
}

self.get_balances_inner(balance, total_anchor_channels_reserve_sats)
}

fn get_balances_inner(
&self, balance: Balance, total_anchor_channels_reserve_sats: u64,
) -> Result<(u64, u64), Error> {
let (total, spendable) = (
balance.total().to_sat(),
balance.trusted_spendable().to_sat().saturating_sub(total_anchor_channels_reserve_sats),
Expand All@@ -229,32 +241,95 @@ where
self.get_balances(total_anchor_channels_reserve_sats).map(|(_, s)| s)
}

/// Send funds to the given address.
///
/// If `amount_msat_or_drain` is `None` the wallet will be drained, i.e., all available funds will be
/// spent.
pub(crate) fn send_to_address(
&self, address: &bitcoin::Address, amount_or_drain: Option<Amount>,
&self, address: &bitcoin::Address, send_amount: OnchainSendAmount,
) -> Result<Txid, Error> {
let confirmation_target = ConfirmationTarget::OnchainPayment;
let fee_rate = self.fee_estimator.estimate_fee_rate(confirmation_target);

let tx = {
let mut locked_wallet = self.inner.lock().unwrap();
let mut tx_builder = locked_wallet.build_tx();

if let Some(amount) = amount_or_drain {
tx_builder
.add_recipient(address.script_pubkey(), amount)
.fee_rate(fee_rate)
.enable_rbf();
} else {
tx_builder
.drain_wallet()
.drain_to(address.script_pubkey())
.fee_rate(fee_rate)
.enable_rbf();
}

// Prepare the tx_builder. We properly check the reserve requirements (again) further down.
let tx_builder = match send_amount {
OnchainSendAmount::ExactRetainingReserve { amount_sats, .. } => {
let mut tx_builder = locked_wallet.build_tx();
let amount = Amount::from_sat(amount_sats);
tx_builder
.add_recipient(address.script_pubkey(), amount)
.fee_rate(fee_rate)
.enable_rbf();
tx_builder
},
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats } => {
let change_address_info = locked_wallet.peek_address(KeychainKind::Internal, 0);
let balance = locked_wallet.balance();
let spendable_amount_sats = self
.get_balances_inner(balance, cur_anchor_reserve_sats)
.map(|(_, s)| s)
.unwrap_or(0);
Comment thread
jkczyz marked this conversation as resolved.
let tmp_tx = {
let mut tmp_tx_builder = locked_wallet.build_tx();
tmp_tx_builder
.drain_wallet()
.drain_to(address.script_pubkey())
.add_recipient(
change_address_info.address.script_pubkey(),
Amount::from_sat(cur_anchor_reserve_sats),
)
.fee_rate(fee_rate)
.enable_rbf();
match tmp_tx_builder.finish() {
Ok(psbt) => psbt.unsigned_tx,
Err(err) => {
log_error!(
self.logger,
"Failed to create temporary transaction: {}",
err
);
return Err(err.into());
},
}
};

let estimated_tx_fee = locked_wallet.calculate_fee(&tmp_tx).map_err(|e| {
log_error!(
self.logger,
"Failed to calculate fee of temporary transaction: {}",
e
);
e
})?;
let estimated_spendable_amount = Amount::from_sat(
spendable_amount_sats.saturating_sub(estimated_tx_fee.to_sat()),
);

if estimated_spendable_amount == Amount::ZERO {
log_error!(self.logger,
"Unable to send payment without infringing on Anchor reserves. Available: {}sats, estimated fee required: {}sats.",
spendable_amount_sats,
estimated_tx_fee,
);
return Err(Error::InsufficientFunds);
}

let mut tx_builder = locked_wallet.build_tx();
tx_builder
.add_recipient(address.script_pubkey(), estimated_spendable_amount)
.fee_absolute(estimated_tx_fee)
.enable_rbf();
tx_builder
},
OnchainSendAmount::AllDrainingReserve => {
let mut tx_builder = locked_wallet.build_tx();
tx_builder
.drain_wallet()
.drain_to(address.script_pubkey())
.fee_rate(fee_rate)
.enable_rbf();
tx_builder
},
};

let mut psbt = match tx_builder.finish() {
Ok(psbt) => {
Expand All@@ -267,6 +342,58 @@ where
},
};

// Check the reserve requirements (again) and return an error if they aren't met.
match send_amount {
OnchainSendAmount::ExactRetainingReserve {
amount_sats,
cur_anchor_reserve_sats,
} => {
let balance = locked_wallet.balance();
let spendable_amount_sats = self
.get_balances_inner(balance, cur_anchor_reserve_sats)
.map(|(_, s)| s)
.unwrap_or(0);
let tx_fee_sats = locked_wallet
.calculate_fee(&psbt.unsigned_tx)
.map_err(|e| {
log_error!(
self.logger,
"Failed to calculate fee of candidate transaction: {}",
e
);
e
})?
.to_sat();
if spendable_amount_sats < amount_sats.saturating_add(tx_fee_sats) {
log_error!(self.logger,
"Unable to send payment due to insufficient funds. Available: {}sats, Required: {}sats + {}sats fee",
spendable_amount_sats,
amount_sats,
tx_fee_sats,
);
return Err(Error::InsufficientFunds);
}
},
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats } => {
let balance = locked_wallet.balance();
let spendable_amount_sats = self
.get_balances_inner(balance, cur_anchor_reserve_sats)
.map(|(_, s)| s)
.unwrap_or(0);
let (sent, received) = locked_wallet.sent_and_received(&psbt.unsigned_tx);
let drain_amount = sent - received;
if spendable_amount_sats < drain_amount.to_sat() {
log_error!(self.logger,
"Unable to send payment due to insufficient funds. Available: {}sats, Required: {}",
spendable_amount_sats,
drain_amount,
);
return Err(Error::InsufficientFunds);
}
},
_ => {},
}

match locked_wallet.sign(&mut psbt, SignOptions::default()) {
Ok(finalized) => {
if !finalized {
Expand DownExpand Up@@ -295,21 +422,33 @@ where

let txid = tx.compute_txid();

if let Some(amount) = amount_or_drain {
log_info!(
self.logger,
"Created new transaction {} sending {}sats on-chain to address {}",
txid,
amount.to_sat(),
address
);
} else {
log_info!(
self.logger,
"Created new transaction {} sending all available on-chain funds to address {}",
txid,
address
);
match send_amount {
OnchainSendAmount::ExactRetainingReserve { amount_sats, .. } => {
log_info!(
self.logger,
"Created new transaction {} sending {}sats on-chain to address {}",
txid,
amount_sats,
address
);
},
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats } => {
log_info!(
self.logger,
"Created new transaction {} sending available on-chain funds retaining a reserve of {}sats to address {}",
txid,
cur_anchor_reserve_sats,
address,
);
},
OnchainSendAmount::AllDrainingReserve => {
log_info!(
self.logger,
"Created new transaction {} sending all available on-chain funds to address {}",
txid,
address
);
},
}

Ok(txid)
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Allow honoring reserve in `send_all_to_address` by tnull · Pull Request #345 · lightningdevkit/ldk-node · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -161,7 +161,7 @@ interface OnchainPayment {
[Throws=NodeError]
Txid send_to_address([ByRef]Address address, u64 amount_sats);
[Throws=NodeError]
Txid send_all_to_address([ByRef]Address address);
Txid send_all_to_address([ByRef]Address address, boolean retain_reserve);
};

interface UnifiedQrPayment {
Expand Down
7 changes: 6 additions & 1 deletion src/chain/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -993,11 +993,16 @@ impl ChainSource {
Err(e) => match e {
esplora_client::Error::Reqwest(err) => {
if err.status() == reqwest::StatusCode::from_u16(400).ok() {
// Ignore 400, as this just means bitcoind already knows the
// Log 400 at lesser level, as this often just means bitcoind already knows the
// transaction.
// FIXME: We can further differentiate here based on the error
// message which will be available with rust-esplora-client 0.7 and
// later.
log_trace!(
logger,
"Failed to broadcast due to HTTP connection error: {}",
err
);
} else {
log_error!(
logger,
Expand Down
14 changes: 12 additions & 2 deletions src/error.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@

use bdk_chain::bitcoin::psbt::ExtractTxError as BdkExtractTxError;
use bdk_chain::local_chain::CannotConnectError as BdkChainConnectionError;
use bdk_chain::tx_graph::CalculateFeeError as BdkChainCalculateFeeError;
use bdk_wallet::error::CreateTxError as BdkCreateTxError;
use bdk_wallet::signer::SignerError as BdkSignerError;

Expand DownExpand Up@@ -196,8 +197,11 @@ impl From<BdkSignerError> for Error {
}

impl From<BdkCreateTxError> for Error {
fn from(_: BdkCreateTxError) -> Self {
Self::OnchainTxCreationFailed
fn from(e: BdkCreateTxError) -> Self {
match e {
BdkCreateTxError::CoinSelection(_) => Self::InsufficientFunds,
_ => Self::OnchainTxCreationFailed,
}
}
}

Expand All@@ -213,6 +217,12 @@ impl From<BdkChainConnectionError> for Error {
}
}

impl From<BdkChainCalculateFeeError> for Error {
fn from(_: BdkChainCalculateFeeError) -> Self {
Self::WalletOperationFailed
}
}

impl From<lightning_transaction_sync::TxSyncError> for Error {
fn from(_e: lightning_transaction_sync::TxSyncError) -> Self {
Self::TxSyncFailed
Expand Down
45 changes: 25 additions & 20 deletions src/payment/onchain.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,10 +9,11 @@

use crate::config::Config;
use crate::error::Error;
use crate::logger::{log_error, log_info, FilesystemLogger, Logger};
use crate::logger::{log_info, FilesystemLogger, Logger};
use crate::types::{ChannelManager, Wallet};
use crate::wallet::OnchainSendAmount;

use bitcoin::{Address, Amount, Txid};
use bitcoin::{Address, Txid};

use std::sync::{Arc, RwLock};

Expand DownExpand Up@@ -60,35 +61,39 @@ impl OnchainPayment {

let cur_anchor_reserve_sats =
crate::total_anchor_channels_reserve_sats(&self.channel_manager, &self.config);
let spendable_amount_sats =
self.wallet.get_spendable_amount_sats(cur_anchor_reserve_sats).unwrap_or(0);

if spendable_amount_sats < amount_sats {
log_error!(self.logger,
"Unable to send payment due to insufficient funds. Available: {}sats, Required: {}sats",
spendable_amount_sats, amount_sats
);
return Err(Error::InsufficientFunds);
}

let amount = Amount::from_sat(amount_sats);
self.wallet.send_to_address(address, Some(amount))
let send_amount =
OnchainSendAmount::ExactRetainingReserve { amount_sats, cur_anchor_reserve_sats };
self.wallet.send_to_address(address, send_amount)
}

/// Send an on-chain payment to the given address, draining all the available funds.
/// Send an on-chain payment to the given address, draining the available funds.
///
/// This is useful if you have closed all channels and want to migrate funds to another
/// on-chain wallet.
///
/// Please note that this will **not** retain any on-chain reserves, which might be potentially
/// Please note that if `retain_reserves` is set to `false` this will **not** retain any on-chain reserves, which might be potentially
/// dangerous if you have open Anchor channels for which you can't trust the counterparty to
/// spend the Anchor output after channel closure.
pub fn send_all_to_address(&self, address: &bitcoin::Address) -> Result<Txid, Error> {
/// spend the Anchor output after channel closure. If `retain_reserves` is set to `true`, this
/// will try to send all spendable onchain funds, i.e.,
/// [`BalanceDetails::spendable_onchain_balance_sats`].
///
/// [`BalanceDetails::spendable_onchain_balance_sats`]: crate::balance::BalanceDetails::spendable_onchain_balance_sats
pub fn send_all_to_address(
&self, address: &bitcoin::Address, retain_reserves: bool,
) -> Result<Txid, Error> {
let rt_lock = self.runtime.read().unwrap();
if rt_lock.is_none() {
return Err(Error::NotRunning);
}

self.wallet.send_to_address(address, None)
let send_amount = if retain_reserves {
let cur_anchor_reserve_sats =
crate::total_anchor_channels_reserve_sats(&self.channel_manager, &self.config);
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats }
} else {
OnchainSendAmount::AllDrainingReserve
};

self.wallet.send_to_address(address, send_amount)
}
}
209 changes: 174 additions & 35 deletions src/wallet/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ use lightning_invoice::RawBolt11Invoice;

use bdk_chain::spk_client::{FullScanRequest, SyncRequest};
use bdk_chain::ChainPosition;
use bdk_wallet::{KeychainKind, PersistedWallet, SignOptions, Update};
use bdk_wallet::{Balance, KeychainKind, PersistedWallet, SignOptions, Update};

use bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
use bitcoin::blockdata::locktime::absolute::LockTime;
Expand All@@ -45,6 +45,12 @@ use bitcoin::{
use std::ops::Deref;
use std::sync::{Arc, Mutex};

pub(crate) enum OnchainSendAmount {
ExactRetainingReserve { amount_sats: u64, cur_anchor_reserve_sats: u64 },
AllRetainingReserve { cur_anchor_reserve_sats: u64 },
AllDrainingReserve,
}

pub(crate) mod persist;
pub(crate) mod ser;

Expand DownExpand Up@@ -215,6 +221,12 @@ where
);
}

self.get_balances_inner(balance, total_anchor_channels_reserve_sats)
}

fn get_balances_inner(
&self, balance: Balance, total_anchor_channels_reserve_sats: u64,
) -> Result<(u64, u64), Error> {
let (total, spendable) = (
balance.total().to_sat(),
balance.trusted_spendable().to_sat().saturating_sub(total_anchor_channels_reserve_sats),
Expand All@@ -229,32 +241,95 @@ where
self.get_balances(total_anchor_channels_reserve_sats).map(|(_, s)| s)
}

/// Send funds to the given address.
///
/// If `amount_msat_or_drain` is `None` the wallet will be drained, i.e., all available funds will be
/// spent.
pub(crate) fn send_to_address(
&self, address: &bitcoin::Address, amount_or_drain: Option<Amount>,
&self, address: &bitcoin::Address, send_amount: OnchainSendAmount,
) -> Result<Txid, Error> {
let confirmation_target = ConfirmationTarget::OnchainPayment;
let fee_rate = self.fee_estimator.estimate_fee_rate(confirmation_target);

let tx = {
let mut locked_wallet = self.inner.lock().unwrap();
let mut tx_builder = locked_wallet.build_tx();

if let Some(amount) = amount_or_drain {
tx_builder
.add_recipient(address.script_pubkey(), amount)
.fee_rate(fee_rate)
.enable_rbf();
} else {
tx_builder
.drain_wallet()
.drain_to(address.script_pubkey())
.fee_rate(fee_rate)
.enable_rbf();
}

// Prepare the tx_builder. We properly check the reserve requirements (again) further down.
let tx_builder = match send_amount {
OnchainSendAmount::ExactRetainingReserve { amount_sats, .. } => {
let mut tx_builder = locked_wallet.build_tx();
let amount = Amount::from_sat(amount_sats);
tx_builder
.add_recipient(address.script_pubkey(), amount)
.fee_rate(fee_rate)
.enable_rbf();
tx_builder
},
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats } => {
let change_address_info = locked_wallet.peek_address(KeychainKind::Internal, 0);
let balance = locked_wallet.balance();
let spendable_amount_sats = self
.get_balances_inner(balance, cur_anchor_reserve_sats)
.map(|(_, s)| s)
.unwrap_or(0);
Comment thread
jkczyz marked this conversation as resolved.
let tmp_tx = {
let mut tmp_tx_builder = locked_wallet.build_tx();
tmp_tx_builder
.drain_wallet()
.drain_to(address.script_pubkey())
.add_recipient(
change_address_info.address.script_pubkey(),
Amount::from_sat(cur_anchor_reserve_sats),
)
.fee_rate(fee_rate)
.enable_rbf();
match tmp_tx_builder.finish() {
Ok(psbt) => psbt.unsigned_tx,
Err(err) => {
log_error!(
self.logger,
"Failed to create temporary transaction: {}",
err
);
return Err(err.into());
},
}
};

let estimated_tx_fee = locked_wallet.calculate_fee(&tmp_tx).map_err(|e| {
log_error!(
self.logger,
"Failed to calculate fee of temporary transaction: {}",
e
);
e
})?;
let estimated_spendable_amount = Amount::from_sat(
spendable_amount_sats.saturating_sub(estimated_tx_fee.to_sat()),
);

if estimated_spendable_amount == Amount::ZERO {
log_error!(self.logger,
"Unable to send payment without infringing on Anchor reserves. Available: {}sats, estimated fee required: {}sats.",
spendable_amount_sats,
estimated_tx_fee,
);
return Err(Error::InsufficientFunds);
}

let mut tx_builder = locked_wallet.build_tx();
tx_builder
.add_recipient(address.script_pubkey(), estimated_spendable_amount)
.fee_absolute(estimated_tx_fee)
.enable_rbf();
tx_builder
},
OnchainSendAmount::AllDrainingReserve => {
let mut tx_builder = locked_wallet.build_tx();
tx_builder
.drain_wallet()
.drain_to(address.script_pubkey())
.fee_rate(fee_rate)
.enable_rbf();
tx_builder
},
};

let mut psbt = match tx_builder.finish() {
Ok(psbt) => {
Expand All@@ -267,6 +342,58 @@ where
},
};

// Check the reserve requirements (again) and return an error if they aren't met.
match send_amount {
OnchainSendAmount::ExactRetainingReserve {
amount_sats,
cur_anchor_reserve_sats,
} => {
let balance = locked_wallet.balance();
let spendable_amount_sats = self
.get_balances_inner(balance, cur_anchor_reserve_sats)
.map(|(_, s)| s)
.unwrap_or(0);
let tx_fee_sats = locked_wallet
.calculate_fee(&psbt.unsigned_tx)
.map_err(|e| {
log_error!(
self.logger,
"Failed to calculate fee of candidate transaction: {}",
e
);
e
})?
.to_sat();
if spendable_amount_sats < amount_sats.saturating_add(tx_fee_sats) {
log_error!(self.logger,
"Unable to send payment due to insufficient funds. Available: {}sats, Required: {}sats + {}sats fee",
spendable_amount_sats,
amount_sats,
tx_fee_sats,
);
return Err(Error::InsufficientFunds);
}
},
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats } => {
let balance = locked_wallet.balance();
let spendable_amount_sats = self
.get_balances_inner(balance, cur_anchor_reserve_sats)
.map(|(_, s)| s)
.unwrap_or(0);
let (sent, received) = locked_wallet.sent_and_received(&psbt.unsigned_tx);
let drain_amount = sent - received;
if spendable_amount_sats < drain_amount.to_sat() {
log_error!(self.logger,
"Unable to send payment due to insufficient funds. Available: {}sats, Required: {}",
spendable_amount_sats,
drain_amount,
);
return Err(Error::InsufficientFunds);
}
},
_ => {},
}

match locked_wallet.sign(&mut psbt, SignOptions::default()) {
Ok(finalized) => {
if !finalized {
Expand DownExpand Up@@ -295,21 +422,33 @@ where

let txid = tx.compute_txid();

if let Some(amount) = amount_or_drain {
log_info!(
self.logger,
"Created new transaction {} sending {}sats on-chain to address {}",
txid,
amount.to_sat(),
address
);
} else {
log_info!(
self.logger,
"Created new transaction {} sending all available on-chain funds to address {}",
txid,
address
);
match send_amount {
OnchainSendAmount::ExactRetainingReserve { amount_sats, .. } => {
log_info!(
self.logger,
"Created new transaction {} sending {}sats on-chain to address {}",
txid,
amount_sats,
address
);
},
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats } => {
log_info!(
self.logger,
"Created new transaction {} sending available on-chain funds retaining a reserve of {}sats to address {}",
txid,
cur_anchor_reserve_sats,
address,
);
},
OnchainSendAmount::AllDrainingReserve => {
log_info!(
self.logger,
"Created new transaction {} sending all available on-chain funds to address {}",
txid,
address
);
},
}

Ok(txid)
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' Allow honoring reserve in `send_all_to_address` by tnull · Pull Request #345 · lightningdevkit/ldk-node · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -161,7 +161,7 @@ interface OnchainPayment {
[Throws=NodeError]
Txid send_to_address([ByRef]Address address, u64 amount_sats);
[Throws=NodeError]
Txid send_all_to_address([ByRef]Address address);
Txid send_all_to_address([ByRef]Address address, boolean retain_reserve);
};

interface UnifiedQrPayment {
Expand Down
7 changes: 6 additions & 1 deletion src/chain/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -993,11 +993,16 @@ impl ChainSource {
Err(e) => match e {
esplora_client::Error::Reqwest(err) => {
if err.status() == reqwest::StatusCode::from_u16(400).ok() {
// Ignore 400, as this just means bitcoind already knows the
// Log 400 at lesser level, as this often just means bitcoind already knows the
// transaction.
// FIXME: We can further differentiate here based on the error
// message which will be available with rust-esplora-client 0.7 and
// later.
log_trace!(
logger,
"Failed to broadcast due to HTTP connection error: {}",
err
);
} else {
log_error!(
logger,
Expand Down
14 changes: 12 additions & 2 deletions src/error.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@

use bdk_chain::bitcoin::psbt::ExtractTxError as BdkExtractTxError;
use bdk_chain::local_chain::CannotConnectError as BdkChainConnectionError;
use bdk_chain::tx_graph::CalculateFeeError as BdkChainCalculateFeeError;
use bdk_wallet::error::CreateTxError as BdkCreateTxError;
use bdk_wallet::signer::SignerError as BdkSignerError;

Expand DownExpand Up@@ -196,8 +197,11 @@ impl From<BdkSignerError> for Error {
}

impl From<BdkCreateTxError> for Error {
fn from(_: BdkCreateTxError) -> Self {
Self::OnchainTxCreationFailed
fn from(e: BdkCreateTxError) -> Self {
match e {
BdkCreateTxError::CoinSelection(_) => Self::InsufficientFunds,
_ => Self::OnchainTxCreationFailed,
}
}
}

Expand All@@ -213,6 +217,12 @@ impl From<BdkChainConnectionError> for Error {
}
}

impl From<BdkChainCalculateFeeError> for Error {
fn from(_: BdkChainCalculateFeeError) -> Self {
Self::WalletOperationFailed
}
}

impl From<lightning_transaction_sync::TxSyncError> for Error {
fn from(_e: lightning_transaction_sync::TxSyncError) -> Self {
Self::TxSyncFailed
Expand Down
45 changes: 25 additions & 20 deletions src/payment/onchain.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,10 +9,11 @@

use crate::config::Config;
use crate::error::Error;
use crate::logger::{log_error, log_info, FilesystemLogger, Logger};
use crate::logger::{log_info, FilesystemLogger, Logger};
use crate::types::{ChannelManager, Wallet};
use crate::wallet::OnchainSendAmount;

use bitcoin::{Address, Amount, Txid};
use bitcoin::{Address, Txid};

use std::sync::{Arc, RwLock};

Expand DownExpand Up@@ -60,35 +61,39 @@ impl OnchainPayment {

let cur_anchor_reserve_sats =
crate::total_anchor_channels_reserve_sats(&self.channel_manager, &self.config);
let spendable_amount_sats =
self.wallet.get_spendable_amount_sats(cur_anchor_reserve_sats).unwrap_or(0);

if spendable_amount_sats < amount_sats {
log_error!(self.logger,
"Unable to send payment due to insufficient funds. Available: {}sats, Required: {}sats",
spendable_amount_sats, amount_sats
);
return Err(Error::InsufficientFunds);
}

let amount = Amount::from_sat(amount_sats);
self.wallet.send_to_address(address, Some(amount))
let send_amount =
OnchainSendAmount::ExactRetainingReserve { amount_sats, cur_anchor_reserve_sats };
self.wallet.send_to_address(address, send_amount)
}

/// Send an on-chain payment to the given address, draining all the available funds.
/// Send an on-chain payment to the given address, draining the available funds.
///
/// This is useful if you have closed all channels and want to migrate funds to another
/// on-chain wallet.
///
/// Please note that this will **not** retain any on-chain reserves, which might be potentially
/// Please note that if `retain_reserves` is set to `false` this will **not** retain any on-chain reserves, which might be potentially
/// dangerous if you have open Anchor channels for which you can't trust the counterparty to
/// spend the Anchor output after channel closure.
pub fn send_all_to_address(&self, address: &bitcoin::Address) -> Result<Txid, Error> {
/// spend the Anchor output after channel closure. If `retain_reserves` is set to `true`, this
/// will try to send all spendable onchain funds, i.e.,
/// [`BalanceDetails::spendable_onchain_balance_sats`].
///
/// [`BalanceDetails::spendable_onchain_balance_sats`]: crate::balance::BalanceDetails::spendable_onchain_balance_sats
pub fn send_all_to_address(
&self, address: &bitcoin::Address, retain_reserves: bool,
) -> Result<Txid, Error> {
let rt_lock = self.runtime.read().unwrap();
if rt_lock.is_none() {
return Err(Error::NotRunning);
}

self.wallet.send_to_address(address, None)
let send_amount = if retain_reserves {
let cur_anchor_reserve_sats =
crate::total_anchor_channels_reserve_sats(&self.channel_manager, &self.config);
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats }
} else {
OnchainSendAmount::AllDrainingReserve
};

self.wallet.send_to_address(address, send_amount)
}
}
209 changes: 174 additions & 35 deletions src/wallet/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ use lightning_invoice::RawBolt11Invoice;

use bdk_chain::spk_client::{FullScanRequest, SyncRequest};
use bdk_chain::ChainPosition;
use bdk_wallet::{KeychainKind, PersistedWallet, SignOptions, Update};
use bdk_wallet::{Balance, KeychainKind, PersistedWallet, SignOptions, Update};

use bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
use bitcoin::blockdata::locktime::absolute::LockTime;
Expand All@@ -45,6 +45,12 @@ use bitcoin::{
use std::ops::Deref;
use std::sync::{Arc, Mutex};

pub(crate) enum OnchainSendAmount {
ExactRetainingReserve { amount_sats: u64, cur_anchor_reserve_sats: u64 },
AllRetainingReserve { cur_anchor_reserve_sats: u64 },
AllDrainingReserve,
}

pub(crate) mod persist;
pub(crate) mod ser;

Expand DownExpand Up@@ -215,6 +221,12 @@ where
);
}

self.get_balances_inner(balance, total_anchor_channels_reserve_sats)
}

fn get_balances_inner(
&self, balance: Balance, total_anchor_channels_reserve_sats: u64,
) -> Result<(u64, u64), Error> {
let (total, spendable) = (
balance.total().to_sat(),
balance.trusted_spendable().to_sat().saturating_sub(total_anchor_channels_reserve_sats),
Expand All@@ -229,32 +241,95 @@ where
self.get_balances(total_anchor_channels_reserve_sats).map(|(_, s)| s)
}

/// Send funds to the given address.
///
/// If `amount_msat_or_drain` is `None` the wallet will be drained, i.e., all available funds will be
/// spent.
pub(crate) fn send_to_address(
&self, address: &bitcoin::Address, amount_or_drain: Option<Amount>,
&self, address: &bitcoin::Address, send_amount: OnchainSendAmount,
) -> Result<Txid, Error> {
let confirmation_target = ConfirmationTarget::OnchainPayment;
let fee_rate = self.fee_estimator.estimate_fee_rate(confirmation_target);

let tx = {
let mut locked_wallet = self.inner.lock().unwrap();
let mut tx_builder = locked_wallet.build_tx();

if let Some(amount) = amount_or_drain {
tx_builder
.add_recipient(address.script_pubkey(), amount)
.fee_rate(fee_rate)
.enable_rbf();
} else {
tx_builder
.drain_wallet()
.drain_to(address.script_pubkey())
.fee_rate(fee_rate)
.enable_rbf();
}

// Prepare the tx_builder. We properly check the reserve requirements (again) further down.
let tx_builder = match send_amount {
OnchainSendAmount::ExactRetainingReserve { amount_sats, .. } => {
let mut tx_builder = locked_wallet.build_tx();
let amount = Amount::from_sat(amount_sats);
tx_builder
.add_recipient(address.script_pubkey(), amount)
.fee_rate(fee_rate)
.enable_rbf();
tx_builder
},
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats } => {
let change_address_info = locked_wallet.peek_address(KeychainKind::Internal, 0);
let balance = locked_wallet.balance();
let spendable_amount_sats = self
.get_balances_inner(balance, cur_anchor_reserve_sats)
.map(|(_, s)| s)
.unwrap_or(0);
Comment thread
jkczyz marked this conversation as resolved.
let tmp_tx = {
let mut tmp_tx_builder = locked_wallet.build_tx();
tmp_tx_builder
.drain_wallet()
.drain_to(address.script_pubkey())
.add_recipient(
change_address_info.address.script_pubkey(),
Amount::from_sat(cur_anchor_reserve_sats),
)
.fee_rate(fee_rate)
.enable_rbf();
match tmp_tx_builder.finish() {
Ok(psbt) => psbt.unsigned_tx,
Err(err) => {
log_error!(
self.logger,
"Failed to create temporary transaction: {}",
err
);
return Err(err.into());
},
}
};

let estimated_tx_fee = locked_wallet.calculate_fee(&tmp_tx).map_err(|e| {
log_error!(
self.logger,
"Failed to calculate fee of temporary transaction: {}",
e
);
e
})?;
let estimated_spendable_amount = Amount::from_sat(
spendable_amount_sats.saturating_sub(estimated_tx_fee.to_sat()),
);

if estimated_spendable_amount == Amount::ZERO {
log_error!(self.logger,
"Unable to send payment without infringing on Anchor reserves. Available: {}sats, estimated fee required: {}sats.",
spendable_amount_sats,
estimated_tx_fee,
);
return Err(Error::InsufficientFunds);
}

let mut tx_builder = locked_wallet.build_tx();
tx_builder
.add_recipient(address.script_pubkey(), estimated_spendable_amount)
.fee_absolute(estimated_tx_fee)
.enable_rbf();
tx_builder
},
OnchainSendAmount::AllDrainingReserve => {
let mut tx_builder = locked_wallet.build_tx();
tx_builder
.drain_wallet()
.drain_to(address.script_pubkey())
.fee_rate(fee_rate)
.enable_rbf();
tx_builder
},
};

let mut psbt = match tx_builder.finish() {
Ok(psbt) => {
Expand All@@ -267,6 +342,58 @@ where
},
};

// Check the reserve requirements (again) and return an error if they aren't met.
match send_amount {
OnchainSendAmount::ExactRetainingReserve {
amount_sats,
cur_anchor_reserve_sats,
} => {
let balance = locked_wallet.balance();
let spendable_amount_sats = self
.get_balances_inner(balance, cur_anchor_reserve_sats)
.map(|(_, s)| s)
.unwrap_or(0);
let tx_fee_sats = locked_wallet
.calculate_fee(&psbt.unsigned_tx)
.map_err(|e| {
log_error!(
self.logger,
"Failed to calculate fee of candidate transaction: {}",
e
);
e
})?
.to_sat();
if spendable_amount_sats < amount_sats.saturating_add(tx_fee_sats) {
log_error!(self.logger,
"Unable to send payment due to insufficient funds. Available: {}sats, Required: {}sats + {}sats fee",
spendable_amount_sats,
amount_sats,
tx_fee_sats,
);
return Err(Error::InsufficientFunds);
}
},
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats } => {
let balance = locked_wallet.balance();
let spendable_amount_sats = self
.get_balances_inner(balance, cur_anchor_reserve_sats)
.map(|(_, s)| s)
.unwrap_or(0);
let (sent, received) = locked_wallet.sent_and_received(&psbt.unsigned_tx);
let drain_amount = sent - received;
if spendable_amount_sats < drain_amount.to_sat() {
log_error!(self.logger,
"Unable to send payment due to insufficient funds. Available: {}sats, Required: {}",
spendable_amount_sats,
drain_amount,
);
return Err(Error::InsufficientFunds);
}
},
_ => {},
}

match locked_wallet.sign(&mut psbt, SignOptions::default()) {
Ok(finalized) => {
if !finalized {
Expand DownExpand Up@@ -295,21 +422,33 @@ where

let txid = tx.compute_txid();

if let Some(amount) = amount_or_drain {
log_info!(
self.logger,
"Created new transaction {} sending {}sats on-chain to address {}",
txid,
amount.to_sat(),
address
);
} else {
log_info!(
self.logger,
"Created new transaction {} sending all available on-chain funds to address {}",
txid,
address
);
match send_amount {
OnchainSendAmount::ExactRetainingReserve { amount_sats, .. } => {
log_info!(
self.logger,
"Created new transaction {} sending {}sats on-chain to address {}",
txid,
amount_sats,
address
);
},
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats } => {
log_info!(
self.logger,
"Created new transaction {} sending available on-chain funds retaining a reserve of {}sats to address {}",
txid,
cur_anchor_reserve_sats,
address,
);
},
OnchainSendAmount::AllDrainingReserve => {
log_info!(
self.logger,
"Created new transaction {} sending all available on-chain funds to address {}",
txid,
address
);
},
}

Ok(txid)
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Allow honoring reserve in `send_all_to_address` by tnull · Pull Request #345 · lightningdevkit/ldk-node · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -161,7 +161,7 @@ interface OnchainPayment {
[Throws=NodeError]
Txid send_to_address([ByRef]Address address, u64 amount_sats);
[Throws=NodeError]
Txid send_all_to_address([ByRef]Address address);
Txid send_all_to_address([ByRef]Address address, boolean retain_reserve);
};

interface UnifiedQrPayment {
Expand Down
7 changes: 6 additions & 1 deletion src/chain/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -993,11 +993,16 @@ impl ChainSource {
Err(e) => match e {
esplora_client::Error::Reqwest(err) => {
if err.status() == reqwest::StatusCode::from_u16(400).ok() {
// Ignore 400, as this just means bitcoind already knows the
// Log 400 at lesser level, as this often just means bitcoind already knows the
// transaction.
// FIXME: We can further differentiate here based on the error
// message which will be available with rust-esplora-client 0.7 and
// later.
log_trace!(
logger,
"Failed to broadcast due to HTTP connection error: {}",
err
);
} else {
log_error!(
logger,
Expand Down
14 changes: 12 additions & 2 deletions src/error.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@

use bdk_chain::bitcoin::psbt::ExtractTxError as BdkExtractTxError;
use bdk_chain::local_chain::CannotConnectError as BdkChainConnectionError;
use bdk_chain::tx_graph::CalculateFeeError as BdkChainCalculateFeeError;
use bdk_wallet::error::CreateTxError as BdkCreateTxError;
use bdk_wallet::signer::SignerError as BdkSignerError;

Expand DownExpand Up@@ -196,8 +197,11 @@ impl From<BdkSignerError> for Error {
}

impl From<BdkCreateTxError> for Error {
fn from(_: BdkCreateTxError) -> Self {
Self::OnchainTxCreationFailed
fn from(e: BdkCreateTxError) -> Self {
match e {
BdkCreateTxError::CoinSelection(_) => Self::InsufficientFunds,
_ => Self::OnchainTxCreationFailed,
}
}
}

Expand All@@ -213,6 +217,12 @@ impl From<BdkChainConnectionError> for Error {
}
}

impl From<BdkChainCalculateFeeError> for Error {
fn from(_: BdkChainCalculateFeeError) -> Self {
Self::WalletOperationFailed
}
}

impl From<lightning_transaction_sync::TxSyncError> for Error {
fn from(_e: lightning_transaction_sync::TxSyncError) -> Self {
Self::TxSyncFailed
Expand Down
45 changes: 25 additions & 20 deletions src/payment/onchain.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,10 +9,11 @@

use crate::config::Config;
use crate::error::Error;
use crate::logger::{log_error, log_info, FilesystemLogger, Logger};
use crate::logger::{log_info, FilesystemLogger, Logger};
use crate::types::{ChannelManager, Wallet};
use crate::wallet::OnchainSendAmount;

use bitcoin::{Address, Amount, Txid};
use bitcoin::{Address, Txid};

use std::sync::{Arc, RwLock};

Expand DownExpand Up@@ -60,35 +61,39 @@ impl OnchainPayment {

let cur_anchor_reserve_sats =
crate::total_anchor_channels_reserve_sats(&self.channel_manager, &self.config);
let spendable_amount_sats =
self.wallet.get_spendable_amount_sats(cur_anchor_reserve_sats).unwrap_or(0);

if spendable_amount_sats < amount_sats {
log_error!(self.logger,
"Unable to send payment due to insufficient funds. Available: {}sats, Required: {}sats",
spendable_amount_sats, amount_sats
);
return Err(Error::InsufficientFunds);
}

let amount = Amount::from_sat(amount_sats);
self.wallet.send_to_address(address, Some(amount))
let send_amount =
OnchainSendAmount::ExactRetainingReserve { amount_sats, cur_anchor_reserve_sats };
self.wallet.send_to_address(address, send_amount)
}

/// Send an on-chain payment to the given address, draining all the available funds.
/// Send an on-chain payment to the given address, draining the available funds.
///
/// This is useful if you have closed all channels and want to migrate funds to another
/// on-chain wallet.
///
/// Please note that this will **not** retain any on-chain reserves, which might be potentially
/// Please note that if `retain_reserves` is set to `false` this will **not** retain any on-chain reserves, which might be potentially
/// dangerous if you have open Anchor channels for which you can't trust the counterparty to
/// spend the Anchor output after channel closure.
pub fn send_all_to_address(&self, address: &bitcoin::Address) -> Result<Txid, Error> {
/// spend the Anchor output after channel closure. If `retain_reserves` is set to `true`, this
/// will try to send all spendable onchain funds, i.e.,
/// [`BalanceDetails::spendable_onchain_balance_sats`].
///
/// [`BalanceDetails::spendable_onchain_balance_sats`]: crate::balance::BalanceDetails::spendable_onchain_balance_sats
pub fn send_all_to_address(
&self, address: &bitcoin::Address, retain_reserves: bool,
) -> Result<Txid, Error> {
let rt_lock = self.runtime.read().unwrap();
if rt_lock.is_none() {
return Err(Error::NotRunning);
}

self.wallet.send_to_address(address, None)
let send_amount = if retain_reserves {
let cur_anchor_reserve_sats =
crate::total_anchor_channels_reserve_sats(&self.channel_manager, &self.config);
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats }
} else {
OnchainSendAmount::AllDrainingReserve
};

self.wallet.send_to_address(address, send_amount)
}
}
209 changes: 174 additions & 35 deletions src/wallet/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ use lightning_invoice::RawBolt11Invoice;

use bdk_chain::spk_client::{FullScanRequest, SyncRequest};
use bdk_chain::ChainPosition;
use bdk_wallet::{KeychainKind, PersistedWallet, SignOptions, Update};
use bdk_wallet::{Balance, KeychainKind, PersistedWallet, SignOptions, Update};

use bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
use bitcoin::blockdata::locktime::absolute::LockTime;
Expand All@@ -45,6 +45,12 @@ use bitcoin::{
use std::ops::Deref;
use std::sync::{Arc, Mutex};

pub(crate) enum OnchainSendAmount {
ExactRetainingReserve { amount_sats: u64, cur_anchor_reserve_sats: u64 },
AllRetainingReserve { cur_anchor_reserve_sats: u64 },
AllDrainingReserve,
}

pub(crate) mod persist;
pub(crate) mod ser;

Expand DownExpand Up@@ -215,6 +221,12 @@ where
);
}

self.get_balances_inner(balance, total_anchor_channels_reserve_sats)
}

fn get_balances_inner(
&self, balance: Balance, total_anchor_channels_reserve_sats: u64,
) -> Result<(u64, u64), Error> {
let (total, spendable) = (
balance.total().to_sat(),
balance.trusted_spendable().to_sat().saturating_sub(total_anchor_channels_reserve_sats),
Expand All@@ -229,32 +241,95 @@ where
self.get_balances(total_anchor_channels_reserve_sats).map(|(_, s)| s)
}

/// Send funds to the given address.
///
/// If `amount_msat_or_drain` is `None` the wallet will be drained, i.e., all available funds will be
/// spent.
pub(crate) fn send_to_address(
&self, address: &bitcoin::Address, amount_or_drain: Option<Amount>,
&self, address: &bitcoin::Address, send_amount: OnchainSendAmount,
) -> Result<Txid, Error> {
let confirmation_target = ConfirmationTarget::OnchainPayment;
let fee_rate = self.fee_estimator.estimate_fee_rate(confirmation_target);

let tx = {
let mut locked_wallet = self.inner.lock().unwrap();
let mut tx_builder = locked_wallet.build_tx();

if let Some(amount) = amount_or_drain {
tx_builder
.add_recipient(address.script_pubkey(), amount)
.fee_rate(fee_rate)
.enable_rbf();
} else {
tx_builder
.drain_wallet()
.drain_to(address.script_pubkey())
.fee_rate(fee_rate)
.enable_rbf();
}

// Prepare the tx_builder. We properly check the reserve requirements (again) further down.
let tx_builder = match send_amount {
OnchainSendAmount::ExactRetainingReserve { amount_sats, .. } => {
let mut tx_builder = locked_wallet.build_tx();
let amount = Amount::from_sat(amount_sats);
tx_builder
.add_recipient(address.script_pubkey(), amount)
.fee_rate(fee_rate)
.enable_rbf();
tx_builder
},
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats } => {
let change_address_info = locked_wallet.peek_address(KeychainKind::Internal, 0);
let balance = locked_wallet.balance();
let spendable_amount_sats = self
.get_balances_inner(balance, cur_anchor_reserve_sats)
.map(|(_, s)| s)
.unwrap_or(0);
Comment thread
jkczyz marked this conversation as resolved.
let tmp_tx = {
let mut tmp_tx_builder = locked_wallet.build_tx();
tmp_tx_builder
.drain_wallet()
.drain_to(address.script_pubkey())
.add_recipient(
change_address_info.address.script_pubkey(),
Amount::from_sat(cur_anchor_reserve_sats),
)
.fee_rate(fee_rate)
.enable_rbf();
match tmp_tx_builder.finish() {
Ok(psbt) => psbt.unsigned_tx,
Err(err) => {
log_error!(
self.logger,
"Failed to create temporary transaction: {}",
err
);
return Err(err.into());
},
}
};

let estimated_tx_fee = locked_wallet.calculate_fee(&tmp_tx).map_err(|e| {
log_error!(
self.logger,
"Failed to calculate fee of temporary transaction: {}",
e
);
e
})?;
let estimated_spendable_amount = Amount::from_sat(
spendable_amount_sats.saturating_sub(estimated_tx_fee.to_sat()),
);

if estimated_spendable_amount == Amount::ZERO {
log_error!(self.logger,
"Unable to send payment without infringing on Anchor reserves. Available: {}sats, estimated fee required: {}sats.",
spendable_amount_sats,
estimated_tx_fee,
);
return Err(Error::InsufficientFunds);
}

let mut tx_builder = locked_wallet.build_tx();
tx_builder
.add_recipient(address.script_pubkey(), estimated_spendable_amount)
.fee_absolute(estimated_tx_fee)
.enable_rbf();
tx_builder
},
OnchainSendAmount::AllDrainingReserve => {
let mut tx_builder = locked_wallet.build_tx();
tx_builder
.drain_wallet()
.drain_to(address.script_pubkey())
.fee_rate(fee_rate)
.enable_rbf();
tx_builder
},
};

let mut psbt = match tx_builder.finish() {
Ok(psbt) => {
Expand All@@ -267,6 +342,58 @@ where
},
};

// Check the reserve requirements (again) and return an error if they aren't met.
match send_amount {
OnchainSendAmount::ExactRetainingReserve {
amount_sats,
cur_anchor_reserve_sats,
} => {
let balance = locked_wallet.balance();
let spendable_amount_sats = self
.get_balances_inner(balance, cur_anchor_reserve_sats)
.map(|(_, s)| s)
.unwrap_or(0);
let tx_fee_sats = locked_wallet
.calculate_fee(&psbt.unsigned_tx)
.map_err(|e| {
log_error!(
self.logger,
"Failed to calculate fee of candidate transaction: {}",
e
);
e
})?
.to_sat();
if spendable_amount_sats < amount_sats.saturating_add(tx_fee_sats) {
log_error!(self.logger,
"Unable to send payment due to insufficient funds. Available: {}sats, Required: {}sats + {}sats fee",
spendable_amount_sats,
amount_sats,
tx_fee_sats,
);
return Err(Error::InsufficientFunds);
}
},
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats } => {
let balance = locked_wallet.balance();
let spendable_amount_sats = self
.get_balances_inner(balance, cur_anchor_reserve_sats)
.map(|(_, s)| s)
.unwrap_or(0);
let (sent, received) = locked_wallet.sent_and_received(&psbt.unsigned_tx);
let drain_amount = sent - received;
if spendable_amount_sats < drain_amount.to_sat() {
log_error!(self.logger,
"Unable to send payment due to insufficient funds. Available: {}sats, Required: {}",
spendable_amount_sats,
drain_amount,
);
return Err(Error::InsufficientFunds);
}
},
_ => {},
}

match locked_wallet.sign(&mut psbt, SignOptions::default()) {
Ok(finalized) => {
if !finalized {
Expand DownExpand Up@@ -295,21 +422,33 @@ where

let txid = tx.compute_txid();

if let Some(amount) = amount_or_drain {
log_info!(
self.logger,
"Created new transaction {} sending {}sats on-chain to address {}",
txid,
amount.to_sat(),
address
);
} else {
log_info!(
self.logger,
"Created new transaction {} sending all available on-chain funds to address {}",
txid,
address
);
match send_amount {
OnchainSendAmount::ExactRetainingReserve { amount_sats, .. } => {
log_info!(
self.logger,
"Created new transaction {} sending {}sats on-chain to address {}",
txid,
amount_sats,
address
);
},
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats } => {
log_info!(
self.logger,
"Created new transaction {} sending available on-chain funds retaining a reserve of {}sats to address {}",
txid,
cur_anchor_reserve_sats,
address,
);
},
OnchainSendAmount::AllDrainingReserve => {
log_info!(
self.logger,
"Created new transaction {} sending all available on-chain funds to address {}",
txid,
address
);
},
}

Ok(txid)
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Allow honoring reserve in `send_all_to_address` by tnull · Pull Request #345 · lightningdevkit/ldk-node · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -161,7 +161,7 @@ interface OnchainPayment {
[Throws=NodeError]
Txid send_to_address([ByRef]Address address, u64 amount_sats);
[Throws=NodeError]
Txid send_all_to_address([ByRef]Address address);
Txid send_all_to_address([ByRef]Address address, boolean retain_reserve);
};

interface UnifiedQrPayment {
Expand Down
7 changes: 6 additions & 1 deletion src/chain/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -993,11 +993,16 @@ impl ChainSource {
Err(e) => match e {
esplora_client::Error::Reqwest(err) => {
if err.status() == reqwest::StatusCode::from_u16(400).ok() {
// Ignore 400, as this just means bitcoind already knows the
// Log 400 at lesser level, as this often just means bitcoind already knows the
// transaction.
// FIXME: We can further differentiate here based on the error
// message which will be available with rust-esplora-client 0.7 and
// later.
log_trace!(
logger,
"Failed to broadcast due to HTTP connection error: {}",
err
);
} else {
log_error!(
logger,
Expand Down
14 changes: 12 additions & 2 deletions src/error.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@

use bdk_chain::bitcoin::psbt::ExtractTxError as BdkExtractTxError;
use bdk_chain::local_chain::CannotConnectError as BdkChainConnectionError;
use bdk_chain::tx_graph::CalculateFeeError as BdkChainCalculateFeeError;
use bdk_wallet::error::CreateTxError as BdkCreateTxError;
use bdk_wallet::signer::SignerError as BdkSignerError;

Expand DownExpand Up@@ -196,8 +197,11 @@ impl From<BdkSignerError> for Error {
}

impl From<BdkCreateTxError> for Error {
fn from(_: BdkCreateTxError) -> Self {
Self::OnchainTxCreationFailed
fn from(e: BdkCreateTxError) -> Self {
match e {
BdkCreateTxError::CoinSelection(_) => Self::InsufficientFunds,
_ => Self::OnchainTxCreationFailed,
}
}
}

Expand All@@ -213,6 +217,12 @@ impl From<BdkChainConnectionError> for Error {
}
}

impl From<BdkChainCalculateFeeError> for Error {
fn from(_: BdkChainCalculateFeeError) -> Self {
Self::WalletOperationFailed
}
}

impl From<lightning_transaction_sync::TxSyncError> for Error {
fn from(_e: lightning_transaction_sync::TxSyncError) -> Self {
Self::TxSyncFailed
Expand Down
45 changes: 25 additions & 20 deletions src/payment/onchain.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,10 +9,11 @@

use crate::config::Config;
use crate::error::Error;
use crate::logger::{log_error, log_info, FilesystemLogger, Logger};
use crate::logger::{log_info, FilesystemLogger, Logger};
use crate::types::{ChannelManager, Wallet};
use crate::wallet::OnchainSendAmount;

use bitcoin::{Address, Amount, Txid};
use bitcoin::{Address, Txid};

use std::sync::{Arc, RwLock};

Expand DownExpand Up@@ -60,35 +61,39 @@ impl OnchainPayment {

let cur_anchor_reserve_sats =
crate::total_anchor_channels_reserve_sats(&self.channel_manager, &self.config);
let spendable_amount_sats =
self.wallet.get_spendable_amount_sats(cur_anchor_reserve_sats).unwrap_or(0);

if spendable_amount_sats < amount_sats {
log_error!(self.logger,
"Unable to send payment due to insufficient funds. Available: {}sats, Required: {}sats",
spendable_amount_sats, amount_sats
);
return Err(Error::InsufficientFunds);
}

let amount = Amount::from_sat(amount_sats);
self.wallet.send_to_address(address, Some(amount))
let send_amount =
OnchainSendAmount::ExactRetainingReserve { amount_sats, cur_anchor_reserve_sats };
self.wallet.send_to_address(address, send_amount)
}

/// Send an on-chain payment to the given address, draining all the available funds.
/// Send an on-chain payment to the given address, draining the available funds.
///
/// This is useful if you have closed all channels and want to migrate funds to another
/// on-chain wallet.
///
/// Please note that this will **not** retain any on-chain reserves, which might be potentially
/// Please note that if `retain_reserves` is set to `false` this will **not** retain any on-chain reserves, which might be potentially
/// dangerous if you have open Anchor channels for which you can't trust the counterparty to
/// spend the Anchor output after channel closure.
pub fn send_all_to_address(&self, address: &bitcoin::Address) -> Result<Txid, Error> {
/// spend the Anchor output after channel closure. If `retain_reserves` is set to `true`, this
/// will try to send all spendable onchain funds, i.e.,
/// [`BalanceDetails::spendable_onchain_balance_sats`].
///
/// [`BalanceDetails::spendable_onchain_balance_sats`]: crate::balance::BalanceDetails::spendable_onchain_balance_sats
pub fn send_all_to_address(
&self, address: &bitcoin::Address, retain_reserves: bool,
) -> Result<Txid, Error> {
let rt_lock = self.runtime.read().unwrap();
if rt_lock.is_none() {
return Err(Error::NotRunning);
}

self.wallet.send_to_address(address, None)
let send_amount = if retain_reserves {
let cur_anchor_reserve_sats =
crate::total_anchor_channels_reserve_sats(&self.channel_manager, &self.config);
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats }
} else {
OnchainSendAmount::AllDrainingReserve
};

self.wallet.send_to_address(address, send_amount)
}
}
209 changes: 174 additions & 35 deletions src/wallet/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ use lightning_invoice::RawBolt11Invoice;

use bdk_chain::spk_client::{FullScanRequest, SyncRequest};
use bdk_chain::ChainPosition;
use bdk_wallet::{KeychainKind, PersistedWallet, SignOptions, Update};
use bdk_wallet::{Balance, KeychainKind, PersistedWallet, SignOptions, Update};

use bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
use bitcoin::blockdata::locktime::absolute::LockTime;
Expand All@@ -45,6 +45,12 @@ use bitcoin::{
use std::ops::Deref;
use std::sync::{Arc, Mutex};

pub(crate) enum OnchainSendAmount {
ExactRetainingReserve { amount_sats: u64, cur_anchor_reserve_sats: u64 },
AllRetainingReserve { cur_anchor_reserve_sats: u64 },
AllDrainingReserve,
}

pub(crate) mod persist;
pub(crate) mod ser;

Expand DownExpand Up@@ -215,6 +221,12 @@ where
);
}

self.get_balances_inner(balance, total_anchor_channels_reserve_sats)
}

fn get_balances_inner(
&self, balance: Balance, total_anchor_channels_reserve_sats: u64,
) -> Result<(u64, u64), Error> {
let (total, spendable) = (
balance.total().to_sat(),
balance.trusted_spendable().to_sat().saturating_sub(total_anchor_channels_reserve_sats),
Expand All@@ -229,32 +241,95 @@ where
self.get_balances(total_anchor_channels_reserve_sats).map(|(_, s)| s)
}

/// Send funds to the given address.
///
/// If `amount_msat_or_drain` is `None` the wallet will be drained, i.e., all available funds will be
/// spent.
pub(crate) fn send_to_address(
&self, address: &bitcoin::Address, amount_or_drain: Option<Amount>,
&self, address: &bitcoin::Address, send_amount: OnchainSendAmount,
) -> Result<Txid, Error> {
let confirmation_target = ConfirmationTarget::OnchainPayment;
let fee_rate = self.fee_estimator.estimate_fee_rate(confirmation_target);

let tx = {
let mut locked_wallet = self.inner.lock().unwrap();
let mut tx_builder = locked_wallet.build_tx();

if let Some(amount) = amount_or_drain {
tx_builder
.add_recipient(address.script_pubkey(), amount)
.fee_rate(fee_rate)
.enable_rbf();
} else {
tx_builder
.drain_wallet()
.drain_to(address.script_pubkey())
.fee_rate(fee_rate)
.enable_rbf();
}

// Prepare the tx_builder. We properly check the reserve requirements (again) further down.
let tx_builder = match send_amount {
OnchainSendAmount::ExactRetainingReserve { amount_sats, .. } => {
let mut tx_builder = locked_wallet.build_tx();
let amount = Amount::from_sat(amount_sats);
tx_builder
.add_recipient(address.script_pubkey(), amount)
.fee_rate(fee_rate)
.enable_rbf();
tx_builder
},
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats } => {
let change_address_info = locked_wallet.peek_address(KeychainKind::Internal, 0);
let balance = locked_wallet.balance();
let spendable_amount_sats = self
.get_balances_inner(balance, cur_anchor_reserve_sats)
.map(|(_, s)| s)
.unwrap_or(0);
Comment thread
jkczyz marked this conversation as resolved.
let tmp_tx = {
let mut tmp_tx_builder = locked_wallet.build_tx();
tmp_tx_builder
.drain_wallet()
.drain_to(address.script_pubkey())
.add_recipient(
change_address_info.address.script_pubkey(),
Amount::from_sat(cur_anchor_reserve_sats),
)
.fee_rate(fee_rate)
.enable_rbf();
match tmp_tx_builder.finish() {
Ok(psbt) => psbt.unsigned_tx,
Err(err) => {
log_error!(
self.logger,
"Failed to create temporary transaction: {}",
err
);
return Err(err.into());
},
}
};

let estimated_tx_fee = locked_wallet.calculate_fee(&tmp_tx).map_err(|e| {
log_error!(
self.logger,
"Failed to calculate fee of temporary transaction: {}",
e
);
e
})?;
let estimated_spendable_amount = Amount::from_sat(
spendable_amount_sats.saturating_sub(estimated_tx_fee.to_sat()),
);

if estimated_spendable_amount == Amount::ZERO {
log_error!(self.logger,
"Unable to send payment without infringing on Anchor reserves. Available: {}sats, estimated fee required: {}sats.",
spendable_amount_sats,
estimated_tx_fee,
);
return Err(Error::InsufficientFunds);
}

let mut tx_builder = locked_wallet.build_tx();
tx_builder
.add_recipient(address.script_pubkey(), estimated_spendable_amount)
.fee_absolute(estimated_tx_fee)
.enable_rbf();
tx_builder
},
OnchainSendAmount::AllDrainingReserve => {
let mut tx_builder = locked_wallet.build_tx();
tx_builder
.drain_wallet()
.drain_to(address.script_pubkey())
.fee_rate(fee_rate)
.enable_rbf();
tx_builder
},
};

let mut psbt = match tx_builder.finish() {
Ok(psbt) => {
Expand All@@ -267,6 +342,58 @@ where
},
};

// Check the reserve requirements (again) and return an error if they aren't met.
match send_amount {
OnchainSendAmount::ExactRetainingReserve {
amount_sats,
cur_anchor_reserve_sats,
} => {
let balance = locked_wallet.balance();
let spendable_amount_sats = self
.get_balances_inner(balance, cur_anchor_reserve_sats)
.map(|(_, s)| s)
.unwrap_or(0);
let tx_fee_sats = locked_wallet
.calculate_fee(&psbt.unsigned_tx)
.map_err(|e| {
log_error!(
self.logger,
"Failed to calculate fee of candidate transaction: {}",
e
);
e
})?
.to_sat();
if spendable_amount_sats < amount_sats.saturating_add(tx_fee_sats) {
log_error!(self.logger,
"Unable to send payment due to insufficient funds. Available: {}sats, Required: {}sats + {}sats fee",
spendable_amount_sats,
amount_sats,
tx_fee_sats,
);
return Err(Error::InsufficientFunds);
}
},
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats } => {
let balance = locked_wallet.balance();
let spendable_amount_sats = self
.get_balances_inner(balance, cur_anchor_reserve_sats)
.map(|(_, s)| s)
.unwrap_or(0);
let (sent, received) = locked_wallet.sent_and_received(&psbt.unsigned_tx);
let drain_amount = sent - received;
if spendable_amount_sats < drain_amount.to_sat() {
log_error!(self.logger,
"Unable to send payment due to insufficient funds. Available: {}sats, Required: {}",
spendable_amount_sats,
drain_amount,
);
return Err(Error::InsufficientFunds);
}
},
_ => {},
}

match locked_wallet.sign(&mut psbt, SignOptions::default()) {
Ok(finalized) => {
if !finalized {
Expand DownExpand Up@@ -295,21 +422,33 @@ where

let txid = tx.compute_txid();

if let Some(amount) = amount_or_drain {
log_info!(
self.logger,
"Created new transaction {} sending {}sats on-chain to address {}",
txid,
amount.to_sat(),
address
);
} else {
log_info!(
self.logger,
"Created new transaction {} sending all available on-chain funds to address {}",
txid,
address
);
match send_amount {
OnchainSendAmount::ExactRetainingReserve { amount_sats, .. } => {
log_info!(
self.logger,
"Created new transaction {} sending {}sats on-chain to address {}",
txid,
amount_sats,
address
);
},
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats } => {
log_info!(
self.logger,
"Created new transaction {} sending available on-chain funds retaining a reserve of {}sats to address {}",
txid,
cur_anchor_reserve_sats,
address,
);
},
OnchainSendAmount::AllDrainingReserve => {
log_info!(
self.logger,
"Created new transaction {} sending all available on-chain funds to address {}",
txid,
address
);
},
}

Ok(txid)
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); Allow honoring reserve in `send_all_to_address` by tnull · Pull Request #345 · lightningdevkit/ldk-node · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -161,7 +161,7 @@ interface OnchainPayment {
[Throws=NodeError]
Txid send_to_address([ByRef]Address address, u64 amount_sats);
[Throws=NodeError]
Txid send_all_to_address([ByRef]Address address);
Txid send_all_to_address([ByRef]Address address, boolean retain_reserve);
};

interface UnifiedQrPayment {
Expand Down
7 changes: 6 additions & 1 deletion src/chain/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -993,11 +993,16 @@ impl ChainSource {
Err(e) => match e {
esplora_client::Error::Reqwest(err) => {
if err.status() == reqwest::StatusCode::from_u16(400).ok() {
// Ignore 400, as this just means bitcoind already knows the
// Log 400 at lesser level, as this often just means bitcoind already knows the
// transaction.
// FIXME: We can further differentiate here based on the error
// message which will be available with rust-esplora-client 0.7 and
// later.
log_trace!(
logger,
"Failed to broadcast due to HTTP connection error: {}",
err
);
} else {
log_error!(
logger,
Expand Down
14 changes: 12 additions & 2 deletions src/error.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,6 +7,7 @@

use bdk_chain::bitcoin::psbt::ExtractTxError as BdkExtractTxError;
use bdk_chain::local_chain::CannotConnectError as BdkChainConnectionError;
use bdk_chain::tx_graph::CalculateFeeError as BdkChainCalculateFeeError;
use bdk_wallet::error::CreateTxError as BdkCreateTxError;
use bdk_wallet::signer::SignerError as BdkSignerError;

Expand DownExpand Up@@ -196,8 +197,11 @@ impl From<BdkSignerError> for Error {
}

impl From<BdkCreateTxError> for Error {
fn from(_: BdkCreateTxError) -> Self {
Self::OnchainTxCreationFailed
fn from(e: BdkCreateTxError) -> Self {
match e {
BdkCreateTxError::CoinSelection(_) => Self::InsufficientFunds,
_ => Self::OnchainTxCreationFailed,
}
}
}

Expand All@@ -213,6 +217,12 @@ impl From<BdkChainConnectionError> for Error {
}
}

impl From<BdkChainCalculateFeeError> for Error {
fn from(_: BdkChainCalculateFeeError) -> Self {
Self::WalletOperationFailed
}
}

impl From<lightning_transaction_sync::TxSyncError> for Error {
fn from(_e: lightning_transaction_sync::TxSyncError) -> Self {
Self::TxSyncFailed
Expand Down
45 changes: 25 additions & 20 deletions src/payment/onchain.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,10 +9,11 @@

use crate::config::Config;
use crate::error::Error;
use crate::logger::{log_error, log_info, FilesystemLogger, Logger};
use crate::logger::{log_info, FilesystemLogger, Logger};
use crate::types::{ChannelManager, Wallet};
use crate::wallet::OnchainSendAmount;

use bitcoin::{Address, Amount, Txid};
use bitcoin::{Address, Txid};

use std::sync::{Arc, RwLock};

Expand DownExpand Up@@ -60,35 +61,39 @@ impl OnchainPayment {

let cur_anchor_reserve_sats =
crate::total_anchor_channels_reserve_sats(&self.channel_manager, &self.config);
let spendable_amount_sats =
self.wallet.get_spendable_amount_sats(cur_anchor_reserve_sats).unwrap_or(0);

if spendable_amount_sats < amount_sats {
log_error!(self.logger,
"Unable to send payment due to insufficient funds. Available: {}sats, Required: {}sats",
spendable_amount_sats, amount_sats
);
return Err(Error::InsufficientFunds);
}

let amount = Amount::from_sat(amount_sats);
self.wallet.send_to_address(address, Some(amount))
let send_amount =
OnchainSendAmount::ExactRetainingReserve { amount_sats, cur_anchor_reserve_sats };
self.wallet.send_to_address(address, send_amount)
}

/// Send an on-chain payment to the given address, draining all the available funds.
/// Send an on-chain payment to the given address, draining the available funds.
///
/// This is useful if you have closed all channels and want to migrate funds to another
/// on-chain wallet.
///
/// Please note that this will **not** retain any on-chain reserves, which might be potentially
/// Please note that if `retain_reserves` is set to `false` this will **not** retain any on-chain reserves, which might be potentially
/// dangerous if you have open Anchor channels for which you can't trust the counterparty to
/// spend the Anchor output after channel closure.
pub fn send_all_to_address(&self, address: &bitcoin::Address) -> Result<Txid, Error> {
/// spend the Anchor output after channel closure. If `retain_reserves` is set to `true`, this
/// will try to send all spendable onchain funds, i.e.,
/// [`BalanceDetails::spendable_onchain_balance_sats`].
///
/// [`BalanceDetails::spendable_onchain_balance_sats`]: crate::balance::BalanceDetails::spendable_onchain_balance_sats
pub fn send_all_to_address(
&self, address: &bitcoin::Address, retain_reserves: bool,
) -> Result<Txid, Error> {
let rt_lock = self.runtime.read().unwrap();
if rt_lock.is_none() {
return Err(Error::NotRunning);
}

self.wallet.send_to_address(address, None)
let send_amount = if retain_reserves {
let cur_anchor_reserve_sats =
crate::total_anchor_channels_reserve_sats(&self.channel_manager, &self.config);
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats }
} else {
OnchainSendAmount::AllDrainingReserve
};

self.wallet.send_to_address(address, send_amount)
}
}
209 changes: 174 additions & 35 deletions src/wallet/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ use lightning_invoice::RawBolt11Invoice;

use bdk_chain::spk_client::{FullScanRequest, SyncRequest};
use bdk_chain::ChainPosition;
use bdk_wallet::{KeychainKind, PersistedWallet, SignOptions, Update};
use bdk_wallet::{Balance, KeychainKind, PersistedWallet, SignOptions, Update};

use bitcoin::blockdata::constants::WITNESS_SCALE_FACTOR;
use bitcoin::blockdata::locktime::absolute::LockTime;
Expand All@@ -45,6 +45,12 @@ use bitcoin::{
use std::ops::Deref;
use std::sync::{Arc, Mutex};

pub(crate) enum OnchainSendAmount {
ExactRetainingReserve { amount_sats: u64, cur_anchor_reserve_sats: u64 },
AllRetainingReserve { cur_anchor_reserve_sats: u64 },
AllDrainingReserve,
}

pub(crate) mod persist;
pub(crate) mod ser;

Expand DownExpand Up@@ -215,6 +221,12 @@ where
);
}

self.get_balances_inner(balance, total_anchor_channels_reserve_sats)
}

fn get_balances_inner(
&self, balance: Balance, total_anchor_channels_reserve_sats: u64,
) -> Result<(u64, u64), Error> {
let (total, spendable) = (
balance.total().to_sat(),
balance.trusted_spendable().to_sat().saturating_sub(total_anchor_channels_reserve_sats),
Expand All@@ -229,32 +241,95 @@ where
self.get_balances(total_anchor_channels_reserve_sats).map(|(_, s)| s)
}

/// Send funds to the given address.
///
/// If `amount_msat_or_drain` is `None` the wallet will be drained, i.e., all available funds will be
/// spent.
pub(crate) fn send_to_address(
&self, address: &bitcoin::Address, amount_or_drain: Option<Amount>,
&self, address: &bitcoin::Address, send_amount: OnchainSendAmount,
) -> Result<Txid, Error> {
let confirmation_target = ConfirmationTarget::OnchainPayment;
let fee_rate = self.fee_estimator.estimate_fee_rate(confirmation_target);

let tx = {
let mut locked_wallet = self.inner.lock().unwrap();
let mut tx_builder = locked_wallet.build_tx();

if let Some(amount) = amount_or_drain {
tx_builder
.add_recipient(address.script_pubkey(), amount)
.fee_rate(fee_rate)
.enable_rbf();
} else {
tx_builder
.drain_wallet()
.drain_to(address.script_pubkey())
.fee_rate(fee_rate)
.enable_rbf();
}

// Prepare the tx_builder. We properly check the reserve requirements (again) further down.
let tx_builder = match send_amount {
OnchainSendAmount::ExactRetainingReserve { amount_sats, .. } => {
let mut tx_builder = locked_wallet.build_tx();
let amount = Amount::from_sat(amount_sats);
tx_builder
.add_recipient(address.script_pubkey(), amount)
.fee_rate(fee_rate)
.enable_rbf();
tx_builder
},
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats } => {
let change_address_info = locked_wallet.peek_address(KeychainKind::Internal, 0);
let balance = locked_wallet.balance();
let spendable_amount_sats = self
.get_balances_inner(balance, cur_anchor_reserve_sats)
.map(|(_, s)| s)
.unwrap_or(0);
Comment thread
jkczyz marked this conversation as resolved.
let tmp_tx = {
let mut tmp_tx_builder = locked_wallet.build_tx();
tmp_tx_builder
.drain_wallet()
.drain_to(address.script_pubkey())
.add_recipient(
change_address_info.address.script_pubkey(),
Amount::from_sat(cur_anchor_reserve_sats),
)
.fee_rate(fee_rate)
.enable_rbf();
match tmp_tx_builder.finish() {
Ok(psbt) => psbt.unsigned_tx,
Err(err) => {
log_error!(
self.logger,
"Failed to create temporary transaction: {}",
err
);
return Err(err.into());
},
}
};

let estimated_tx_fee = locked_wallet.calculate_fee(&tmp_tx).map_err(|e| {
log_error!(
self.logger,
"Failed to calculate fee of temporary transaction: {}",
e
);
e
})?;
let estimated_spendable_amount = Amount::from_sat(
spendable_amount_sats.saturating_sub(estimated_tx_fee.to_sat()),
);

if estimated_spendable_amount == Amount::ZERO {
log_error!(self.logger,
"Unable to send payment without infringing on Anchor reserves. Available: {}sats, estimated fee required: {}sats.",
spendable_amount_sats,
estimated_tx_fee,
);
return Err(Error::InsufficientFunds);
}

let mut tx_builder = locked_wallet.build_tx();
tx_builder
.add_recipient(address.script_pubkey(), estimated_spendable_amount)
.fee_absolute(estimated_tx_fee)
.enable_rbf();
tx_builder
},
OnchainSendAmount::AllDrainingReserve => {
let mut tx_builder = locked_wallet.build_tx();
tx_builder
.drain_wallet()
.drain_to(address.script_pubkey())
.fee_rate(fee_rate)
.enable_rbf();
tx_builder
},
};

let mut psbt = match tx_builder.finish() {
Ok(psbt) => {
Expand All@@ -267,6 +342,58 @@ where
},
};

// Check the reserve requirements (again) and return an error if they aren't met.
match send_amount {
OnchainSendAmount::ExactRetainingReserve {
amount_sats,
cur_anchor_reserve_sats,
} => {
let balance = locked_wallet.balance();
let spendable_amount_sats = self
.get_balances_inner(balance, cur_anchor_reserve_sats)
.map(|(_, s)| s)
.unwrap_or(0);
let tx_fee_sats = locked_wallet
.calculate_fee(&psbt.unsigned_tx)
.map_err(|e| {
log_error!(
self.logger,
"Failed to calculate fee of candidate transaction: {}",
e
);
e
})?
.to_sat();
if spendable_amount_sats < amount_sats.saturating_add(tx_fee_sats) {
log_error!(self.logger,
"Unable to send payment due to insufficient funds. Available: {}sats, Required: {}sats + {}sats fee",
spendable_amount_sats,
amount_sats,
tx_fee_sats,
);
return Err(Error::InsufficientFunds);
}
},
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats } => {
let balance = locked_wallet.balance();
let spendable_amount_sats = self
.get_balances_inner(balance, cur_anchor_reserve_sats)
.map(|(_, s)| s)
.unwrap_or(0);
let (sent, received) = locked_wallet.sent_and_received(&psbt.unsigned_tx);
let drain_amount = sent - received;
if spendable_amount_sats < drain_amount.to_sat() {
log_error!(self.logger,
"Unable to send payment due to insufficient funds. Available: {}sats, Required: {}",
spendable_amount_sats,
drain_amount,
);
return Err(Error::InsufficientFunds);
}
},
_ => {},
}

match locked_wallet.sign(&mut psbt, SignOptions::default()) {
Ok(finalized) => {
if !finalized {
Expand DownExpand Up@@ -295,21 +422,33 @@ where

let txid = tx.compute_txid();

if let Some(amount) = amount_or_drain {
log_info!(
self.logger,
"Created new transaction {} sending {}sats on-chain to address {}",
txid,
amount.to_sat(),
address
);
} else {
log_info!(
self.logger,
"Created new transaction {} sending all available on-chain funds to address {}",
txid,
address
);
match send_amount {
OnchainSendAmount::ExactRetainingReserve { amount_sats, .. } => {
log_info!(
self.logger,
"Created new transaction {} sending {}sats on-chain to address {}",
txid,
amount_sats,
address
);
},
OnchainSendAmount::AllRetainingReserve { cur_anchor_reserve_sats } => {
log_info!(
self.logger,
"Created new transaction {} sending available on-chain funds retaining a reserve of {}sats to address {}",
txid,
cur_anchor_reserve_sats,
address,
);
},
OnchainSendAmount::AllDrainingReserve => {
log_info!(
self.logger,
"Created new transaction {} sending all available on-chain funds to address {}",
txid,
address
);
},
}

Ok(txid)
Expand Down
Loading