Skip to content

Commit

Permalink
Move onchain payments API to OnchainPaymentsHandler
Browse files Browse the repository at this point in the history
  • Loading branch information
tnull committed Mar 5, 2024
1 parent 3dfd00d commit 0216178
Show file tree
Hide file tree
Showing 9 changed files with 92 additions and 50 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,10 @@ class AndroidLibTest {
val nodeId2 = node2.nodeId()
println("Node Id 2: $nodeId2")

val address1 = node1.newOnchainAddress()
val address1 = node1.onchain().newOnchainAddress()
println("Funding address 1: $address1")

val address2 = node2.newOnchainAddress()
val address2 = node2.onchain().newOnchainAddress()
println("Funding address 2: $address2")

node1.stop()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,10 +146,10 @@ class LibraryTest {
val nodeId2 = node2.nodeId()
println("Node Id 2: $nodeId2")

val address1 = node1.newOnchainAddress()
val address1 = node1.onchain().newOnchainAddress()
println("Funding address 1: $address1")

val address2 = node2.newOnchainAddress()
val address2 = node2.onchain().newOnchainAddress()
println("Funding address 2: $address2")

val txid1 = sendToAddress(address1, 100000u)
Expand Down
16 changes: 10 additions & 6 deletions bindings/ldk_node.udl
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,7 @@ interface Node {
sequence<SocketAddress>? listening_addresses();
Bolt11PaymentsHandler bolt11();
SpontaneousPaymentsHandler spontaneous();
[Throws=NodeError]
Address new_onchain_address();
[Throws=NodeError]
Txid send_to_onchain_address([ByRef]Address address, u64 amount_msat);
[Throws=NodeError]
Txid send_all_to_onchain_address([ByRef]Address address);
OnchainPaymentsHandler onchain();
[Throws=NodeError]
void connect(PublicKey node_id, SocketAddress address, boolean persist);
[Throws=NodeError]
Expand Down Expand Up @@ -110,6 +105,15 @@ interface SpontaneousPaymentsHandler {
void send_spontaneous_payment_probes(u64 amount_msat, PublicKey node_id);
};

interface OnchainPaymentsHandler {
[Throws=NodeError]
Address new_onchain_address();
[Throws=NodeError]
Txid send_to_onchain_address([ByRef]Address address, u64 amount_msat);
[Throws=NodeError]
Txid send_all_to_onchain_address([ByRef]Address address);
};

[Error]
enum NodeError {
"AlreadyRunning",
Expand Down
4 changes: 2 additions & 2 deletions bindings/python/src/ldk_node/test_ldk_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,9 +125,9 @@ def test_channel_full_cycle(self):
node_id_2 = node_2.node_id()
print("Node ID 2:", node_id_2)

address_1 = node_1.new_onchain_address()
address_1 = node_1.onchain().new_onchain_address()
txid_1 = send_to_address(address_1, 100000)
address_2 = node_2.new_onchain_address()
address_2 = node_2.onchain().new_onchain_address()
txid_2 = send_to_address(address_2, 100000)

wait_for_tx(esplora_endpoint, txid_1)
Expand Down
42 changes: 8 additions & 34 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ use gossip::GossipSource;
use liquidity::LiquiditySource;
use payment_store::PaymentStore;
pub use payment_store::{LSPFeeLimits, PaymentDetails, PaymentDirection, PaymentStatus};
use payments::{Bolt11PaymentsHandler, SpontaneousPaymentsHandler};
use payments::{Bolt11PaymentsHandler, OnchainPaymentsHandler, SpontaneousPaymentsHandler};
use peer_store::{PeerInfo, PeerStore};
use types::{
Broadcaster, ChainMonitor, ChannelManager, DynStore, FeeEstimator, KeysManager, NetworkGraph,
Expand All @@ -154,7 +154,6 @@ use lightning_background_processor::process_events_async;
use lightning_transaction_sync::EsploraSyncClient;

use bitcoin::secp256k1::PublicKey;
use bitcoin::{Address, Txid};

use rand::Rng;

Expand Down Expand Up @@ -771,38 +770,13 @@ impl Node {
))
}

/// Retrieve a new on-chain/funding address.
pub fn new_onchain_address(&self) -> Result<Address, Error> {
let funding_address = self.wallet.get_new_address()?;
log_info!(self.logger, "Generated new funding address: {}", funding_address);
Ok(funding_address)
}

/// Send an on-chain payment to the given address.
pub fn send_to_onchain_address(
&self, address: &bitcoin::Address, amount_sats: u64,
) -> Result<Txid, Error> {
let rt_lock = self.runtime.read().unwrap();
if rt_lock.is_none() {
return Err(Error::NotRunning);
}

let cur_balance = self.wallet.get_balance()?;
if cur_balance.get_spendable() < amount_sats {
log_error!(self.logger, "Unable to send payment due to insufficient funds.");
return Err(Error::InsufficientFunds);
}
self.wallet.send_to_address(address, Some(amount_sats))
}

/// Send an on-chain payment to the given address, draining all the available funds.
pub fn send_all_to_onchain_address(&self, address: &bitcoin::Address) -> 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)
/// Returns a payment handler allowing to send and receive on-chain payments.
pub fn onchain(&self) -> Arc<OnchainPaymentsHandler> {
Arc::new(OnchainPaymentsHandler::new(
Arc::clone(&self.runtime),
Arc::clone(&self.wallet),
Arc::clone(&self.logger),
))
}

/// Retrieve a list of known channels.
Expand Down
2 changes: 2 additions & 0 deletions src/payments/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
//! Handlers for different types of payments.
mod bolt11;
mod onchain;
mod spontaneous;

pub use bolt11::Bolt11PaymentsHandler;
pub use onchain::OnchainPaymentsHandler;
pub use spontaneous::SpontaneousPaymentsHandler;
63 changes: 63 additions & 0 deletions src/payments/onchain.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
//! Holds a payment handler allowing to send and receive on-chain payments.
use crate::error::Error;
use crate::logger::{log_error, log_info, FilesystemLogger, Logger};
use crate::types::Wallet;

use bitcoin::{Address, Txid};

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

/// A payment handler allowing to send and receive on-chain payments.
///
/// Should be retrieved by calling [`Node::onchain`].
///
/// [`Node::onchain`]: crate::Node::onchain
pub struct OnchainPaymentsHandler {
runtime: Arc<RwLock<Option<tokio::runtime::Runtime>>>,
wallet: Arc<Wallet>,
logger: Arc<FilesystemLogger>,
}

impl OnchainPaymentsHandler {
pub(crate) fn new(
runtime: Arc<RwLock<Option<tokio::runtime::Runtime>>>, wallet: Arc<Wallet>,
logger: Arc<FilesystemLogger>,
) -> Self {
Self { runtime, wallet, logger }
}

/// Retrieve a new on-chain/funding address.
pub fn new_onchain_address(&self) -> Result<Address, Error> {
let funding_address = self.wallet.get_new_address()?;
log_info!(self.logger, "Generated new funding address: {}", funding_address);
Ok(funding_address)
}

/// Send an on-chain payment to the given address.
pub fn send_to_onchain_address(
&self, address: &bitcoin::Address, amount_sats: u64,
) -> Result<Txid, Error> {
let rt_lock = self.runtime.read().unwrap();
if rt_lock.is_none() {
return Err(Error::NotRunning);
}

let cur_balance = self.wallet.get_balance()?;
if cur_balance.get_spendable() < amount_sats {
log_error!(self.logger, "Unable to send payment due to insufficient funds.");
return Err(Error::InsufficientFunds);
}
self.wallet.send_to_address(address, Some(amount_sats))
}

/// Send an on-chain payment to the given address, draining all the available funds.
pub fn send_all_to_onchain_address(&self, address: &bitcoin::Address) -> 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)
}
}
3 changes: 1 addition & 2 deletions src/uniffi_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ pub use lightning::util::string::UntrustedString;

