Skip to content

Commit 5abbd97

Browse files
committed
Add RBF replacement tracking with new persisted lookup table
Introduce a new lookup `ReplacedTransactionStore` that maps old/replaced transaction IDs to their current replacement transaction IDs, enabling reliable tracking of replaced transactions throughout the replacement chain. Key changes: - Add persisted storage for RBF replacement relationships - Link transactions in replacement trees using payment IDs - Remove entire replacement chains from persistence when any transaction in the tree is confirmed
1 parent 233aa5a commit 5abbd97

File tree

7 files changed

+208
-49
lines changed

7 files changed

+208
-49
lines changed

src/builder.rs

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ use crate::io::utils::{
5959
use crate::io::vss_store::VssStoreBuilder;
6060
use crate::io::{
6161
self, PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE, PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE,
62+
REPLACED_TX_PERSISTENCE_PRIMARY_NAMESPACE, REPLACED_TX_PERSISTENCE_SECONDARY_NAMESPACE,
6263
};
6364
use crate::liquidity::{
6465
LSPS1ClientConfig, LSPS2ClientConfig, LSPS2ServiceConfig, LiquiditySourceBuilder,
@@ -71,7 +72,7 @@ use crate::runtime::Runtime;
7172
use crate::tx_broadcaster::TransactionBroadcaster;
7273
use crate::types::{
7374
ChainMonitor, ChannelManager, DynStore, GossipSync, Graph, KeysManager, MessageRouter,
74-
OnionMessenger, PaymentStore, PeerManager, Persister,
75+
OnionMessenger, PaymentStore, PeerManager, Persister, ReplacedTransactionStore,
7576
};
7677
use crate::wallet::persist::KVStoreWalletPersister;
7778
use crate::wallet::Wallet;
@@ -1230,6 +1231,21 @@ fn build_with_store_internal(
12301231
},
12311232
};
12321233

1234+
let replaced_tx_store =
1235+
match io::utils::read_replaced_txs(Arc::clone(&kv_store), Arc::clone(&logger)) {
1236+
Ok(replaced_txs) => Arc::new(ReplacedTransactionStore::new(
1237+
replaced_txs,
1238+
REPLACED_TX_PERSISTENCE_PRIMARY_NAMESPACE.to_string(),
1239+
REPLACED_TX_PERSISTENCE_SECONDARY_NAMESPACE.to_string(),
1240+
Arc::clone(&kv_store),
1241+
Arc::clone(&logger),
1242+
)),
1243+
Err(e) => {
1244+
log_error!(logger, "Failed to read replaced transaction data from store: {}", e);
1245+
return Err(BuildError::ReadFailed);
1246+
},
1247+
};
1248+
12331249
let wallet = Arc::new(Wallet::new(
12341250
bdk_wallet,
12351251
wallet_persister,
@@ -1238,6 +1254,7 @@ fn build_with_store_internal(
12381254
Arc::clone(&payment_store),
12391255
Arc::clone(&config),
12401256
Arc::clone(&logger),
1257+
Arc::clone(&replaced_tx_store),
12411258
));
12421259

12431260
// Initialize the KeysManager

src/io/mod.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,3 +78,7 @@ pub(crate) const BDK_WALLET_INDEXER_KEY: &str = "indexer";
7878
///
7979
/// [`StaticInvoice`]: lightning::offers::static_invoice::StaticInvoice
8080
pub(crate) const STATIC_INVOICE_STORE_PRIMARY_NAMESPACE: &str = "static_invoices";
81+
82+
/// The replaced transaction information will be persisted under this prefix.
83+
pub(crate) const REPLACED_TX_PERSISTENCE_PRIMARY_NAMESPACE: &str = "replaced_txs";
84+
pub(crate) const REPLACED_TX_PERSISTENCE_SECONDARY_NAMESPACE: &str = "";

src/io/utils.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ use crate::io::{
4545
NODE_METRICS_KEY, NODE_METRICS_PRIMARY_NAMESPACE, NODE_METRICS_SECONDARY_NAMESPACE,
4646
};
4747
use crate::logger::{log_error, LdkLogger, Logger};
48+
use crate::payment::ReplacedOnchainTransactionDetails;
4849
use crate::peer_store::PeerStore;
4950
use crate::types::{Broadcaster, DynStore, KeysManager, Sweeper};
5051
use crate::wallet::ser::{ChangeSetDeserWrapper, ChangeSetSerWrapper};
@@ -576,6 +577,38 @@ pub(crate) fn read_bdk_wallet_change_set(
576577
Ok(Some(change_set))
577578
}
578579

580+
/// Read previously persisted replaced transaction information from the store.
581+
pub(crate) fn read_replaced_txs<L: Deref>(
582+
kv_store: Arc<DynStore>, logger: L,
583+
) -> Result<Vec<ReplacedOnchainTransactionDetails>, std::io::Error>
584+
where
585+
L::Target: LdkLogger,
586+
{
587+
let mut res = Vec::new();
588+
589+
for stored_key in KVStoreSync::list(
590+
&*kv_store,
591+
REPLACED_TX_PERSISTENCE_PRIMARY_NAMESPACE,
592+
REPLACED_TX_PERSISTENCE_SECONDARY_NAMESPACE,
593+
)? {
594+
let mut reader = Cursor::new(KVStoreSync::read(
595+
&*kv_store,
596+
REPLACED_TX_PERSISTENCE_PRIMARY_NAMESPACE,
597+
REPLACED_TX_PERSISTENCE_SECONDARY_NAMESPACE,
598+
&stored_key,
599+
)?);
600+
let payment = ReplacedOnchainTransactionDetails::read(&mut reader).map_err(|e| {
601+
log_error!(logger, "Failed to deserialize ReplacedOnchainTransactionDetails: {}", e);
602+
std::io::Error::new(
603+
std::io::ErrorKind::InvalidData,
604+
"Failed to deserialize ReplacedOnchainTransactionDetails",
605+
)
606+
})?;
607+
res.push(payment);
608+
}
609+
Ok(res)
610+
}
611+
579612
#[cfg(test)]
580613
mod tests {
581614
use super::read_or_generate_seed_file;

src/payment/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,15 @@ pub(crate) mod asynchronous;
1111
mod bolt11;
1212
mod bolt12;
1313
mod onchain;
14+
mod replaced_transaction_store;
1415
mod spontaneous;
1516
pub(crate) mod store;
1617
mod unified_qr;
1718

1819
pub use bolt11::Bolt11Payment;
1920
pub use bolt12::Bolt12Payment;
2021
pub use onchain::OnchainPayment;
22+
pub use replaced_transaction_store::ReplacedOnchainTransactionDetails;
2123
pub use spontaneous::SpontaneousPayment;
2224
pub use store::{
2325
ConfirmationStatus, LSPFeeLimits, PaymentDetails, PaymentDirection, PaymentKind, PaymentStatus,
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
// This file is Copyright its original authors, visible in version control history.
2+
//
3+
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5+
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
6+
// accordance with one or both of these licenses.
7+
8+
use bitcoin::Txid;
9+
use lightning::ln::channelmanager::PaymentId;
10+
use lightning::ln::msgs::DecodeError;
11+
use lightning::util::ser::{Readable, Writeable};
12+
use lightning::{_init_and_read_len_prefixed_tlv_fields, write_tlv_fields};
13+
14+
use crate::data_store::{StorableObject, StorableObjectId, StorableObjectUpdate};
15+
16+
/// Details of an on-chain transaction that has replaced a previous transaction (e.g., via RBF).
17+
#[derive(Clone, Debug, PartialEq, Eq)]
18+
pub struct ReplacedOnchainTransactionDetails {
19+
/// The new transaction ID.
20+
pub new_txid: Txid,
21+
/// The original transaction ID that was replaced.
22+
pub original_txid: Txid,
23+
/// The payment ID associated with the transaction.
24+
pub payment_id: PaymentId,
25+
}
26+
27+
impl ReplacedOnchainTransactionDetails {
28+
pub(crate) fn new(new_txid: Txid, original_txid: Txid, payment_id: PaymentId) -> Self {
29+
Self { new_txid, original_txid, payment_id }
30+
}
31+
}
32+
33+
impl Writeable for ReplacedOnchainTransactionDetails {
34+
fn write<W: lightning::util::ser::Writer>(
35+
&self, writer: &mut W,
36+
) -> Result<(), lightning::io::Error> {
37+
write_tlv_fields!(writer, {
38+
(0, self.new_txid, required),
39+
(2, self.original_txid, required),
40+
(4, self.payment_id, required),
41+
});
42+
Ok(())
43+
}
44+
}
45+
46+
impl Readable for ReplacedOnchainTransactionDetails {
47+
fn read<R: lightning::io::Read>(
48+
reader: &mut R,
49+
) -> Result<ReplacedOnchainTransactionDetails, DecodeError> {
50+
_init_and_read_len_prefixed_tlv_fields!(reader, {
51+
(0, new_txid, required),
52+
(2, original_txid, required),
53+
(4, payment_id, required),
54+
});
55+
56+
let new_txid: Txid = new_txid.0.ok_or(DecodeError::InvalidValue)?;
57+
let original_txid: Txid = original_txid.0.ok_or(DecodeError::InvalidValue)?;
58+
let payment_id: PaymentId = payment_id.0.ok_or(DecodeError::InvalidValue)?;
59+
60+
Ok(ReplacedOnchainTransactionDetails { new_txid, original_txid, payment_id })
61+
}
62+
}
63+
64+
impl StorableObjectId for Txid {
65+
fn encode_to_hex_str(&self) -> String {
66+
self.to_string()
67+
}
68+
}
69+
impl StorableObject for ReplacedOnchainTransactionDetails {
70+
type Id = Txid;
71+
type Update = ReplacedOnchainTransactionDetailsUpdate;
72+
73+
fn id(&self) -> Self::Id {
74+
self.new_txid
75+
}
76+
77+
fn update(&mut self, _update: &Self::Update) -> bool {
78+
// We don't update, we delete on confirmation
79+
false
80+
}
81+
82+
fn to_update(&self) -> Self::Update {
83+
self.into()
84+
}
85+
}
86+
87+
#[derive(Clone, Debug, PartialEq, Eq)]
88+
pub(crate) struct ReplacedOnchainTransactionDetailsUpdate {
89+
pub id: Txid,
90+
}
91+
92+
impl From<&ReplacedOnchainTransactionDetails> for ReplacedOnchainTransactionDetailsUpdate {
93+
fn from(value: &ReplacedOnchainTransactionDetails) -> Self {
94+
Self { id: value.new_txid }
95+
}
96+
}
97+
98+
impl StorableObjectUpdate<ReplacedOnchainTransactionDetails>
99+
for ReplacedOnchainTransactionDetailsUpdate
100+
{
101+
fn id(&self) -> <ReplacedOnchainTransactionDetails as StorableObject>::Id {
102+
self.id
103+
}
104+
}

src/types.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ use crate::fee_estimator::OnchainFeeEstimator;
3434
use crate::gossip::RuntimeSpawner;
3535
use crate::logger::Logger;
3636
use crate::message_handler::NodeCustomMessageHandler;
37-
use crate::payment::PaymentDetails;
37+
use crate::payment::{PaymentDetails, ReplacedOnchainTransactionDetails};
3838

3939
/// A supertrait that requires that a type implements both [`KVStore`] and [`KVStoreSync`] at the
4040
/// same time.
@@ -462,3 +462,6 @@ impl From<&(u64, Vec<u8>)> for CustomTlvRecord {
462462
CustomTlvRecord { type_num: tlv.0, value: tlv.1.clone() }
463463
}
464464
}
465+
466+
pub(crate) type ReplacedTransactionStore =
467+
DataStore<ReplacedOnchainTransactionDetails, Arc<Logger>>;

src/wallet/mod.rs

Lines changed: 43 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,10 @@ use crate::config::Config;
5151
use crate::fee_estimator::{ConfirmationTarget, FeeEstimator, OnchainFeeEstimator};
5252
use crate::logger::{log_debug, log_error, log_info, log_trace, LdkLogger, Logger};
5353
use crate::payment::store::ConfirmationStatus;
54-
use crate::payment::{PaymentDetails, PaymentDirection, PaymentKind, PaymentStatus};
55-
use crate::types::{Broadcaster, PaymentStore};
54+
use crate::payment::{
55+
PaymentDetails, PaymentDirection, PaymentKind, PaymentStatus, ReplacedOnchainTransactionDetails,
56+
};
57+
use crate::types::{Broadcaster, PaymentStore, ReplacedTransactionStore};
5658
use crate::Error;
5759

5860
pub(crate) enum OnchainSendAmount {
@@ -73,18 +75,28 @@ pub(crate) struct Wallet {
7375
payment_store: Arc<PaymentStore>,
7476
config: Arc<Config>,
7577
logger: Arc<Logger>,
78+
replaced_tx_store: Arc<ReplacedTransactionStore>,
7679
}
7780

7881
impl Wallet {
7982
pub(crate) fn new(
8083
wallet: bdk_wallet::PersistedWallet<KVStoreWalletPersister>,
8184
wallet_persister: KVStoreWalletPersister, broadcaster: Arc<Broadcaster>,
8285
fee_estimator: Arc<OnchainFeeEstimator>, payment_store: Arc<PaymentStore>,
83-
config: Arc<Config>, logger: Arc<Logger>,
86+
config: Arc<Config>, logger: Arc<Logger>, replaced_tx_store: Arc<ReplacedTransactionStore>,
8487
) -> Self {
8588
let inner = Mutex::new(wallet);
8689
let persister = Mutex::new(wallet_persister);
87-
Self { inner, persister, broadcaster, fee_estimator, payment_store, config, logger }
90+
Self {
91+
inner,
92+
persister,
93+
broadcaster,
94+
fee_estimator,
95+
payment_store,
96+
config,
97+
logger,
98+
replaced_tx_store,
99+
}
88100
}
89101

90102
pub(crate) fn get_full_scan_request(&self) -> FullScanRequest<KeychainKind> {
@@ -209,6 +221,17 @@ impl Wallet {
209221
None,
210222
);
211223
self.payment_store.insert_or_update(payment)?;
224+
225+
// Remove any replaced transactions associated with this payment
226+
let replaced_txids = self
227+
.replaced_tx_store
228+
.list_filter(|r| r.payment_id == payment_id)
229+
.iter()
230+
.map(|p| p.new_txid)
231+
.collect::<Vec<Txid>>();
232+
for replaced_txid in replaced_txids {
233+
self.replaced_tx_store.remove(&replaced_txid)?;
234+
}
212235
},
213236
WalletEvent::ChainTipChanged { new_tip, .. } => {
214237
// Get all payments that are Pending with Confirmed status
@@ -253,47 +276,24 @@ impl Wallet {
253276
);
254277
self.payment_store.insert_or_update(payment)?;
255278
},
256-
WalletEvent::TxReplaced { txid, tx, conflicts } => {
279+
WalletEvent::TxReplaced { txid, conflicts, .. } => {
257280
let payment_id = self
258281
.find_payment_by_txid(*txid)
259282
.unwrap_or_else(|| PaymentId(txid.to_byte_array()));
260283

261-
if let Some(mut payment) = self.payment_store.get(&payment_id) {
262-
if let PaymentKind::Onchain {
263-
ref mut conflicting_txids,
264-
txid: current_txid,
265-
..
266-
} = payment.kind
267-
{
268-
let existing_set: std::collections::HashSet<_> =
269-
conflicting_txids.iter().collect();
270-
271-
let new_conflicts: Vec<_> = conflicts
272-
.iter()
273-
.map(|(_, conflict_txid)| *conflict_txid)
274-
.filter(|conflict_txid| {
275-
*conflict_txid != current_txid
276-
&& !existing_set.contains(conflict_txid)
277-
})
278-
.collect();
279-
280-
conflicting_txids.extend(new_conflicts);
281-
}
282-
self.payment_store.insert_or_update(payment)?;
283-
} else {
284-
let conflicting_txids =
285-
Some(conflicts.iter().map(|(_, txid)| *txid).collect());
284+
// Collect all conflict txids
285+
let conflict_txids: Vec<Txid> =
286+
conflicts.iter().map(|(_, conflict_txid)| *conflict_txid).collect();
286287

287-
let payment = self.create_payment_from_tx(
288-
locked_wallet,
288+
for conflict_txid in conflict_txids {
289+
// Update the replaced transaction store
290+
let replaced_tx_details = ReplacedOnchainTransactionDetails::new(
291+
conflict_txid,
289292
*txid,
290293
payment_id,
291-
tx,
292-
PaymentStatus::Pending,
293-
ConfirmationStatus::Unconfirmed,
294-
conflicting_txids,
295294
);
296-
self.payment_store.insert_or_update(payment)?;
295+
296+
self.replaced_tx_store.insert_or_update(replaced_tx_details)?;
297297
}
298298
},
299299
WalletEvent::TxDropped { txid, tx } => {
@@ -963,16 +963,12 @@ impl Wallet {
963963
return Some(direct_payment_id);
964964
}
965965

966-
self.payment_store
967-
.list_filter(|p| {
968-
if let PaymentKind::Onchain { txid, conflicting_txids, .. } = &p.kind {
969-
*txid == target_txid || conflicting_txids.contains(&target_txid)
970-
} else {
971-
false
972-
}
973-
})
974-
.first()
975-
.map(|p| p.id)
966+
// Check if this txid is a replaced transaction
967+
if let Some(replaced_details) = self.replaced_tx_store.get(&target_txid) {
968+
return Some(replaced_details.payment_id);
969+
}
970+
971+
None
976972
}
977973
}
978974

0 commit comments

Comments
 (0)