Skip to content
Open
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
16 changes: 15 additions & 1 deletion benches/payments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@ use bitcoin::Amount;
use common::{
expect_channel_ready_event, generate_blocks_and_wait, premine_and_distribute_funds,
random_chain_source, setup_bitcoind_and_electrsd, setup_two_nodes_with_store,
ExpectOnchainPaymentEvent, OnchainPaymentEvent,
};
use criterion::{criterion_group, criterion_main, Criterion};
use ldk_node::lightning::chain::channelmonitor::ANTI_REORG_DELAY;
use ldk_node::{Event, Node};
use lightning_types::payment::{PaymentHash, PaymentPreimage};
use rand::RngCore;
Expand Down Expand Up @@ -142,7 +144,7 @@ fn payment_benchmark(c: &mut Criterion) {
runtime.block_on(async move {
let address_a = node_a_cloned.onchain_payment().new_address().unwrap();
let premine_sat = 25_000_000;
premine_and_distribute_funds(
let premine_txid = premine_and_distribute_funds(
&bitcoind.client,
&electrsd.client,
vec![address_a],
Expand All @@ -151,6 +153,18 @@ fn payment_benchmark(c: &mut Criterion) {
.await;
node_a_cloned.sync_wallets().unwrap();
node_b_cloned.sync_wallets().unwrap();
generate_blocks_and_wait(
&bitcoind.client,
&electrsd.client,
(ANTI_REORG_DELAY - 1) as usize,
)
.await;
node_a_cloned.sync_wallets().unwrap();
node_b_cloned.sync_wallets().unwrap();
assert_eq!(
node_a_cloned.expect_onchain_payment_event(OnchainPaymentEvent::Received).await,
premine_txid,
);
open_channel_push_amt(
&node_a_cloned,
&node_b_cloned,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,28 @@ class LibraryTest {
node1.syncWallets()
node2.syncWallets()

val onchainPaymentReceivedEvent1 = node1.waitNextEvent()
println("Got event: $onchainPaymentReceivedEvent1")
when (onchainPaymentReceivedEvent1) {
is Event.OnchainPaymentReceived -> {
assertEquals(txid1, onchainPaymentReceivedEvent1.txid)
assertEquals(100000000uL, onchainPaymentReceivedEvent1.amountMsat)
}
else -> error("Expected initial on-chain payment event")
}
node1.eventHandled()

val onchainPaymentReceivedEvent2 = node2.waitNextEvent()
println("Got event: $onchainPaymentReceivedEvent2")
when (onchainPaymentReceivedEvent2) {
is Event.OnchainPaymentReceived -> {
assertEquals(txid2, onchainPaymentReceivedEvent2.txid)
assertEquals(100000000uL, onchainPaymentReceivedEvent2.amountMsat)
}
else -> error("Expected initial on-chain payment event")
}
node2.eventHandled()

val spendableBalance1 = node1.listBalances().spendableOnchainBalanceSats
val spendableBalance2 = node2.listBalances().spendableOnchainBalanceSats
val totalBalance1 = node1.listBalances().totalOnchainBalanceSats
Expand Down
8 changes: 8 additions & 0 deletions bindings/python/src/ldk_node/test_ldk_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,14 @@ def fund_nodes(node_1, node_2, esplora_endpoint, amount_sats=100000):
node_1.sync_wallets()
node_2.sync_wallets()

received_event_1 = expect_event(node_1, Event.ONCHAIN_PAYMENT_RECEIVED)
assert received_event_1.txid == txid_1
assert received_event_1.amount_msat == amount_sats * 1000

received_event_2 = expect_event(node_2, Event.ONCHAIN_PAYMENT_RECEIVED)
assert received_event_2.txid == txid_2
assert received_event_2.amount_msat == amount_sats * 1000

def open_channel_and_wait_ready(node_1, node_2, node_id_2, listening_address_2, esplora_endpoint, channel_amount_sats=50000):
node_1.open_channel(node_id_2, listening_address_2, channel_amount_sats, None, None)

Expand Down
34 changes: 17 additions & 17 deletions src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1440,8 +1440,8 @@ fn build_with_store_internal(

let kv_store_ref = Arc::clone(&kv_store);
let logger_ref = Arc::clone(&logger);
let (payment_store_res, node_metris_res, pending_payment_store_res) =
runtime.block_on(async move {
let (payment_store_res, node_metris_res, pending_payment_store_res, event_queue_res) = runtime
.block_on(async move {
tokio::join!(
read_all_objects(
&*kv_store_ref,
Expand All @@ -1455,7 +1455,8 @@ fn build_with_store_internal(
PENDING_PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE,
PENDING_PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE,
Arc::clone(&logger_ref),
)
),
read_event_queue(Arc::clone(&kv_store_ref), Arc::clone(&logger_ref)),
)
});

Expand Down Expand Up @@ -1742,6 +1743,18 @@ fn build_with_store_internal(
},
};

let event_queue = match event_queue_res {
Ok(event_queue) => Arc::new(event_queue),
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
Arc::new(EventQueue::new(Arc::clone(&kv_store), Arc::clone(&logger)))
} else {
log_error!(logger, "Failed to read event queue from store: {}", e);
return Err(BuildError::ReadFailed);
}
},
};

let wallet = Arc::new(Wallet::new(
bdk_wallet,
wallet_persister,
Expand All @@ -1751,6 +1764,7 @@ fn build_with_store_internal(
Arc::clone(&payment_store),
Arc::clone(&runtime),
Arc::clone(&config),
Arc::clone(&event_queue),
Arc::clone(&logger),
Arc::clone(&pending_payment_store),
));
Expand Down Expand Up @@ -1853,7 +1867,6 @@ fn build_with_store_internal(
external_scores_res,
channel_manager_bytes_res,
sweeper_bytes_res,
event_queue_res,
peer_info_res,
) = runtime.block_on(async move {
tokio::join!(
Expand All @@ -1866,7 +1879,6 @@ fn build_with_store_internal(
CHANNEL_MANAGER_PERSISTENCE_KEY,
),
output_sweeper_future,
read_event_queue(Arc::clone(&kv_store_ref), Arc::clone(&logger_ref)),
read_peer_info(Arc::clone(&kv_store_ref), Arc::clone(&logger_ref)),
)
});
Expand Down Expand Up @@ -2212,18 +2224,6 @@ fn build_with_store_internal(
},
};

let event_queue = match event_queue_res {
Ok(event_queue) => Arc::new(event_queue),
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
Arc::new(EventQueue::new(Arc::clone(&kv_store), Arc::clone(&logger)))
} else {
log_error!(logger, "Failed to read event queue from store: {}", e);
return Err(BuildError::ReadFailed);
}
},
};

let peer_store = match peer_info_res {
Ok(peer_store) => Arc::new(peer_store),
Err(e) => {
Expand Down
104 changes: 91 additions & 13 deletions src/data_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,33 +82,43 @@ where
}

pub(crate) async fn insert_or_update(&self, object: SO) -> Result<bool, Error> {
self.insert_or_update_with(object, |updated, _| updated).await
}

/// Inserts `object` or merges it into an existing object, returning whether the store changed
/// and the effective object after the merge.
pub(crate) async fn insert_or_update_and_get(&self, object: SO) -> Result<(bool, SO), Error> {
self.insert_or_update_with(object, |updated, stored_object| {
(updated, stored_object.clone())
})
.await
}

async fn insert_or_update_with<R>(
&self, object: SO, result_fn: impl FnOnce(bool, &SO) -> R,
) -> Result<R, Error> {
let _guard = self.mutation_lock.lock().await;

let id = object.id();
let data_to_persist = {
let updated_object = {
let locked_objects = self.objects.lock().expect("lock");
if let Some(existing_object) = locked_objects.get(&id) {
let mut updated_object = existing_object.clone();
let updated = updated_object.update(object.to_update());
if updated {
Some(updated_object)
updated_object
} else {
None
return Ok(result_fn(false, existing_object));
}
} else {
Some(object)
object
}
};

match data_to_persist {
Some(updated_object) => {
self.persist(&updated_object).await?;
let mut locked_objects = self.objects.lock().expect("lock");
locked_objects.insert(id, updated_object);
Ok(true)
},
None => Ok(false),
}
self.persist(&updated_object).await?;
let mut locked_objects = self.objects.lock().expect("lock");
let stored_object = locked_objects.entry(id).insert_entry(updated_object).into_mut();
Ok(result_fn(true, stored_object))
}

pub(crate) async fn remove(&self, id: &SO::Id) -> Result<(), Error> {
Expand Down Expand Up @@ -287,6 +297,52 @@ mod tests {
(2, data, required),
});

struct MergingTestObjectUpdate {
id: TestObjectId,
data: [u8; 3],
}

impl StorableObjectUpdate<MergingTestObject> for MergingTestObjectUpdate {
fn id(&self) -> TestObjectId {
self.id
}
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct MergingTestObject {
id: TestObjectId,
data: [u8; 3],
preserved_data: [u8; 3],
}

impl StorableObject for MergingTestObject {
type Id = TestObjectId;
type Update = MergingTestObjectUpdate;

fn id(&self) -> Self::Id {
self.id
}

fn update(&mut self, update: Self::Update) -> bool {
if self.data != update.data {
self.data = update.data;
true
} else {
false
}
}

fn to_update(&self) -> Self::Update {
Self::Update { id: self.id, data: self.data }
}
}

impl_writeable_tlv_based!(MergingTestObject, {
(0, id, required),
(2, data, required),
(4, preserved_data, required),
});

struct FailingStore;

impl KVStore for FailingStore {
Expand Down Expand Up @@ -403,6 +459,28 @@ mod tests {
assert_eq!(Ok(true), data_store.insert_or_update(new_iou_object).await);
}

#[tokio::test]
async fn insert_or_update_and_get_returns_merged_object() {
let store: Arc<DynStore> = Arc::new(DynStoreWrapper(InMemoryStore::new()));
let logger = Arc::new(TestLogger::new());
let id = TestObjectId { id: [42u8; 4] };
let existing = MergingTestObject { id, data: [23u8; 3], preserved_data: [24u8; 3] };
let data_store = DataStore::new(
vec![existing],
"datastore_test_primary".to_string(),
"datastore_test_secondary".to_string(),
store,
logger,
);

let supplied = MergingTestObject { id, data: [25u8; 3], preserved_data: [26u8; 3] };
let expected = MergingTestObject { data: supplied.data, ..existing };
assert_eq!(Ok((true, expected)), data_store.insert_or_update_and_get(supplied).await);

let unchanged = MergingTestObject { preserved_data: [27u8; 3], ..expected };
assert_eq!(Ok((false, expected)), data_store.insert_or_update_and_get(unchanged).await);
}

#[tokio::test]
async fn insert_or_update_does_not_mutate_memory_if_persist_fails() {
let existing_id = TestObjectId { id: [42u8; 4] };
Expand Down
56 changes: 55 additions & 1 deletion src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use std::sync::{Arc, Mutex};

use bitcoin::blockdata::locktime::absolute::LockTime;
use bitcoin::secp256k1::PublicKey;
use bitcoin::{Amount, OutPoint};
use bitcoin::{Amount, BlockHash, OutPoint, Txid};
use lightning::blinded_path::message::NextMessageHop;
use lightning::events::bump_transaction::BumpTransactionEvent;
#[cfg(not(feature = "uniffi"))]
Expand Down Expand Up @@ -271,6 +271,46 @@ pub enum Event {
/// This will be `None` for events serialized by LDK Node v0.2.1 and prior.
reason: Option<ClosureReason>,
},
/// A sent on-chain payment was successful.
///
/// This is only emitted for wallet transactions which were not classified as channel
/// funding, splices, closes, sweeps, or other LDK-driven chain activity.
///
/// It's guaranteed to have reached at least [`ANTI_REORG_DELAY`] confirmations.
///
/// [`ANTI_REORG_DELAY`]: lightning::chain::channelmonitor::ANTI_REORG_DELAY
OnchainPaymentSuccessful {
/// A local identifier used to track the payment.
payment_id: PaymentId,
/// The transaction identifier.
txid: Txid,
/// The value, in thousandths of a satoshi, that was sent.
amount_msat: u64,
/// The hash of the block in which the transaction was confirmed.
block_hash: BlockHash,
/// The height at which the block was confirmed.
block_height: u32,
},
/// An on-chain payment has been received.
///
/// This is only emitted for wallet transactions which were not classified as channel
/// funding, splices, closes, sweeps, or other LDK-driven chain activity.
///
/// It's guaranteed to have reached at least [`ANTI_REORG_DELAY`] confirmations.
///
/// [`ANTI_REORG_DELAY`]: lightning::chain::channelmonitor::ANTI_REORG_DELAY
OnchainPaymentReceived {
/// A local identifier used to track the payment.
payment_id: PaymentId,
/// The transaction identifier.
txid: Txid,
/// The value, in thousandths of a satoshi, that has been received.
amount_msat: u64,
/// The hash of the block in which the transaction was confirmed.
block_hash: BlockHash,
/// The height at which the block was confirmed.
block_height: u32,
},
/// A channel splice has been negotiated and the funding transaction is pending
/// confirmation on-chain.
SpliceNegotiated {
Expand Down Expand Up @@ -374,6 +414,20 @@ impl_writeable_tlv_based_enum!(Event,
(5, user_channel_id, required),
// TLV 7 (abandoned_funding_txo) may be set for LDK Node v0.7.
},
(10, OnchainPaymentSuccessful) => {
(0, payment_id, required),
(2, txid, required),
(4, amount_msat, required),
(6, block_hash, required),
(8, block_height, required),
},
(11, OnchainPaymentReceived) => {
(0, payment_id, required),
(2, txid, required),
(4, amount_msat, required),
(6, block_hash, required),
(8, block_height, required),
},
);

pub struct EventQueue<L: Deref>
Expand Down
Loading
Loading