pub use lightning_invoice::Bolt11Invoice;

pub use bitcoin::{BlockHash, Network, OutPoint};
pub use bitcoin::{Address, BlockHash, Network, OutPoint, Txid};

pub use bip39::Mnemonic;

Expand All @@ -17,7 +17,6 @@ use crate::{SocketAddress, UserChannelId};
use bitcoin::hashes::sha256::Hash as Sha256;
use bitcoin::hashes::Hash;
use bitcoin::secp256k1::PublicKey;
use bitcoin::{Address, Txid};
use lightning_invoice::SignedRawBolt11Invoice;

use std::convert::TryInto;
Expand Down
4 changes: 2 additions & 2 deletions tests/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,8 +317,8 @@ pub fn open_channel(
pub(crate) fn do_channel_full_cycle<E: ElectrumApi>(
node_a: TestNode, node_b: TestNode, bitcoind: &BitcoindClient, electrsd: &E, allow_0conf: bool,
) {
let addr_a = node_a.new_onchain_address().unwrap();
let addr_b = node_b.new_onchain_address().unwrap();
let addr_a = node_a.onchain().new_onchain_address().unwrap();
let addr_b = node_b.onchain().new_onchain_address().unwrap();

let premine_amount_sat = 100_000;

Expand Down

0 comments on commit 0216178

Please sign in to comment.