From 10b0b3e3a399c37faf584ff70690b4e7e48cb779 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Tue, 17 Nov 2026 10:50:14 +0100 Subject: [PATCH 01/11] Add wallet test helpers for tracked payments Wallet tests read and write the pending payment store directly, each spelling out the store call and the entry or update type it takes. Changing the shape of pending entries would touch nearly every test. Route those reads and writes through a few test helpers, so later changes to the entry type only need to adapt the helpers. Written with the help of an AI tool. Co-Authored-By: HAL 9000 --- src/wallet/mod.rs | 1170 ++++++++++----------------------------------- 1 file changed, 263 insertions(+), 907 deletions(-) diff --git a/src/wallet/mod.rs b/src/wallet/mod.rs index ab8f5b812b..a8119554d4 100644 --- a/src/wallet/mod.rs +++ b/src/wallet/mod.rs @@ -5340,6 +5340,38 @@ mod tests { wallet.address_pool.lock().unwrap().available.iter().map(|(index, _)| *index).collect() } + async fn entry_of(wallet: &Wallet, id: &PaymentId) -> Option { + wallet.payment_stores.pending_payment_store().get(id).await.unwrap() + } + + async fn record_of(wallet: &Wallet, id: &PaymentId) -> Option { + wallet.payment_stores.payment_store().get(id).await.unwrap() + } + + /// Writes `details` as the payment record and an entry tracking it with the given conflicts, + /// as wallet sync does for a pending payment. + async fn track_pending(wallet: &Wallet, details: PaymentDetails, conflicting_txids: Vec) { + let stores = wallet.payment_stores.lock().await; + stores.insert_or_update_payment(details.clone()).await.unwrap(); + let entry = PendingPaymentDetails::new(details, conflicting_txids, Vec::new()); + stores.pending_payment_store().insert_or_update(entry).await.unwrap(); + } + + /// Records that wallet sync saw `conflicting_txids` conflict with the payment's transaction. + async fn set_conflicts(wallet: &Wallet, id: PaymentId, conflicting_txids: Vec) { + wallet + .payment_stores + .pending_payment_store() + .update(PendingPaymentDetailsUpdate { + id, + payment_update: None, + conflicting_txids: Some(conflicting_txids), + candidates: Vec::new(), + }) + .await + .unwrap(); + } + fn funding_payment(id: PaymentId, txid: Txid, status: PaymentStatus) -> PaymentDetails { PaymentDetails::new( id, @@ -6505,8 +6537,7 @@ mod tests { .await .unwrap() .expect("the round identifies its payment"); - let entry = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("entry"); + let entry = entry_of(&wallet, &id).await.expect("entry"); assert!(entry.details().is_none()); assert!(entry.candidate(txid).expect("candidate").awaiting_broadcast); assert_eq!( @@ -6570,15 +6601,7 @@ mod tests { .unwrap() .expect("the round's facts identify its payment"); assert!( - wallet - .payment_stores - .pending_payment_store() - .get(&id) - .await - .unwrap() - .expect("entry") - .candidate(txid) - .is_some(), + entry_of(&wallet, &id).await.expect("entry").candidate(txid).is_some(), "the signed round is in the channel's candidate history", ); @@ -6713,8 +6736,7 @@ mod tests { .expect("this node\'s share"); assert_eq!(figures.funding_payment_id, id); assert_eq!(figures.fee_paid_msat, Some(300_000), "the recorded share stands"); - let entry = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("entry"); + let entry = entry_of(&wallet, &id).await.expect("entry"); assert!(entry.candidate(txid).expect("candidate").awaiting_broadcast); } @@ -6764,8 +6786,7 @@ mod tests { // own. assert_eq!(payments[0].amount_msat, Some(500_300_000)); assert_eq!(payments[0].fee_paid_msat, Some(300_000)); - let entry = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("entry"); + let entry = entry_of(&wallet, &id).await.expect("entry"); assert_eq!(entry.details().map(|details| details.id), Some(id)); assert!(entry.candidate(txid).expect("candidate").awaiting_broadcast); } @@ -6807,8 +6828,7 @@ mod tests { }; wallet.update_payment_store(vec![event]).await.unwrap(); - let payment = - wallet.payment_stores.payment_store().get(&id).await.unwrap().expect("record"); + let payment = record_of(&wallet, &id).await.expect("record"); assert_eq!(payment.status, PaymentStatus::Succeeded); assert!(matches!( payment.kind, @@ -6820,7 +6840,7 @@ mod tests { )); assert_eq!(payment.amount_msat, Some(500_300_000)); assert!( - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_none(), + entry_of(&wallet, &id).await.is_none(), "a settled payment leaves the entry nothing to track", ); } @@ -6928,8 +6948,7 @@ mod tests { old_block_time: None, }; wallet.update_payment_store(vec![event]).await.unwrap(); - let payment = - wallet.payment_stores.payment_store().get(&id).await.unwrap().expect("record"); + let payment = record_of(&wallet, &id).await.expect("record"); assert!(matches!( payment.kind, PaymentKind::Onchain { txid, status: ConfirmationStatus::Confirmed { .. }, .. } @@ -6976,8 +6995,7 @@ mod tests { assert_eq!(payments.len(), 1, "the bump must join the first round's record"); assert_eq!(payments[0].id, id); assert!(matches!(payments[0].kind, PaymentKind::Onchain { txid: t, .. } if t == bump_txid)); - let entry = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("entry"); + let entry = entry_of(&wallet, &id).await.expect("entry"); assert_eq!( entry.candidates().iter().map(|c| c.txid).collect::>(), vec![txid, bump_txid] @@ -7028,35 +7046,16 @@ mod tests { let bump_id = wallet.find_payment_by_txid(bump_txid).await.unwrap().expect("a record"); assert_ne!(bump_id, failed_id); - let payment = - wallet.payment_stores.payment_store().get(&bump_id).await.unwrap().expect("record"); + let payment = record_of(&wallet, &bump_id).await.expect("record"); assert_eq!(payment.status, PaymentStatus::Pending); assert!(matches!(payment.kind, PaymentKind::Onchain { txid: t, .. } if t == bump_txid)); - let entry = wallet - .payment_stores - .pending_payment_store() - .get(&bump_id) - .await - .unwrap() - .expect("entry"); + let entry = entry_of(&wallet, &bump_id).await.expect("entry"); assert_eq!(entry.details(), Some(&payment)); assert!(entry.candidate(bump_txid).expect("candidate").awaiting_broadcast); - let failed = wallet - .payment_stores - .payment_store() - .get(&failed_id) - .await - .unwrap() - .expect("the failed record stays"); + let failed = record_of(&wallet, &failed_id).await.expect("the failed record stays"); assert_eq!(failed.status, PaymentStatus::Failed); assert!(matches!(failed.kind, PaymentKind::Onchain { txid: t, .. } if t == txid)); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&failed_id) - .await - .unwrap() - .is_none()); + assert!(entry_of(&wallet, &failed_id).await.is_none()); } /// The bump's history carries a round this node contributed nothing to over from the failed @@ -7118,13 +7117,7 @@ mod tests { .local_figures .expect("figures"); assert_eq!(figures.funding_payment_id, failed_id); - let entry = wallet - .payment_stores - .pending_payment_store() - .get(&bump_id) - .await - .unwrap() - .expect("entry"); + let entry = entry_of(&wallet, &bump_id).await.expect("entry"); assert!(entry.candidate(counterparty_txid).is_some()); } @@ -7147,17 +7140,14 @@ mod tests { ); sign_and_observe_round(&wallet, &tx, &candidates).await; let id = wallet.find_payment_by_txid(prior_txid).await.unwrap().expect("id"); - let payment = - wallet.payment_stores.payment_store().get(&id).await.unwrap().expect("payment"); - let record = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("record"); + let payment = record_of(&wallet, &id).await.expect("payment"); + let record = entry_of(&wallet, &id).await.expect("record"); assert!(record.candidate(txid).unwrap().awaiting_broadcast); wallet.record_broadcast_splice_round(channel_id, txid).await.unwrap(); - assert_eq!(wallet.payment_stores.payment_store().get(&id).await.unwrap(), Some(payment)); - let record = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("record"); + assert_eq!(record_of(&wallet, &id).await, Some(payment)); + let record = entry_of(&wallet, &id).await.expect("record"); assert_eq!( record.candidates().iter().map(|c| c.txid).collect::>(), vec![prior_txid, txid] @@ -7389,8 +7379,7 @@ mod tests { matches!(&payments[0].kind, PaymentKind::Onchain { txid: t, .. } if *t == next_txid) ); assert_eq!(payments[0].amount_msat, Some(400_700_000)); - let record = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("record"); + let record = entry_of(&wallet, &id).await.expect("record"); assert_eq!( record.candidates().iter().map(|c| c.txid).collect::>(), vec![prior_txid, txid, next_txid] @@ -7428,19 +7417,13 @@ mod tests { wallet.drop_abandoned_splice_rounds(channel_id, &[]).await.unwrap(); - assert!(wallet.payment_stores.payment_store().get(&id).await.unwrap().is_none()); - assert!(wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_none()); + assert!(record_of(&wallet, &id).await.is_none()); + assert!(entry_of(&wallet, &id).await.is_none()); // The round's provenance fact outlives the drop — it says what the transaction would have // been, which a drop does not change — so the txid still identifies the payment it belonged // to, and the stores no longer have a record under that payment. assert_eq!(wallet.find_payment_by_txid(txid).await.unwrap(), Some(id)); - let other = wallet - .payment_stores - .pending_payment_store() - .get(&other_id) - .await - .unwrap() - .expect("the other channel's entry stays"); + let other = entry_of(&wallet, &other_id).await.expect("the other channel's entry stays"); assert!(other.candidate(other_txid).is_some()); assert_eq!(wallet.find_payment_by_txid(other_txid).await.unwrap(), Some(other_id)); } @@ -7472,17 +7455,14 @@ mod tests { ); wallet.record_signed_funding(&bump_tx, &bump_candidates).await.unwrap(); record_unseen_round(&wallet, &bump_tx).await; - let payment = - wallet.payment_stores.payment_store().get(&id).await.unwrap().expect("payment"); + let payment = record_of(&wallet, &id).await.expect("payment"); assert!(matches!(payment.kind, PaymentKind::Onchain { txid: t, .. } if t == bump_txid)); wallet.drop_abandoned_splice_rounds(channel_id, &[txid]).await.unwrap(); - let record = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("record"); + let record = entry_of(&wallet, &id).await.expect("record"); assert_eq!(record.candidates().iter().map(|c| c.txid).collect::>(), vec![txid]); - let payment = - wallet.payment_stores.payment_store().get(&id).await.unwrap().expect("payment"); + let payment = record_of(&wallet, &id).await.expect("payment"); assert!( matches!(payment.kind, PaymentKind::Onchain { txid: t, .. } if t == txid), "the original round must be the actively-tracked transaction again" @@ -7514,11 +7494,9 @@ mod tests { wallet.drop_abandoned_splice_rounds(channel_id, &[]).await.unwrap(); - let record = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("record"); + let record = entry_of(&wallet, &id).await.expect("record"); assert_eq!(record.candidates().iter().map(|c| c.txid).collect::>(), vec![txid]); - let payment = - wallet.payment_stores.payment_store().get(&id).await.unwrap().expect("payment"); + let payment = record_of(&wallet, &id).await.expect("payment"); assert!(matches!(payment.kind, PaymentKind::Onchain { txid: t, .. } if t == txid)); assert_eq!(payment.status, PaymentStatus::Pending); } @@ -7555,15 +7533,14 @@ mod tests { wallet.drop_abandoned_splice_rounds(channel_id, &[]).await.unwrap(); - let record = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("record"); + let record = entry_of(&wallet, &id).await.expect("record"); assert_eq!(record.candidates().iter().map(|c| c.txid).collect::>(), vec![txid]); let kept = record.candidate(txid).expect("the negotiated round keeps its place"); assert_eq!(kept.amount_msat, Some(500_300_000)); assert_eq!(kept.fee_paid_msat, Some(300_000)); assert!(!kept.awaiting_broadcast); // Wallet sync has not picked the round up, so there is no payment record either way. - assert!(wallet.payment_stores.payment_store().get(&id).await.unwrap().is_none()); + assert!(record_of(&wallet, &id).await.is_none()); } /// LDK abandoned the only round this node contributed to, an RBF of a counterparty-initiated @@ -7586,12 +7563,12 @@ mod tests { wallet.record_signed_funding(&tx, &candidates).await.unwrap(); record_unseen_round(&wallet, &tx).await; let id = wallet.find_payment_by_txid(prior_txid).await.unwrap().expect("id"); - assert!(wallet.payment_stores.payment_store().get(&id).await.unwrap().is_some()); + assert!(record_of(&wallet, &id).await.is_some()); wallet.drop_abandoned_splice_rounds(channel_id, &[prior_txid]).await.unwrap(); - assert!(wallet.payment_stores.payment_store().get(&id).await.unwrap().is_none()); - assert!(wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_none()); + assert!(record_of(&wallet, &id).await.is_none()); + assert!(entry_of(&wallet, &id).await.is_none()); } /// LDK abandoned the only round this node contributed to, an RBF of a counterparty-initiated @@ -7610,12 +7587,8 @@ mod tests { let counterparty_txid = counterparty_tx.compute_txid(); observe_unconfirmed(&wallet, &counterparty_tx).await; let observed_id = PaymentId(counterparty_txid.to_byte_array()); - let observed = wallet - .payment_stores - .payment_store() - .get(&observed_id) + let observed = record_of(&wallet, &observed_id) .await - .unwrap() .expect("wallet sync recorded the counterparty's round"); let (tx, contribution) = splice_out_round(&wallet, 2, 499_000, 700); @@ -7631,11 +7604,10 @@ mod tests { wallet.drop_abandoned_splice_rounds(channel_id, &[counterparty_txid]).await.unwrap(); - let kept = wallet.payment_stores.payment_store().get(&id).await.unwrap().expect("kept"); + let kept = record_of(&wallet, &id).await.expect("kept"); assert_eq!(kept.amount_msat, observed.amount_msat); assert_eq!(kept.direction, observed.direction); - let entry = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("entry"); + let entry = entry_of(&wallet, &id).await.expect("entry"); assert!(entry.candidates().is_empty()); assert!(entry.funding_channels().is_empty()); assert!(wallet @@ -7690,8 +7662,7 @@ mod tests { .unwrap(); observe_unconfirmed(&wallet, &counterparty_tx).await; let id = PaymentId(counterparty_txid.to_byte_array()); - let observed = - wallet.payment_stores.payment_store().get(&id).await.unwrap().expect("observed"); + let observed = record_of(&wallet, &id).await.expect("observed"); assert!(matches!( observed.kind, PaymentKind::Onchain { tx_type: Some(TransactionType::InteractiveFunding { .. }), .. } @@ -7761,8 +7732,7 @@ mod tests { wallet.onchain_payment_fields_locked(&locked_wallet, &second_tx) }; observe_unconfirmed(&wallet, &second_tx).await; - let replaced = - wallet.payment_stores.payment_store().get(&id).await.unwrap().expect("record"); + let replaced = record_of(&wallet, &id).await.expect("record"); assert_eq!(replaced.amount_msat, amount_msat); assert_eq!(replaced.fee_paid_msat, fee_paid_msat); assert!(matches!(replaced.kind, PaymentKind::Onchain { txid, .. } if txid == second_txid)); @@ -7864,7 +7834,7 @@ mod tests { wallet.drop_abandoned_splice_rounds(channel_id, &[counterparty_txid]).await.unwrap(); - assert!(wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_none()); + assert!(entry_of(&wallet, &id).await.is_none()); assert!(wallet .channel_tx_facts(&counterparty_txid) .await @@ -7924,8 +7894,7 @@ mod tests { old_block_time: None, }; wallet.update_payment_store(vec![event]).await.unwrap(); - let payment = - wallet.payment_stores.payment_store().get(&id).await.unwrap().expect("payment"); + let payment = record_of(&wallet, &id).await.expect("payment"); assert!(matches!( payment.kind, PaymentKind::Onchain { txid: t, status: ConfirmationStatus::Confirmed { .. }, .. } @@ -7934,12 +7903,8 @@ mod tests { wallet.drop_abandoned_splice_rounds(channel_id, &[txid]).await.unwrap(); - assert_eq!( - wallet.payment_stores.payment_store().get(&id).await.unwrap(), - Some(payment.clone()) - ); - let record = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("record"); + assert_eq!(record_of(&wallet, &id).await, Some(payment.clone())); + let record = entry_of(&wallet, &id).await.expect("record"); assert_eq!(record.candidates().iter().map(|c| c.txid).collect::>(), vec![txid]); assert_eq!(record.details(), Some(&payment)); assert!(record.candidate(bump_txid).is_none()); @@ -7968,17 +7933,12 @@ mod tests { let mut moved_on = PaymentDetailsUpdate::new(id); moved_on.txid = Some(bump_txid); wallet.payment_stores.payment_store().update(moved_on).await.unwrap(); - let payment = - wallet.payment_stores.payment_store().get(&id).await.unwrap().expect("payment"); + let payment = record_of(&wallet, &id).await.expect("payment"); wallet.drop_abandoned_splice_rounds(channel_id, &[]).await.unwrap(); - assert_eq!( - wallet.payment_stores.payment_store().get(&id).await.unwrap(), - Some(payment.clone()) - ); - let record = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("record"); + assert_eq!(record_of(&wallet, &id).await, Some(payment.clone())); + let record = entry_of(&wallet, &id).await.expect("record"); assert!(record.candidates().is_empty()); assert_eq!(record.details(), Some(&payment)); } @@ -8000,11 +7960,11 @@ mod tests { record_unseen_round(&wallet, &tx).await; let id = wallet.find_payment_by_txid(txid).await.unwrap().expect("id"); wallet.payment_stores.payment_store().remove(&id).await.unwrap(); - assert!(wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_some()); + assert!(entry_of(&wallet, &id).await.is_some()); wallet.drop_abandoned_splice_rounds(channel_id, &[]).await.unwrap(); - assert!(wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_none()); + assert!(entry_of(&wallet, &id).await.is_none()); } /// A hand-back that was cut short between the two stores — the payment record tracks the @@ -8043,8 +8003,7 @@ mod tests { update.amount_msat = Some(Some(500_300_000)); update.fee_paid_msat = Some(Some(300_000)); wallet.payment_stores.payment_store().update(update).await.unwrap(); - let entry = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("entry"); + let entry = entry_of(&wallet, &id).await.expect("entry"); assert!(matches!( entry.details().map(|details| &details.kind), Some(PaymentKind::Onchain { txid: t, .. }) if *t == bump_txid @@ -8052,11 +8011,9 @@ mod tests { wallet.drop_abandoned_splice_rounds(channel_id, &[txid]).await.unwrap(); - let entry = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("entry"); + let entry = entry_of(&wallet, &id).await.expect("entry"); assert_eq!(entry.candidates().iter().map(|c| c.txid).collect::>(), vec![txid]); - let payment = - wallet.payment_stores.payment_store().get(&id).await.unwrap().expect("payment"); + let payment = record_of(&wallet, &id).await.expect("payment"); assert!(matches!(payment.kind, PaymentKind::Onchain { txid: t, .. } if t == txid)); assert_eq!(payment.amount_msat, Some(500_300_000)); assert_eq!(entry.details(), Some(&payment)); @@ -8168,24 +8125,12 @@ mod tests { .await .unwrap(); - assert!(wallet.payment_stores.payment_store().get(&id).await.unwrap().is_none()); - assert!(wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_none()); - assert!(wallet.payment_stores.payment_store().get(&other_id).await.unwrap().is_some()); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&other_id) - .await - .unwrap() - .is_some()); - assert!(wallet.payment_stores.payment_store().get(&closed_id).await.unwrap().is_some()); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&closed_id) - .await - .unwrap() - .is_some()); + assert!(record_of(&wallet, &id).await.is_none()); + assert!(entry_of(&wallet, &id).await.is_none()); + assert!(record_of(&wallet, &other_id).await.is_some()); + assert!(entry_of(&wallet, &other_id).await.is_some()); + assert!(record_of(&wallet, &closed_id).await.is_some()); + assert!(entry_of(&wallet, &closed_id).await.is_some()); } /// A record that graduated while its pending entry lingers — the entry's removal is still @@ -8223,12 +8168,10 @@ mod tests { wallet.drop_abandoned_splice_rounds(channel_id, &[txid]).await.unwrap(); - let payment = - wallet.payment_stores.payment_store().get(&id).await.unwrap().expect("payment"); + let payment = record_of(&wallet, &id).await.expect("payment"); assert_eq!(payment.status, PaymentStatus::Succeeded); assert!(matches!(payment.kind, PaymentKind::Onchain { txid: t, .. } if t == bump_txid)); - let entry = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("entry"); + let entry = entry_of(&wallet, &id).await.expect("entry"); assert_eq!(entry.candidates().iter().map(|c| c.txid).collect::>(), vec![txid]); assert_eq!(entry.details().map(|details| details.status), Some(PaymentStatus::Pending)); } @@ -8263,19 +8206,17 @@ mod tests { // The round's facts landed before the entry, so the transaction identifies its payment // already, before any entry tracks it. let id = wallet.find_payment_by_txid(txid).await.unwrap().expect("id"); - assert!(wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_none()); + assert!(entry_of(&wallet, &id).await.is_none()); fail_store.fail_writes.store(false, Ordering::Release); wallet.record_signed_funding(&tx, &candidates).await.unwrap(); assert_eq!(wallet.find_payment_by_txid(txid).await.unwrap(), Some(id)); - let record = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("record"); + let record = entry_of(&wallet, &id).await.expect("record"); assert_eq!(record.candidates().iter().map(|c| c.txid).collect::>(), vec![txid]); assert!(record.candidate(txid).expect("candidate").awaiting_broadcast); // Wallet sync creates the payment record when it observes the transaction. observe_unconfirmed(&wallet, &tx).await; - let payment = - wallet.payment_stores.payment_store().get(&id).await.unwrap().expect("payment"); + let payment = record_of(&wallet, &id).await.expect("payment"); assert!(matches!(payment.kind, PaymentKind::Onchain { txid: t, .. } if t == txid)); } @@ -8298,7 +8239,7 @@ mod tests { ); sign_and_observe_round(&wallet, &tx, &candidates).await; let id = wallet.find_payment_by_txid(txid).await.unwrap().expect("id"); - let prior = wallet.payment_stores.payment_store().get(&id).await.unwrap().expect("payment"); + let prior = record_of(&wallet, &id).await.expect("payment"); let (bump_tx, bump_contribution) = splice_out_round(&wallet, 2, 499_000, 700); let bump_txid = bump_tx.compute_txid(); @@ -8312,11 +8253,10 @@ mod tests { assert!(wallet.record_signed_funding(&bump_tx, &bump_candidates).await.is_err()); assert_eq!(fail_store.failed_writes.load(Ordering::Acquire), 1); - assert_eq!(wallet.payment_stores.payment_store().get(&id).await.unwrap(), Some(prior)); - let record = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("record"); + assert_eq!(record_of(&wallet, &id).await, Some(prior)); + let record = entry_of(&wallet, &id).await.expect("record"); assert_eq!(record.candidates().iter().map(|c| c.txid).collect::>(), vec![txid]); - assert!(wallet.payment_stores.payment_store().get(&bump_id).await.unwrap().is_none()); + assert!(record_of(&wallet, &bump_id).await.is_none()); } /// The candidates handed to the signing-time recording are the channel's pending splice @@ -8413,8 +8353,7 @@ mod tests { let event = WalletEvent::ChainTipChanged { old_tip: block_id(9), new_tip: block_id(10) }; wallet.update_payment_store(vec![event]).await.unwrap(); - let payment = - wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().unwrap(); + let payment = record_of(&wallet, &payment_id).await.unwrap(); assert_eq!(payment.status, PaymentStatus::Succeeded); assert_eq!( payment.amount_msat, @@ -8423,13 +8362,7 @@ mod tests { ); assert_eq!(payment.fee_paid_msat, Some(999)); assert!(payment.latest_update_timestamp > 0, "the graduation write must timestamp"); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&payment_id) - .await - .unwrap() - .is_none()); + assert!(entry_of(&wallet, &payment_id).await.is_none()); } /// When the live record has diverged from the pending-store snapshot — here the snapshot @@ -8470,8 +8403,7 @@ mod tests { let event = WalletEvent::ChainTipChanged { old_tip: block_id(9), new_tip: block_id(10) }; wallet.update_payment_store(vec![event]).await.unwrap(); - let payment = - wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().unwrap(); + let payment = record_of(&wallet, &payment_id).await.unwrap(); assert_eq!( payment.status, PaymentStatus::Pending, @@ -8482,7 +8414,7 @@ mod tests { PaymentKind::Onchain { status: ConfirmationStatus::Unconfirmed, .. } )); assert!( - wallet.payment_stores.pending_payment_store().get(&payment_id).await.unwrap().is_some(), + entry_of(&wallet, &payment_id).await.is_some(), "the entry must survive for future events to drive" ); } @@ -8553,20 +8485,12 @@ mod tests { PaymentDirection::Outbound, PaymentStatus::Pending, ); - wallet.payment_stores.payment_store().insert_or_update(details.clone()).await.unwrap(); - let entry = PendingPaymentDetails::new(details, vec![conflicting_txid], Vec::new()); - wallet.payment_stores.pending_payment_store().insert_or_update(entry).await.unwrap(); + track_pending(&wallet, details, vec![conflicting_txid]).await; wallet.remove_payment(&payment_id).await.unwrap(); - assert!(wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().is_none()); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&payment_id) - .await - .unwrap() - .is_none()); + assert!(record_of(&wallet, &payment_id).await.is_none()); + assert!(entry_of(&wallet, &payment_id).await.is_none()); assert_eq!(wallet.find_payment_by_txid(txid).await.unwrap(), None); assert_eq!(wallet.find_payment_by_txid(conflicting_txid).await.unwrap(), None); @@ -8578,7 +8502,7 @@ mod tests { conflicts: vec![(0, conflicting_txid)], }; wallet.update_payment_store(vec![event]).await.unwrap(); - assert!(wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().is_none()); + assert!(record_of(&wallet, &payment_id).await.is_none()); } /// A round's facts identify its payment for as long as they are kept, which outlasts the @@ -8604,7 +8528,7 @@ mod tests { .await .unwrap() .expect("the round identifies its payment"); - assert!(wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().is_some()); + assert!(record_of(&wallet, &payment_id).await.is_some()); wallet.remove_payment(&payment_id).await.unwrap(); assert_eq!( @@ -8633,16 +8557,10 @@ mod tests { wallet.update_payment_store(events).await.unwrap(); assert!( - wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().is_none(), + record_of(&wallet, &payment_id).await.is_none(), "a removed payment must not come back", ); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&payment_id) - .await - .unwrap() - .is_none()); + assert!(entry_of(&wallet, &payment_id).await.is_none()); assert!( wallet .payment_stores @@ -8680,7 +8598,7 @@ mod tests { wallet.payment_stores.payment_store().insert_or_update(details).await.unwrap(); wallet.remove_payment(&payment_id).await.unwrap(); - assert!(wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().is_none()); + assert!(record_of(&wallet, &payment_id).await.is_none()); // Removing an id known to neither store is also a no-op rather than an error. wallet.remove_payment(&PaymentId([8u8; 32])).await.unwrap(); @@ -8733,17 +8651,7 @@ mod tests { wallet.record_funding_payment(details, candidates).await.unwrap(); // Sync saw the close double-spend the splice's funding transaction. - wallet - .payment_stores - .pending_payment_store() - .update(PendingPaymentDetailsUpdate { - id: payment_id, - payment_update: None, - conflicting_txids: Some(vec![close_txid]), - candidates: Vec::new(), - }) - .await - .unwrap(); + set_conflicts(&wallet, payment_id, vec![close_txid]).await; let event = WalletEvent::TxConfirmed { txid: close_txid, @@ -8753,8 +8661,7 @@ mod tests { }; wallet.update_payment_store(vec![event]).await.unwrap(); - let funding = - wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().unwrap(); + let funding = record_of(&wallet, &payment_id).await.unwrap(); match &funding.kind { PaymentKind::Onchain { txid, status, tx_type } => { assert_eq!(*txid, splice_txid, "the record must not adopt the close's txid"); @@ -8858,20 +8765,7 @@ mod tests { PaymentDirection::Inbound, PaymentStatus::Pending, ); - wallet - .payment_stores - .payment_store() - .insert_or_update(close_details.clone()) - .await - .unwrap(); - let entry = - PendingPaymentDetails::new(close_details, vec![splice_txid], Vec::new()); - wallet - .payment_stores - .pending_payment_store() - .insert_or_update(entry) - .await - .unwrap(); + track_pending(&wallet, close_details, vec![splice_txid]).await; } assert_eq!( @@ -8888,8 +8782,7 @@ mod tests { }; wallet.update_payment_store(vec![event]).await.unwrap(); - let funding = - wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().unwrap(); + let funding = record_of(&wallet, &payment_id).await.unwrap(); match &funding.kind { PaymentKind::Onchain { txid, status, tx_type } => { assert_eq!(*txid, splice_txid); @@ -8951,17 +8844,7 @@ mod tests { let details = interactive_funding_details(payment_id, splice_txid, Some(1_000_000), Some(500)); wallet.record_funding_payment(details, candidates).await.unwrap(); - wallet - .payment_stores - .pending_payment_store() - .update(PendingPaymentDetailsUpdate { - id: payment_id, - payment_update: None, - conflicting_txids: Some(vec![close_txid]), - candidates: Vec::new(), - }) - .await - .unwrap(); + set_conflicts(&wallet, payment_id, vec![close_txid]).await; // The round was seen in the mempool; the close is canonically confirmed, so the round, // having lost the conflict, is no longer canonical. @@ -8976,8 +8859,7 @@ mod tests { }; wallet.update_payment_store(vec![event]).await.unwrap(); - let payment = - wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().unwrap(); + let payment = record_of(&wallet, &payment_id).await.unwrap(); assert_eq!(payment.status, PaymentStatus::Failed); match &payment.kind { PaymentKind::Onchain { txid, status, tx_type } => { @@ -8990,7 +8872,7 @@ mod tests { assert_eq!(payment.amount_msat, Some(1_000_000)); assert_eq!(payment.fee_paid_msat, Some(500)); assert!( - wallet.payment_stores.pending_payment_store().get(&payment_id).await.unwrap().is_none(), + entry_of(&wallet, &payment_id).await.is_none(), "the entry must go so the lost transaction stops being rebroadcast" ); } @@ -9036,17 +8918,7 @@ mod tests { // depth, while the second round merely drops out of the mempool. let close_tx = wallet_paying_tx(&wallet, 1); let close_txid = close_tx.compute_txid(); - wallet - .payment_stores - .pending_payment_store() - .update(PendingPaymentDetailsUpdate { - id: payment_id, - payment_update: None, - conflicting_txids: Some(vec![close_txid]), - candidates: Vec::new(), - }) - .await - .unwrap(); + set_conflicts(&wallet, payment_id, vec![close_txid]).await; insert_confirmed_tx(&wallet, close_tx, 5); evict_tx(&wallet, second_txid); @@ -9058,11 +8930,9 @@ mod tests { }; wallet.update_payment_store(vec![event]).await.unwrap(); - let payment = - wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().unwrap(); + let payment = record_of(&wallet, &payment_id).await.unwrap(); assert_eq!(payment.status, PaymentStatus::Pending, "the evicted round can still confirm"); - let entry = - wallet.payment_stores.pending_payment_store().get(&payment_id).await.unwrap().unwrap(); + let entry = entry_of(&wallet, &payment_id).await.unwrap(); assert_eq!(entry.candidates().len(), 2, "both rounds stay on record"); // A second close spends the evicted round's input and confirms to depth too: no round @@ -9076,16 +8946,9 @@ mod tests { }; wallet.update_payment_store(vec![event]).await.unwrap(); - let payment = - wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().unwrap(); + let payment = record_of(&wallet, &payment_id).await.unwrap(); assert_eq!(payment.status, PaymentStatus::Failed); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&payment_id) - .await - .unwrap() - .is_none()); + assert!(entry_of(&wallet, &payment_id).await.is_none()); } /// A round the wallet never saw has not lost either: the wallet's graph learns a transaction @@ -9129,17 +8992,7 @@ mod tests { // anti-reorg depth. let close_tx = wallet_paying_tx(&wallet, 2); let close_txid = close_tx.compute_txid(); - wallet - .payment_stores - .pending_payment_store() - .update(PendingPaymentDetailsUpdate { - id: payment_id, - payment_update: None, - conflicting_txids: Some(vec![close_txid]), - candidates: Vec::new(), - }) - .await - .unwrap(); + set_conflicts(&wallet, payment_id, vec![close_txid]).await; insert_confirmed_tx(&wallet, close_tx, 5); let block_id = @@ -9150,11 +9003,9 @@ mod tests { }; wallet.update_payment_store(vec![event]).await.unwrap(); - let payment = - wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().unwrap(); + let payment = record_of(&wallet, &payment_id).await.unwrap(); assert_eq!(payment.status, PaymentStatus::Pending, "the unseen round can still confirm"); - let entry = - wallet.payment_stores.pending_payment_store().get(&payment_id).await.unwrap().unwrap(); + let entry = entry_of(&wallet, &payment_id).await.unwrap(); assert_eq!(entry.candidates.len(), 2, "both rounds stay on record"); // The first round turns up in the mempool, and a second close spends its input and @@ -9168,16 +9019,9 @@ mod tests { }; wallet.update_payment_store(vec![event]).await.unwrap(); - let payment = - wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().unwrap(); + let payment = record_of(&wallet, &payment_id).await.unwrap(); assert_eq!(payment.status, PaymentStatus::Failed); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&payment_id) - .await - .unwrap() - .is_none()); + assert!(entry_of(&wallet, &payment_id).await.is_none()); } /// An unseen round that confirms after all is adopted by its record like any other @@ -9214,17 +9058,7 @@ mod tests { let close_tx = wallet_paying_tx(&wallet, 2); let close_txid = close_tx.compute_txid(); - wallet - .payment_stores - .pending_payment_store() - .update(PendingPaymentDetailsUpdate { - id: payment_id, - payment_update: None, - conflicting_txids: Some(vec![close_txid]), - candidates: Vec::new(), - }) - .await - .unwrap(); + set_conflicts(&wallet, payment_id, vec![close_txid]).await; insert_confirmed_tx(&wallet, close_tx, 5); let block_id = @@ -9245,8 +9079,7 @@ mod tests { }; wallet.update_payment_store(vec![event]).await.unwrap(); - let payment = - wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().unwrap(); + let payment = record_of(&wallet, &payment_id).await.unwrap(); assert_eq!(payment.status, PaymentStatus::Pending); match &payment.kind { PaymentKind::Onchain { txid, status, tx_type } => { @@ -9267,8 +9100,7 @@ mod tests { .is_none(), "the round is not recorded a second time" ); - let entry = - wallet.payment_stores.pending_payment_store().get(&payment_id).await.unwrap().unwrap(); + let entry = entry_of(&wallet, &payment_id).await.unwrap(); assert!(matches!( entry.details().unwrap().kind, PaymentKind::Onchain { status: ConfirmationStatus::Confirmed { .. }, .. } @@ -9305,17 +9137,7 @@ mod tests { let details = interactive_funding_details(payment_id, splice_txid, Some(1_000_000), Some(500)); wallet.record_funding_payment(details, candidates).await.unwrap(); - wallet - .payment_stores - .pending_payment_store() - .update(PendingPaymentDetailsUpdate { - id: payment_id, - payment_update: None, - conflicting_txids: Some(vec![bumped_txid]), - candidates: Vec::new(), - }) - .await - .unwrap(); + set_conflicts(&wallet, payment_id, vec![bumped_txid]).await; insert_confirmed_tx(&wallet, bumped_tx, 5); @@ -9327,11 +9149,10 @@ mod tests { }; wallet.update_payment_store(vec![event]).await.unwrap(); - let payment = - wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().unwrap(); + let payment = record_of(&wallet, &payment_id).await.unwrap(); assert_eq!(payment.status, PaymentStatus::Pending); assert!( - wallet.payment_stores.pending_payment_store().get(&payment_id).await.unwrap().is_some(), + entry_of(&wallet, &payment_id).await.is_some(), "the entry must survive for classification to adopt the confirmed candidate" ); } @@ -9358,17 +9179,7 @@ mod tests { let details = interactive_funding_details(payment_id, splice_txid, Some(1_000_000), Some(500)); wallet.record_funding_payment(details, candidates).await.unwrap(); - wallet - .payment_stores - .pending_payment_store() - .update(PendingPaymentDetailsUpdate { - id: payment_id, - payment_update: None, - conflicting_txids: Some(vec![close_txid]), - candidates: Vec::new(), - }) - .await - .unwrap(); + set_conflicts(&wallet, payment_id, vec![close_txid]).await; insert_confirmed_tx(&wallet, close_tx, 5); @@ -9380,16 +9191,9 @@ mod tests { }; wallet.update_payment_store(vec![event]).await.unwrap(); - let payment = - wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().unwrap(); + let payment = record_of(&wallet, &payment_id).await.unwrap(); assert_eq!(payment.status, PaymentStatus::Pending); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&payment_id) - .await - .unwrap() - .is_some()); + assert!(entry_of(&wallet, &payment_id).await.is_some()); } /// A conflict may double-spend only one round of the negotiation — e.g. it shares an input @@ -9425,17 +9229,7 @@ mod tests { let details = interactive_funding_details(payment_id, splice_txid, Some(1_000_000), Some(500)); wallet.record_funding_payment(details, candidates).await.unwrap(); - wallet - .payment_stores - .pending_payment_store() - .update(PendingPaymentDetailsUpdate { - id: payment_id, - payment_update: None, - conflicting_txids: Some(vec![conflict_txid]), - candidates: Vec::new(), - }) - .await - .unwrap(); + set_conflicts(&wallet, payment_id, vec![conflict_txid]).await; insert_confirmed_tx(&wallet, conflict_tx, 5); insert_unconfirmed_tx(&wallet, live_candidate_tx); @@ -9448,11 +9242,10 @@ mod tests { }; wallet.update_payment_store(vec![event]).await.unwrap(); - let payment = - wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().unwrap(); + let payment = record_of(&wallet, &payment_id).await.unwrap(); assert_eq!(payment.status, PaymentStatus::Pending); assert!( - wallet.payment_stores.pending_payment_store().get(&payment_id).await.unwrap().is_some(), + entry_of(&wallet, &payment_id).await.is_some(), "a candidate can still confirm, so the record must stay pending" ); } @@ -9499,12 +9292,11 @@ mod tests { }; wallet.update_payment_store(vec![event]).await.unwrap(); - let payment = - wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().unwrap(); + let payment = record_of(&wallet, &payment_id).await.unwrap(); assert_eq!(payment.status, PaymentStatus::Failed); assert_eq!(payment.latest_update_timestamp, 7, "the repair pass must not rewrite"); assert!( - wallet.payment_stores.pending_payment_store().get(&payment_id).await.unwrap().is_none(), + entry_of(&wallet, &payment_id).await.is_none(), "the lingering entry must be removed" ); } @@ -9558,12 +9350,11 @@ mod tests { ]; wallet.update_payment_store(events).await.unwrap(); - let payment = - wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().unwrap(); + let payment = record_of(&wallet, &payment_id).await.unwrap(); assert_eq!(payment.status, PaymentStatus::Failed); assert_eq!(payment.latest_update_timestamp, 7, "the replay must not rewrite the record"); assert!( - wallet.payment_stores.pending_payment_store().get(&payment_id).await.unwrap().is_none(), + entry_of(&wallet, &payment_id).await.is_none(), "the replay must finish the interrupted entry removal" ); } @@ -9585,7 +9376,7 @@ mod tests { let reads = counting_store.reads(PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE) - reads_before; let payment_id = PaymentId(txid.to_byte_array()); - assert!(wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().is_some()); + assert!(record_of(&wallet, &payment_id).await.is_some()); assert_eq!(reads, 2, "recording an unknown transaction re-read the payment store"); } @@ -9616,18 +9407,11 @@ mod tests { WalletEvent::TxUnconfirmed { txid: r1, tx: Arc::new(dummy_tx()), old_block_time: None }; wallet.update_payment_store(vec![event]).await.unwrap(); - let payment = - wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().unwrap(); + let payment = record_of(&wallet, &payment_id).await.unwrap(); assert_eq!(payment.status, PaymentStatus::Failed, "the record must not resurrect"); assert!(matches!(payment.kind, PaymentKind::Onchain { txid, .. } if txid == r2)); assert_eq!(payment.latest_update_timestamp, 7); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&payment_id) - .await - .unwrap() - .is_none()); + assert!(entry_of(&wallet, &payment_id).await.is_none()); // ...and even confirms: the record settled as `Failed` and must stay that way. let event = WalletEvent::TxConfirmed { @@ -9638,18 +9422,11 @@ mod tests { }; wallet.update_payment_store(vec![event]).await.unwrap(); - let payment = - wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().unwrap(); + let payment = record_of(&wallet, &payment_id).await.unwrap(); assert_eq!(payment.status, PaymentStatus::Failed, "the record must not resurrect"); assert!(matches!(payment.kind, PaymentKind::Onchain { txid, .. } if txid == r2)); assert_eq!(payment.latest_update_timestamp, 7); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&payment_id) - .await - .unwrap() - .is_none()); + assert!(entry_of(&wallet, &payment_id).await.is_none()); } /// The same collision through a conflict list: a pending entry listing a settled funding @@ -9673,31 +9450,18 @@ mod tests { let r2 = Txid::from_byte_array([4u8; 32]); let live_id = PaymentId(r2.to_byte_array()); let live = interactive_funding_details(live_id, r2, Some(2_000_000), Some(700)); - wallet.payment_stores.payment_store().insert_or_update(live.clone()).await.unwrap(); - wallet - .payment_stores - .pending_payment_store() - .insert_or_update(PendingPaymentDetails::new(live.clone(), vec![r1], Vec::new())) - .await - .unwrap(); + track_pending(&wallet, live.clone(), vec![r1]).await; assert_eq!(wallet.find_payment_by_txid(r1).await.unwrap(), Some(live_id)); let event = WalletEvent::TxUnconfirmed { txid: r1, tx: Arc::new(dummy_tx()), old_block_time: None }; wallet.update_payment_store(vec![event]).await.unwrap(); - let payment = - wallet.payment_stores.payment_store().get(&settled_id).await.unwrap().unwrap(); + let payment = record_of(&wallet, &settled_id).await.unwrap(); assert_eq!(payment.status, PaymentStatus::Failed, "the settled record must not resurrect"); assert_eq!(payment.latest_update_timestamp, 7); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&settled_id) - .await - .unwrap() - .is_none()); - assert_eq!(wallet.payment_stores.payment_store().get(&live_id).await.unwrap(), Some(live)); + assert!(entry_of(&wallet, &settled_id).await.is_none()); + assert_eq!(record_of(&wallet, &live_id).await, Some(live)); } /// The failure transition must apply regardless of the payment's direction: a splice-out @@ -9725,17 +9489,7 @@ mod tests { interactive_funding_details(payment_id, splice_txid, Some(1_000_000), Some(500)); details.direction = PaymentDirection::Inbound; wallet.record_funding_payment(details, candidates).await.unwrap(); - wallet - .payment_stores - .pending_payment_store() - .update(PendingPaymentDetailsUpdate { - id: payment_id, - payment_update: None, - conflicting_txids: Some(vec![close_txid]), - candidates: Vec::new(), - }) - .await - .unwrap(); + set_conflicts(&wallet, payment_id, vec![close_txid]).await; insert_unconfirmed_tx(&wallet, splice_tx); insert_confirmed_tx(&wallet, close_tx, 5); @@ -9748,16 +9502,9 @@ mod tests { }; wallet.update_payment_store(vec![event]).await.unwrap(); - let payment = - wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().unwrap(); + let payment = record_of(&wallet, &payment_id).await.unwrap(); assert_eq!(payment.status, PaymentStatus::Failed); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&payment_id) - .await - .unwrap() - .is_none()); + assert!(entry_of(&wallet, &payment_id).await.is_none()); } /// Wallet sync can record a genuine replacement round before it is recorded as a candidate: @@ -9797,13 +9544,7 @@ mod tests { PaymentDirection::Outbound, PaymentStatus::Pending, ); - wallet.payment_stores.payment_store().insert_or_update(duplicate.clone()).await.unwrap(); - wallet - .payment_stores - .pending_payment_store() - .insert_or_update(PendingPaymentDetails::new(duplicate, Vec::new(), Vec::new())) - .await - .unwrap(); + track_pending(&wallet, duplicate, Vec::new()).await; assert_eq!(wallet.find_payment_by_txid(txid2).await.unwrap(), Some(duplicate_id)); // Round 2 is recorded as a candidate, with the history of a later round this node signs. @@ -9841,13 +9582,7 @@ mod tests { } => assert_eq!(*txid, txid2), kind => panic!("unexpected kind {:?}", kind), } - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&duplicate_id) - .await - .unwrap() - .is_none()); + assert!(entry_of(&wallet, &duplicate_id).await.is_none()); assert_eq!(wallet.find_payment_by_txid(txid2).await.unwrap(), Some(funding_id)); } @@ -9877,13 +9612,7 @@ mod tests { PaymentDirection::Outbound, PaymentStatus::Pending, ); - wallet.payment_stores.payment_store().insert_or_update(duplicate.clone()).await.unwrap(); - wallet - .payment_stores - .pending_payment_store() - .insert_or_update(PendingPaymentDetails::new(duplicate, Vec::new(), Vec::new())) - .await - .unwrap(); + track_pending(&wallet, duplicate, Vec::new()).await; // Round 2 is the active broadcast; its record lists both rounds. let rounds = vec![ @@ -9970,13 +9699,7 @@ mod tests { let details = interactive_funding_details(funding_id, txid2, Some(1_000_000), Some(400)); wallet.record_funding_payment(details, rounds).await.unwrap(); - let failed = wallet - .payment_stores - .payment_store() - .get(&duplicate_id) - .await - .unwrap() - .expect("the failed record stays"); + let failed = record_of(&wallet, &duplicate_id).await.expect("the failed record stays"); assert_eq!(failed.status, PaymentStatus::Failed); let payments = wallet.payment_stores.payment_store().list_page(None).await.unwrap().objects; assert_eq!(payments.len(), 2, "the funding record is added beside the failed one"); @@ -10020,13 +9743,7 @@ mod tests { PaymentDirection::Outbound, PaymentStatus::Pending, ); - wallet.payment_stores.payment_store().insert_or_update(duplicate.clone()).await.unwrap(); - wallet - .payment_stores - .pending_payment_store() - .insert_or_update(PendingPaymentDetails::new(duplicate, Vec::new(), Vec::new())) - .await - .unwrap(); + track_pending(&wallet, duplicate, Vec::new()).await; // Round 2 is recorded as a candidate, but one of the duplicate's two removals fails. let rounds = vec![ @@ -10054,13 +9771,7 @@ mod tests { let payments = wallet.payment_stores.payment_store().list_page(None).await.unwrap().objects; assert_eq!(payments.len(), 1, "the duplicate must be merged away"); assert_eq!(payments[0].id, funding_id); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&duplicate_id) - .await - .unwrap() - .is_none()); + assert!(entry_of(&wallet, &duplicate_id).await.is_none()); assert_eq!(wallet.find_payment_by_txid(txid2).await.unwrap(), Some(funding_id)); } @@ -10087,7 +9798,7 @@ mod tests { for candidate in candidates.iter().filter(|candidate| candidate.txid != txid) { assert!(wallet.channel_tx_facts(&candidate.txid).await.is_none()); } - assert!(wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_none()); + assert!(entry_of(&wallet, &id).await.is_none()); id } @@ -10132,7 +9843,7 @@ mod tests { wallet.update_payment_store(vec![event]).await.unwrap(); let duplicate_id = PaymentId(counterparty_txid.to_byte_array()); assert_ne!(duplicate_id, id); - assert!(wallet.payment_stores.payment_store().get(&duplicate_id).await.unwrap().is_some()); + assert!(record_of(&wallet, &duplicate_id).await.is_some()); wallet.record_signed_funding(&tx, &candidates).await.unwrap(); @@ -10149,16 +9860,9 @@ mod tests { assert_eq!(payment.amount_msat, amount_msat); assert_eq!(payment.fee_paid_msat, fee_paid_msat); assert_eq!(payment.direction, direction); - let entry = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("entry"); + let entry = entry_of(&wallet, &id).await.expect("entry"); assert_eq!(entry.details(), Some(payment)); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&duplicate_id) - .await - .unwrap() - .is_none()); + assert!(entry_of(&wallet, &duplicate_id).await.is_none()); assert_eq!(wallet.find_payment_by_txid(counterparty_txid).await.unwrap(), Some(id)); } @@ -10191,7 +9895,7 @@ mod tests { observe_unconfirmed(&wallet, &counterparty_tx).await; let duplicate_id = PaymentId(counterparty_txid.to_byte_array()); assert_ne!(id, duplicate_id); - assert!(wallet.payment_stores.payment_store().get(&duplicate_id).await.unwrap().is_some()); + assert!(record_of(&wallet, &duplicate_id).await.is_some()); // The replay completes the write and merges the duplicate away; our round is not // observed, so no payment record exists under the payment's id. @@ -10204,16 +9908,9 @@ mod tests { .unwrap() .objects .is_empty()); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&duplicate_id) - .await - .unwrap() - .is_none()); + assert!(entry_of(&wallet, &duplicate_id).await.is_none()); assert_eq!(wallet.find_payment_by_txid(counterparty_txid).await.unwrap(), Some(id)); - let entry = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("entry"); + let entry = entry_of(&wallet, &id).await.expect("entry"); assert!(entry.candidate(counterparty_txid).is_some()); // A replacement or eviction of the counterparty's round is harmless without a record. @@ -10254,10 +9951,9 @@ mod tests { "{:?}", payments[0].kind ); - let entry = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("entry"); + let entry = entry_of(&wallet, &id).await.expect("entry"); assert_eq!(entry.details(), Some(&payments[0])); - assert!(wallet.payment_stores.payment_store().get(&duplicate_id).await.unwrap().is_none()); + assert!(record_of(&wallet, &duplicate_id).await.is_none()); } /// A counterparty round's record is classified as an interactive funding by the facts its @@ -10297,13 +9993,7 @@ mod tests { observe_unconfirmed(&wallet, &counterparty_tx).await; let duplicate_id = PaymentId(counterparty_txid.to_byte_array()); assert_ne!(duplicate_id, id); - let duplicate = wallet - .payment_stores - .payment_store() - .get(&duplicate_id) - .await - .unwrap() - .expect("a record of its own"); + let duplicate = record_of(&wallet, &duplicate_id).await.expect("a record of its own"); assert!(matches!( duplicate.kind, PaymentKind::Onchain { tx_type: Some(TransactionType::InteractiveFunding { .. }), .. } @@ -10321,16 +10011,10 @@ mod tests { assert_eq!(wallet.find_payment_by_txid(counterparty_txid).await.unwrap(), Some(id)); assert!( - wallet.payment_stores.payment_store().get(&duplicate_id).await.unwrap().is_none(), + record_of(&wallet, &duplicate_id).await.is_none(), "the duplicate must be merged away" ); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&duplicate_id) - .await - .unwrap() - .is_none()); + assert!(entry_of(&wallet, &duplicate_id).await.is_none()); let payments = wallet.payment_stores.payment_store().list_page(None).await.unwrap().objects; assert_eq!(payments.len(), 1); assert_eq!(payments[0].id, id); @@ -10381,12 +10065,8 @@ mod tests { wallet.update_payment_store(events).await.unwrap(); let duplicate_id = PaymentId(first_txid.to_byte_array()); assert_ne!(duplicate_id, id); - let duplicate = wallet - .payment_stores - .payment_store() - .get(&duplicate_id) + let duplicate = record_of(&wallet, &duplicate_id) .await - .unwrap() .expect("the replacement is filed under the first round's record"); assert!(matches!( duplicate.kind, @@ -10405,13 +10085,7 @@ mod tests { let payments = wallet.payment_stores.payment_store().list_page(None).await.unwrap().objects; assert_eq!(payments.len(), 1, "the duplicate must be merged away"); assert_eq!(payments[0].id, id); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&duplicate_id) - .await - .unwrap() - .is_none()); + assert!(entry_of(&wallet, &duplicate_id).await.is_none()); assert_eq!(wallet.find_payment_by_txid(first_txid).await.unwrap(), Some(id)); assert_eq!(wallet.find_payment_by_txid(replacement_txid).await.unwrap(), Some(id)); } @@ -10454,13 +10128,7 @@ mod tests { PaymentDirection::Outbound, PaymentStatus::Pending, ); - wallet.payment_stores.payment_store().insert_or_update(duplicate.clone()).await.unwrap(); - wallet - .payment_stores - .pending_payment_store() - .insert_or_update(PendingPaymentDetails::new(duplicate.clone(), Vec::new(), Vec::new())) - .await - .unwrap(); + track_pending(&wallet, duplicate.clone(), Vec::new()).await; // This node signs round 3, a bump of the replacement, but the duplicate's removal fails. let (bump_tx, bump_contribution) = splice_out_round(&wallet, 3, 499_000, 700); @@ -10478,8 +10146,7 @@ mod tests { wallet.record_signed_funding(&bump_tx, &bump_candidates).await.unwrap(); // The signing is recorded in full and the duplicate is left as it was. - let entry = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("entry"); + let entry = entry_of(&wallet, &id).await.expect("entry"); assert_eq!( entry.candidates().iter().map(|c| c.txid).collect::>(), vec![txid, replacement_txid, bump_txid] @@ -10487,34 +10154,18 @@ mod tests { assert!(entry.candidate(bump_txid).expect("candidate").awaiting_broadcast); // The signing writes no payment record: the one wallet sync made for the first round // still describes that round, and the entry still mirrors it. - let payment = - wallet.payment_stores.payment_store().get(&id).await.unwrap().expect("payment"); + let payment = record_of(&wallet, &id).await.expect("payment"); assert!(matches!(payment.kind, PaymentKind::Onchain { txid: t, .. } if t == txid)); assert_eq!(entry.details(), Some(&payment)); - assert_eq!( - wallet.payment_stores.payment_store().get(&duplicate_id).await.unwrap(), - Some(duplicate) - ); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&duplicate_id) - .await - .unwrap() - .is_some()); + assert_eq!(record_of(&wallet, &duplicate_id).await, Some(duplicate)); + assert!(entry_of(&wallet, &duplicate_id).await.is_some()); // The bump's `SpliceNegotiated` event merges the duplicate away. wallet.record_broadcast_splice_round(channel_id, bump_txid).await.unwrap(); let payments = wallet.payment_stores.payment_store().list_page(None).await.unwrap().objects; assert_eq!(payments.len(), 1, "the duplicate must be merged away"); assert_eq!(payments[0].id, id); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&duplicate_id) - .await - .unwrap() - .is_none()); + assert!(entry_of(&wallet, &duplicate_id).await.is_none()); assert_eq!(wallet.find_payment_by_txid(replacement_txid).await.unwrap(), Some(id)); } @@ -10557,13 +10208,7 @@ mod tests { PaymentDirection::Outbound, PaymentStatus::Pending, ); - wallet.payment_stores.payment_store().insert_or_update(duplicate.clone()).await.unwrap(); - wallet - .payment_stores - .pending_payment_store() - .insert_or_update(PendingPaymentDetails::new(duplicate.clone(), Vec::new(), Vec::new())) - .await - .unwrap(); + track_pending(&wallet, duplicate.clone(), Vec::new()).await; let (bump_tx, bump_contribution) = splice_out_round(&wallet, 3, 499_000, 700); let bump_txid = bump_tx.compute_txid(); let bump_candidates = splice_candidates( @@ -10583,33 +10228,17 @@ mod tests { fail_store.fail_next_remove_in(PENDING_PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE); let res = wallet.record_broadcast_splice_round(channel_id, bump_txid).await; assert!(res.is_err(), "a failed merge must fail the write"); - let entry = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("entry"); + let entry = entry_of(&wallet, &id).await.expect("entry"); assert!(!entry.candidate(bump_txid).expect("candidate").awaiting_broadcast); - assert_eq!( - wallet.payment_stores.payment_store().get(&duplicate_id).await.unwrap(), - Some(duplicate) - ); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&duplicate_id) - .await - .unwrap() - .is_some()); + assert_eq!(record_of(&wallet, &duplicate_id).await, Some(duplicate)); + assert!(entry_of(&wallet, &duplicate_id).await.is_some()); // The replayed write finds the round marked already and merges the duplicate away. wallet.record_broadcast_splice_round(channel_id, bump_txid).await.unwrap(); let payments = wallet.payment_stores.payment_store().list_page(None).await.unwrap().objects; assert_eq!(payments.len(), 1, "the duplicate must be merged away"); assert_eq!(payments[0].id, id); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&duplicate_id) - .await - .unwrap() - .is_none()); + assert!(entry_of(&wallet, &duplicate_id).await.is_none()); assert_eq!(wallet.find_payment_by_txid(replacement_txid).await.unwrap(), Some(id)); } @@ -10676,8 +10305,7 @@ mod tests { .insert_or_update(duplicate_entry.clone()) .await .unwrap(); - let entry_before = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("entry"); + let entry_before = entry_of(&wallet, &id).await.expect("entry"); let rounds = entry_before.candidates().to_vec(); // The merge adopts the confirmation onto the payment record, then fails to mirror it onto @@ -10689,44 +10317,27 @@ mod tests { assert!(res.is_err(), "the injected pending-store failure must surface"); } fail_store.fail_writes.store(false, Ordering::Release); - let payment = - wallet.payment_stores.payment_store().get(&id).await.unwrap().expect("payment"); + let payment = record_of(&wallet, &id).await.expect("payment"); assert!(matches!( payment.kind, PaymentKind::Onchain { txid: t, status: ConfirmationStatus::Confirmed { .. }, .. } if t == replacement_txid )); - assert_eq!( - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap(), - Some(entry_before) - ); - assert_eq!( - wallet.payment_stores.payment_store().get(&duplicate_id).await.unwrap(), - Some(duplicate) - ); - assert_eq!( - wallet.payment_stores.pending_payment_store().get(&duplicate_id).await.unwrap(), - Some(duplicate_entry) - ); + assert_eq!(entry_of(&wallet, &id).await, Some(entry_before)); + assert_eq!(record_of(&wallet, &duplicate_id).await, Some(duplicate)); + assert_eq!(entry_of(&wallet, &duplicate_id).await, Some(duplicate_entry)); // A re-run finds the confirmation adopted, mirrors it, and removes the duplicate. { let guard = wallet.payment_stores.lock().await; wallet.merge_duplicate_candidate_records(&guard, id, &rounds).await.unwrap(); } - let entry = - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().expect("entry"); + let entry = entry_of(&wallet, &id).await.expect("entry"); assert_eq!(entry.details(), Some(&payment)); let payments = wallet.payment_stores.payment_store().list_page(None).await.unwrap().objects; assert_eq!(payments.len(), 1, "the duplicate must be merged away"); assert_eq!(payments[0].id, id); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&duplicate_id) - .await - .unwrap() - .is_none()); + assert!(entry_of(&wallet, &duplicate_id).await.is_none()); assert_eq!(wallet.find_payment_by_txid(replacement_txid).await.unwrap(), Some(id)); } @@ -10871,20 +10482,14 @@ mod tests { wallet.resolve_closed_channel_splice_rounds(channel_id, &[]).await.unwrap(); - let payment = wallet - .payment_stores - .payment_store() - .get(&id) - .await - .unwrap() - .expect("the record stays"); + let payment = record_of(&wallet, &id).await.expect("the record stays"); assert_eq!(payment.status, PaymentStatus::Failed); assert!(matches!( payment.kind, PaymentKind::Onchain { txid: recorded, status: ConfirmationStatus::Unconfirmed, .. } if recorded == txid )); - assert!(wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_none()); + assert!(entry_of(&wallet, &id).await.is_none()); } /// Signs a round and records its broadcast without wallet sync ever observing its @@ -10903,13 +10508,7 @@ mod tests { /// `id` as a failed payment carrying the share of the round the signing recorded. async fn assert_failed_unobserved_round(wallet: &Wallet, id: PaymentId, txid: Txid) { let (counterparty_node_id, channel_id) = test_counterparty_and_channel(); - let payment = wallet - .payment_stores - .payment_store() - .get(&id) - .await - .unwrap() - .expect("the attempt is on record"); + let payment = record_of(&wallet, &id).await.expect("the attempt is on record"); assert_eq!(payment.status, PaymentStatus::Failed); assert_eq!( payment.kind, @@ -10944,7 +10543,7 @@ mod tests { wallet.resolve_closed_channel_splice_rounds(channel_id, &[]).await.unwrap(); assert_failed_unobserved_round(&wallet, id, txid).await; - assert!(wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_none()); + assert!(entry_of(&wallet, &id).await.is_none()); } /// The entry of an unobserved round stays while the monitor watches the round: the @@ -10963,16 +10562,10 @@ mod tests { wallet.resolve_closed_channel_splice_rounds(channel_id, &[txid]).await.unwrap(); assert!( - wallet.payment_stores.payment_store().get(&id).await.unwrap().is_none(), + record_of(&wallet, &id).await.is_none(), "the round can still confirm, so nothing is failed", ); - let entry = wallet - .payment_stores - .pending_payment_store() - .get(&id) - .await - .unwrap() - .expect("the entry stays"); + let entry = entry_of(&wallet, &id).await.expect("the entry stays"); assert!(entry.details().is_none()); assert!(entry.candidate(txid).is_some()); } @@ -10994,16 +10587,10 @@ mod tests { wallet.resolve_closed_channel_splice_rounds(channel_id, &[]).await.unwrap(); assert!( - wallet.payment_stores.payment_store().get(&id).await.unwrap().is_none(), + record_of(&wallet, &id).await.is_none(), "the locked round can still confirm, so nothing is failed", ); - let entry = wallet - .payment_stores - .pending_payment_store() - .get(&id) - .await - .unwrap() - .expect("the entry stays"); + let entry = entry_of(&wallet, &id).await.expect("the entry stays"); assert!(entry.details().is_none()); assert!(entry.candidate(txid).is_some()); assert_eq!(entry.locked_rounds(), &[txid]); @@ -11038,13 +10625,7 @@ mod tests { ); wallet.record_signed_funding(&tx, &candidates).await.unwrap(); let id = wallet.find_payment_by_txid(txid).await.unwrap().expect("recorded"); - let entry = wallet - .payment_stores - .pending_payment_store() - .get(&id) - .await - .unwrap() - .expect("the entry"); + let entry = entry_of(&wallet, &id).await.expect("the entry"); assert!(entry.details().is_none()); assert!(entry.candidate(external_txid).is_some_and(|round| round.amount_msat.is_some())); (external_txid, id) @@ -11067,11 +10648,11 @@ mod tests { wallet.resolve_closed_channel_splice_rounds(channel_id, &[]).await.unwrap(); assert!( - wallet.payment_stores.payment_store().get(&id).await.unwrap().is_none(), + record_of(&wallet, &id).await.is_none(), "round {} was never a payment of the wallet's, so there is nothing to fail", external_txid, ); - assert!(wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_none()); + assert!(entry_of(&wallet, &id).await.is_none()); } /// A failed read of the round's facts is no answer about its share: the close fails for the @@ -11092,15 +10673,9 @@ mod tests { let result = wallet.resolve_closed_channel_splice_rounds(channel_id, &[]).await; assert!(matches!(result, Err(Error::PersistenceFailed)), "{:?}", result); - assert!(wallet.payment_stores.payment_store().get(&id).await.unwrap().is_none()); + assert!(record_of(&wallet, &id).await.is_none()); fail_store.fail_reads.store(false, Ordering::Release); - let entry = wallet - .payment_stores - .pending_payment_store() - .get(&id) - .await - .unwrap() - .expect("the entry stays"); + let entry = entry_of(&wallet, &id).await.expect("the entry stays"); let listed: Vec = entry.candidates().iter().map(|round| round.txid).collect(); assert_eq!(listed, vec![external_txid], "the abandoned bump is dropped before the read"); assert!(entry.candidate(external_txid).is_some_and(|round| round.amount_msat.is_some())); @@ -11108,8 +10683,8 @@ mod tests { // The replay, with the reads back: the external round alone is left, and it goes without // a record. wallet.resolve_closed_channel_splice_rounds(channel_id, &[]).await.unwrap(); - assert!(wallet.payment_stores.payment_store().get(&id).await.unwrap().is_none()); - assert!(wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_none()); + assert!(record_of(&wallet, &id).await.is_none()); + assert!(entry_of(&wallet, &id).await.is_none()); } /// A sibling round this node did not contribute to, in the entry's history from the signing @@ -11134,7 +10709,7 @@ mod tests { .unwrap(); assert_failed_unobserved_round(&wallet, id, txid).await; - assert!(wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_none()); + assert!(entry_of(&wallet, &id).await.is_none()); } /// LDK promoted a round of ours and discarded the counterparty's round it replaced with the @@ -11153,21 +10728,9 @@ mod tests { wallet.resolve_promoted_splice_round(channel_id, txid, Some(&[txid])).await.unwrap(); - let payment = wallet - .payment_stores - .payment_store() - .get(&id) - .await - .unwrap() - .expect("the record stays"); + let payment = record_of(&wallet, &id).await.expect("the record stays"); assert_eq!(payment.status, PaymentStatus::Pending); - let entry = wallet - .payment_stores - .pending_payment_store() - .get(&id) - .await - .unwrap() - .expect("the entry stays"); + let entry = entry_of(&wallet, &id).await.expect("the entry stays"); assert_eq!(entry.candidates().len(), 2); assert_eq!(entry.locked_rounds(), &[txid]); } @@ -11198,20 +10761,14 @@ mod tests { .await .unwrap(); - let payment = wallet - .payment_stores - .payment_store() - .get(&id) - .await - .unwrap() - .expect("the record stays"); + let payment = record_of(&wallet, &id).await.expect("the record stays"); assert_eq!(payment.status, PaymentStatus::Failed); assert!(matches!( payment.kind, PaymentKind::Onchain { txid: recorded, status: ConfirmationStatus::Unconfirmed, .. } if recorded == txid )); - assert!(wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_none()); + assert!(entry_of(&wallet, &id).await.is_none()); } /// Wallet sync moved the record onto the counterparty's round before LDK promoted it, so the @@ -11233,7 +10790,7 @@ mod tests { old_block_time: None, }; wallet.update_payment_store(vec![event]).await.unwrap(); - let payment = wallet.payment_stores.payment_store().get(&id).await.unwrap().unwrap(); + let payment = record_of(&wallet, &id).await.unwrap(); assert!( matches!(payment.kind, PaymentKind::Onchain { txid, .. } if txid == counterparty_txid) ); @@ -11247,20 +10804,14 @@ mod tests { .await .unwrap(); - let payment = wallet - .payment_stores - .payment_store() - .get(&id) - .await - .unwrap() - .expect("the record stays"); + let payment = record_of(&wallet, &id).await.expect("the record stays"); assert_eq!(payment.status, PaymentStatus::Failed); assert!(matches!( payment.kind, PaymentKind::Onchain { txid, status: ConfirmationStatus::Unconfirmed, .. } if txid == counterparty_txid )); - assert!(wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_none()); + assert!(entry_of(&wallet, &id).await.is_none()); } /// The same at a close whose monitor watches the counterparty's round the record moved onto: @@ -11280,7 +10831,7 @@ mod tests { old_block_time: None, }; wallet.update_payment_store(vec![event]).await.unwrap(); - let payment = wallet.payment_stores.payment_store().get(&id).await.unwrap().unwrap(); + let payment = record_of(&wallet, &id).await.unwrap(); assert!( matches!(payment.kind, PaymentKind::Onchain { txid, .. } if txid == counterparty_txid) ); @@ -11290,20 +10841,14 @@ mod tests { .await .unwrap(); - let payment = wallet - .payment_stores - .payment_store() - .get(&id) - .await - .unwrap() - .expect("the record stays"); + let payment = record_of(&wallet, &id).await.expect("the record stays"); assert_eq!(payment.status, PaymentStatus::Failed); assert!(matches!( payment.kind, PaymentKind::Onchain { txid, status: ConfirmationStatus::Unconfirmed, .. } if txid == counterparty_txid )); - assert!(wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_none()); + assert!(entry_of(&wallet, &id).await.is_none()); } /// A round of ours nothing had broadcast when the counterparty's round locked — our @@ -11325,10 +10870,7 @@ mod tests { wallet.record_signed_funding(&tx, &candidates).await.unwrap(); record_unseen_round(&wallet, &tx).await; let id = wallet.find_payment_by_txid(txid).await.unwrap().expect("id"); - assert!( - wallet.payment_stores.payment_store().get(&id).await.unwrap().is_some(), - "the round was recorded" - ); + assert!(record_of(&wallet, &id).await.is_some(), "the round was recorded"); wallet .resolve_promoted_splice_round( @@ -11339,8 +10881,8 @@ mod tests { .await .unwrap(); - assert!(wallet.payment_stores.payment_store().get(&id).await.unwrap().is_none()); - assert!(wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_none()); + assert!(record_of(&wallet, &id).await.is_none()); + assert!(entry_of(&wallet, &id).await.is_none()); } /// Failing the payment writes the record before it removes the entry; a replay after the @@ -11366,7 +10908,7 @@ mod tests { }) .await .unwrap(); - assert!(wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_some()); + assert!(entry_of(&wallet, &id).await.is_some()); wallet .resolve_promoted_splice_round( @@ -11377,15 +10919,9 @@ mod tests { .await .unwrap(); - let payment = wallet - .payment_stores - .payment_store() - .get(&id) - .await - .unwrap() - .expect("the record stays"); + let payment = record_of(&wallet, &id).await.expect("the record stays"); assert_eq!(payment.status, PaymentStatus::Failed); - assert!(wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_none()); + assert!(entry_of(&wallet, &id).await.is_none()); } /// A promotion reported for a channel the manager no longer lists — the channel closed before @@ -11405,36 +10941,18 @@ mod tests { let id = record_broadcast_rounds(&wallet, &tx, &rounds).await; wallet.resolve_promoted_splice_round(channel_id, counterparty_txid, None).await.unwrap(); - let payment = wallet - .payment_stores - .payment_store() - .get(&id) - .await - .unwrap() - .expect("the record stays"); + let payment = record_of(&wallet, &id).await.expect("the record stays"); assert_eq!(payment.status, PaymentStatus::Pending); - let entry = wallet - .payment_stores - .pending_payment_store() - .get(&id) - .await - .unwrap() - .expect("the entry stays"); + let entry = entry_of(&wallet, &id).await.expect("the entry stays"); assert_eq!(entry.locked_rounds(), &[counterparty_txid]); wallet .resolve_closed_channel_splice_rounds(channel_id, &[counterparty_txid]) .await .unwrap(); - let payment = wallet - .payment_stores - .payment_store() - .get(&id) - .await - .unwrap() - .expect("the record stays"); + let payment = record_of(&wallet, &id).await.expect("the record stays"); assert_eq!(payment.status, PaymentStatus::Failed); - assert!(wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_none()); + assert!(entry_of(&wallet, &id).await.is_none()); } /// A payment whose round LDK promoted before is kept when a later splice's round is promoted @@ -11464,41 +10982,17 @@ mod tests { .unwrap(); for (id, locked) in [(first_id, first_txid), (second_id, second_txid)] { - let payment = wallet - .payment_stores - .payment_store() - .get(&id) - .await - .unwrap() - .expect("the record stays"); + let payment = record_of(&wallet, &id).await.expect("the record stays"); assert_eq!(payment.status, PaymentStatus::Pending); - let entry = wallet - .payment_stores - .pending_payment_store() - .get(&id) - .await - .unwrap() - .expect("the entry stays"); + let entry = entry_of(&wallet, &id).await.expect("the entry stays"); assert_eq!(entry.locked_rounds(), &[locked]); } wallet.resolve_closed_channel_splice_rounds(channel_id, &[second_txid]).await.unwrap(); for id in [first_id, second_id] { - let payment = wallet - .payment_stores - .payment_store() - .get(&id) - .await - .unwrap() - .expect("the record stays"); + let payment = record_of(&wallet, &id).await.expect("the record stays"); assert_eq!(payment.status, PaymentStatus::Pending); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&id) - .await - .unwrap() - .is_some()); + assert!(entry_of(&wallet, &id).await.is_some()); } } @@ -11515,13 +11009,7 @@ mod tests { let (first_txid, bump_txid) = (first_tx.compute_txid(), bump_tx.compute_txid()); let id = record_broadcast_rounds(&wallet, &first_tx, &[(first_txid, Some(first.clone()))]).await; - let payment = wallet - .payment_stores - .payment_store() - .get(&id) - .await - .unwrap() - .expect("the record exists"); + let payment = record_of(&wallet, &id).await.expect("the record exists"); let first_figures = (payment.amount_msat, payment.fee_paid_msat); let candidates = splice_candidates( counterparty_node_id, @@ -11530,13 +11018,7 @@ mod tests { ); wallet.record_signed_funding(&bump_tx, &candidates).await.unwrap(); record_unseen_round(&wallet, &bump_tx).await; - let payment = wallet - .payment_stores - .payment_store() - .get(&id) - .await - .unwrap() - .expect("the record exists"); + let payment = record_of(&wallet, &id).await.expect("the record exists"); assert!(matches!(payment.kind, PaymentKind::Onchain { txid, .. } if txid == bump_txid)); assert_ne!((payment.amount_msat, payment.fee_paid_msat), first_figures); @@ -11545,23 +11027,11 @@ mod tests { .await .unwrap(); - let payment = wallet - .payment_stores - .payment_store() - .get(&id) - .await - .unwrap() - .expect("the record stays"); + let payment = record_of(&wallet, &id).await.expect("the record stays"); assert_eq!(payment.status, PaymentStatus::Pending); assert!(matches!(payment.kind, PaymentKind::Onchain { txid, .. } if txid == first_txid)); assert_eq!((payment.amount_msat, payment.fee_paid_msat), first_figures); - let entry = wallet - .payment_stores - .pending_payment_store() - .get(&id) - .await - .unwrap() - .expect("the entry stays"); + let entry = entry_of(&wallet, &id).await.expect("the entry stays"); assert_eq!(entry.candidates().iter().map(|c| c.txid).collect::>(), vec![first_txid]); assert_eq!(entry.locked_rounds(), &[first_txid]); } @@ -11588,31 +11058,16 @@ mod tests { .await .unwrap(); } - let entry = wallet - .payment_stores - .pending_payment_store() - .get(&id) - .await - .unwrap() - .expect("the entry stays"); + let entry = entry_of(&wallet, &id).await.expect("the entry stays"); assert_eq!(entry.locked_rounds(), &[txid]); wallet .resolve_closed_channel_splice_rounds(channel_id, &[later_funding_txid]) .await .unwrap(); - let payment = wallet - .payment_stores - .payment_store() - .get(&id) - .await - .unwrap() - .expect("the record stays"); + let payment = record_of(&wallet, &id).await.expect("the record stays"); assert_eq!(payment.status, PaymentStatus::Pending); - assert!( - wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_some(), - "the entry stays" - ); + assert!(entry_of(&wallet, &id).await.is_some(), "the entry stays"); } /// A promoted round whose `SpliceNegotiated` event is still unhandled when the channel closes @@ -11636,21 +11091,9 @@ mod tests { .resolve_closed_channel_splice_rounds(channel_id, &[later_funding_txid]) .await .unwrap(); - let payment = wallet - .payment_stores - .payment_store() - .get(&id) - .await - .unwrap() - .expect("the record stays"); + let payment = record_of(&wallet, &id).await.expect("the record stays"); assert_eq!(payment.status, PaymentStatus::Pending); - let entry = wallet - .payment_stores - .pending_payment_store() - .get(&id) - .await - .unwrap() - .expect("the entry stays"); + let entry = entry_of(&wallet, &id).await.expect("the entry stays"); assert!(entry.candidate(txid).is_some_and(|round| round.awaiting_broadcast)); } @@ -11691,32 +11134,14 @@ mod tests { for _ in 0..2 { wallet.drop_abandoned_splice_rounds(channel_id, &tracked_rounds).await.unwrap(); } - let payment = wallet - .payment_stores - .payment_store() - .get(&id) - .await - .unwrap() - .expect("the record stays"); + let payment = record_of(&wallet, &id).await.expect("the record stays"); assert_eq!(payment.status, PaymentStatus::Pending); - let entry = wallet - .payment_stores - .pending_payment_store() - .get(&id) - .await - .unwrap() - .expect("the entry stays"); + let entry = entry_of(&wallet, &id).await.expect("the entry stays"); assert_eq!(entry.candidates().len(), 2); // At the close the monitor has settled on the funding and watches neither round. wallet.resolve_closed_channel_splice_rounds(channel_id, &[funding_txid]).await.unwrap(); - let payment = wallet - .payment_stores - .payment_store() - .get(&id) - .await - .unwrap() - .expect("the record stays"); + let payment = record_of(&wallet, &id).await.expect("the record stays"); assert_eq!(payment.status, PaymentStatus::Failed); assert!(matches!( payment.kind, @@ -11726,7 +11151,7 @@ mod tests { tx_type: Some(TransactionType::InteractiveFunding { .. }), } if txid == bump_txid )); - assert!(wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_none()); + assert!(entry_of(&wallet, &id).await.is_none()); } /// The close leaves a payment alone while the monitor watches a round of ours in its record: @@ -11746,21 +11171,9 @@ mod tests { .resolve_closed_channel_splice_rounds(channel_id, &[funding_txid, bump_txid]) .await .unwrap(); - let payment = wallet - .payment_stores - .payment_store() - .get(&id) - .await - .unwrap() - .expect("the record stays"); + let payment = record_of(&wallet, &id).await.expect("the record stays"); assert_eq!(payment.status, PaymentStatus::Pending); - let entry = wallet - .payment_stores - .pending_payment_store() - .get(&id) - .await - .unwrap() - .expect("the entry stays"); + let entry = entry_of(&wallet, &id).await.expect("the entry stays"); assert_eq!(entry.candidates().len(), 2); } @@ -11794,19 +11207,13 @@ mod tests { .await .unwrap(); wallet.resolve_closed_channel_splice_rounds(channel_id, &[]).await.unwrap(); - let payment = wallet - .payment_stores - .payment_store() - .get(&id) - .await - .unwrap() - .expect("the record stays"); + let payment = record_of(&wallet, &id).await.expect("the record stays"); assert_eq!(payment.status, PaymentStatus::Succeeded); assert!(matches!( payment.kind, PaymentKind::Onchain { status: ConfirmationStatus::Confirmed { .. }, .. } )); - assert!(wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_some()); + assert!(entry_of(&wallet, &id).await.is_some()); } /// Failing the payment writes the record before it removes the entry; the close replayed after @@ -11831,15 +11238,9 @@ mod tests { .await .unwrap(); wallet.resolve_closed_channel_splice_rounds(channel_id, &[]).await.unwrap(); - let payment = wallet - .payment_stores - .payment_store() - .get(&id) - .await - .unwrap() - .expect("the record stays"); + let payment = record_of(&wallet, &id).await.expect("the record stays"); assert_eq!(payment.status, PaymentStatus::Failed); - assert!(wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_none()); + assert!(entry_of(&wallet, &id).await.is_none()); } /// The close resolves every record of the channel — two splices signed under different @@ -11865,21 +11266,9 @@ mod tests { let funding_txid = Txid::from_byte_array([0xF0; 32]); wallet.resolve_closed_channel_splice_rounds(channel_id, &[funding_txid]).await.unwrap(); for id in [first_id, second_id] { - let payment = wallet - .payment_stores - .payment_store() - .get(&id) - .await - .unwrap() - .expect("the record stays"); + let payment = record_of(&wallet, &id).await.expect("the record stays"); assert_eq!(payment.status, PaymentStatus::Failed); - assert!(wallet - .payment_stores - .pending_payment_store() - .get(&id) - .await - .unwrap() - .is_none()); + assert!(entry_of(&wallet, &id).await.is_none()); } } @@ -11945,12 +11334,8 @@ mod tests { .await .unwrap() .is_none()); - let payment = wallet - .payment_stores - .payment_store() - .get(&figures.funding_payment_id) + let payment = record_of(&wallet, &figures.funding_payment_id) .await - .unwrap() .expect("wallet sync records the transaction"); assert_eq!(payment.amount_msat, figures.amount_msat); assert_eq!(payment.fee_paid_msat, figures.fee_paid_msat); @@ -12036,7 +11421,7 @@ mod tests { let result = wallet.update_payment_store(vec![event]).await; assert!(matches!(result, Err(Error::PersistenceFailed)), "{:?}", result); assert!( - wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().is_none(), + record_of(&wallet, &payment_id).await.is_none(), "a record written now would carry the wallet's view of the amount for good", ); } @@ -12045,14 +11430,8 @@ mod tests { // under the funding payment the report identifies. fail_store.fail_reads.store(false, Ordering::Release); wallet.update_payment_store(vec![confirmed_at(confirmation_height)]).await.unwrap(); - assert!(wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().is_none()); - let payment = wallet - .payment_stores - .payment_store() - .get(&figures.funding_payment_id) - .await - .unwrap() - .expect("record"); + assert!(record_of(&wallet, &payment_id).await.is_none()); + let payment = record_of(&wallet, &figures.funding_payment_id).await.expect("record"); assert_eq!(payment.status, PaymentStatus::Succeeded); assert_eq!(payment.amount_msat, figures.amount_msat); assert_eq!(payment.fee_paid_msat, figures.fee_paid_msat); @@ -12101,13 +11480,8 @@ mod tests { wallet.update_payment_store(vec![graduated]).await.unwrap(); let payment_id = PaymentId(claim_txid.to_byte_array()); - let unclassified = wallet - .payment_stores - .payment_store() - .get(&payment_id) - .await - .unwrap() - .expect("wallet sync records the transaction"); + let unclassified = + record_of(&wallet, &payment_id).await.expect("wallet sync records the transaction"); assert_eq!(unclassified.status, PaymentStatus::Succeeded); assert!( matches!(unclassified.kind, PaymentKind::Onchain { tx_type: None, .. }), @@ -12126,13 +11500,7 @@ mod tests { .unwrap(); wallet.classify_recorded_transaction(claim_txid).await; - let classified = wallet - .payment_stores - .payment_store() - .get(&payment_id) - .await - .unwrap() - .expect("the record stays"); + let classified = record_of(&wallet, &payment_id).await.expect("the record stays"); assert!( matches!( classified.kind, @@ -12178,8 +11546,7 @@ mod tests { wallet.update_payment_store(vec![seen]).await.unwrap(); let payment_id = PaymentId(txid.to_byte_array()); - let recorded = - wallet.payment_stores.payment_store().get(&payment_id).await.unwrap().unwrap(); + let recorded = record_of(&wallet, &payment_id).await.unwrap(); assert_eq!(recorded.direction, PaymentDirection::Outbound); assert!(matches!( recorded.kind, @@ -12358,13 +11725,8 @@ mod tests { wallet.update_payment_store(vec![event]).await.unwrap(); let payment_id = PaymentId(sweep_txid.to_byte_array()); - let unclassified = wallet - .payment_stores - .payment_store() - .get(&payment_id) - .await - .unwrap() - .expect("wallet sync records the transaction"); + let unclassified = + record_of(&wallet, &payment_id).await.expect("wallet sync records the transaction"); assert!( matches!(unclassified.kind, PaymentKind::Onchain { tx_type: None, .. }), "the transaction has no recorded facts yet, so it cannot be classified: {:?}", @@ -12386,13 +11748,7 @@ mod tests { let event = WalletEvent::ChainTipChanged { old_tip: block_id(1), new_tip: block_id(2) }; wallet.update_payment_store(vec![event]).await.unwrap(); - let classified = wallet - .payment_stores - .payment_store() - .get(&payment_id) - .await - .unwrap() - .expect("the record stays"); + let classified = record_of(&wallet, &payment_id).await.expect("the record stays"); match classified.kind { PaymentKind::Onchain { tx_type: Some(TransactionType::Sweep { channels }), .. } => { assert_eq!(channels, vec![channel]); @@ -13190,7 +12546,7 @@ mod tests { .unwrap(); drop(stores); - assert!(wallet.payment_stores.pending_payment_store().get(&id).await.unwrap().is_none()); + assert!(entry_of(&wallet, &id).await.is_none()); } #[tokio::test] From 903cd7ccc60bd08e31f6aa8bb8d4605d7cc54588 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Tue, 17 Nov 2026 10:51:13 +0100 Subject: [PATCH 02/11] Share the wallet-sync handling of observed txs The confirmed, unconfirmed and dropped wallet events each repeated the same steps to resolve a transaction's payment and write its record and pending entry, so any change to that flow had to be made three times. Handle all three through one method, parameterized by the status the event implies. The store calls, their order and error handling stay as they were. Written with the help of an AI tool. Co-Authored-By: HAL 9000 --- src/wallet/mod.rs | 279 ++++++++++++++++------------------------------ 1 file changed, 95 insertions(+), 184 deletions(-) diff --git a/src/wallet/mod.rs b/src/wallet/mod.rs index a8119554d4..5cc62a5bbd 100644 --- a/src/wallet/mod.rs +++ b/src/wallet/mod.rs @@ -782,78 +782,7 @@ impl Wallet { timestamp: block_time.confirmation_time, }; - // Hold the cross-store lock from payment-id resolution through the last write: - // a funding-record write landing in between would leave the id resolved - // against a torn candidate index and the generic fallback below overwriting - // (or duplicating) the record that write had just made. - let stores = self.payment_stores.lock().await; - - let mut payment_id = self - .find_payment_by_txid(txid) - .await? - .unwrap_or_else(|| PaymentId(txid.to_byte_array())); - - match self - .apply_funding_status_update_locked( - &stores, - payment_id, - txid, - confirmation_status, - ) - .await? - { - FundingStatusUpdate::Applied => continue, - FundingStatusUpdate::NotFunding => {}, - // Not part of the funding payment's history (e.g. a close spending the - // funding outpoint): record it under its own id below instead, unless a - // settled funding payment sits there already. - FundingStatusUpdate::Foreign => { - match self.foreign_transaction_payment_id(payment_id, txid).await? { - Some(fallback_id) => payment_id = fallback_id, - None => { - log_debug!( - self.logger, - "Skipping wallet event for transaction {} of a settled funding payment", - txid, - ); - continue; - }, - } - }, - } - - // A record written from the wallet's own view would misread a shared input of - // an interactively negotiated funding as wholly this node's, and once the - // record is classified or settled its amount and fee are never written again. - // So a fact that cannot be read fails the pass, as a write that fails does, - // rather than write the record on that view. - let provenance = self.read_tx_provenance(txid, &tx).await?; - let payment = { - let locked_wallet = self.inner.lock().expect("lock"); - self.create_payment_from_tx( - &locked_wallet, - txid, - payment_id, - &tx, - &provenance, - payment_status, - confirmation_status, - ) - }; - - stores.insert_or_update_payment(payment.clone()).await?; - - if payment_status == PaymentStatus::Pending { - self.upsert_pending_payment(&stores, payment, Vec::new()).await?; - } else { - // The transaction was first observed already confirmed through the reorg - // depth, so the record is written settled and never graduates. An entry - // under its id that no record promoted yet -- the signed rounds of a splice - // whose transaction nothing had observed before -- tracked this payment - // alone, and with the payment settled tracks nothing further, as the entry - // of a graduated record does. - stores.remove_pending_payment(&payment_id).await?; - } + self.record_wallet_tx(txid, &tx, payment_status, confirmation_status).await?; }, WalletEvent::ChainTipChanged { new_tip, .. } => { let pending_payments: Vec = self @@ -989,66 +918,19 @@ impl Wallet { } }, WalletEvent::TxUnconfirmed { txid, tx, .. } => { - // See `TxConfirmed`: id resolution and the writes below must not interleave - // with the funding-record writers. - let stores = self.payment_stores.lock().await; - - let mut payment_id = self - .find_payment_by_txid(txid) - .await? - .unwrap_or_else(|| PaymentId(txid.to_byte_array())); - - match self - .apply_funding_status_update_locked( - &stores, - payment_id, - txid, - ConfirmationStatus::Unconfirmed, - ) - .await? - { - FundingStatusUpdate::Applied => continue, - FundingStatusUpdate::NotFunding => {}, - // Not part of the funding payment's history (e.g. a close spending the - // funding outpoint): record it under its own id below instead, unless a - // settled funding payment sits there already. - FundingStatusUpdate::Foreign => { - match self.foreign_transaction_payment_id(payment_id, txid).await? { - Some(fallback_id) => payment_id = fallback_id, - None => { - log_debug!( - self.logger, - "Skipping wallet event for transaction {} of a settled funding payment", - txid, - ); - continue; - }, - } - }, - } - - // See `TxConfirmed`: a fact that cannot be read fails the pass. - let provenance = self.read_tx_provenance(txid, &tx).await?; - let payment = { - let locked_wallet = self.inner.lock().expect("lock"); - self.create_payment_from_tx( - &locked_wallet, - txid, - payment_id, - &tx, - &provenance, - PaymentStatus::Pending, - ConfirmationStatus::Unconfirmed, - ) - }; - stores.insert_or_update_payment(payment.clone()).await?; - self.upsert_pending_payment(&stores, payment, Vec::new()).await?; + self.record_wallet_tx( + txid, + &tx, + PaymentStatus::Pending, + ConfirmationStatus::Unconfirmed, + ) + .await?; }, WalletEvent::TxReplaced { txid, conflicts, .. } => { - // See `TxConfirmed`: id resolution and the writes below must not interleave - // with the funding-record writers. The pending entry written below embeds a - // read of the payment record, which must not go stale against a concurrent - // write either. + // See `record_wallet_tx`: id resolution and the writes below must not + // interleave with the funding-record writers. The pending entry written below + // embeds a read of the payment record, which must not go stale against a + // concurrent write either. let stores = self.payment_stores.lock().await; let Some(payment_id) = self.find_payment_by_txid(txid).await? else { @@ -1094,60 +976,13 @@ impl Wallet { self.upsert_pending_payment(&stores, payment, conflict_txids).await?; }, WalletEvent::TxDropped { txid, tx } => { - // See `TxConfirmed`: id resolution and the writes below must not interleave - // with the funding-record writers. - let stores = self.payment_stores.lock().await; - - let mut payment_id = self - .find_payment_by_txid(txid) - .await? - .unwrap_or_else(|| PaymentId(txid.to_byte_array())); - - match self - .apply_funding_status_update_locked( - &stores, - payment_id, - txid, - ConfirmationStatus::Unconfirmed, - ) - .await? - { - FundingStatusUpdate::Applied => continue, - FundingStatusUpdate::NotFunding => {}, - // Not part of the funding payment's history (e.g. a close spending the - // funding outpoint): record it under its own id below instead, unless a - // settled funding payment sits there already. - FundingStatusUpdate::Foreign => { - match self.foreign_transaction_payment_id(payment_id, txid).await? { - Some(fallback_id) => payment_id = fallback_id, - None => { - log_debug!( - self.logger, - "Skipping wallet event for transaction {} of a settled funding payment", - txid, - ); - continue; - }, - } - }, - } - - // See `TxConfirmed`: a fact that cannot be read fails the pass. - let provenance = self.read_tx_provenance(txid, &tx).await?; - let payment = { - let locked_wallet = self.inner.lock().expect("lock"); - self.create_payment_from_tx( - &locked_wallet, - txid, - payment_id, - &tx, - &provenance, - PaymentStatus::Pending, - ConfirmationStatus::Unconfirmed, - ) - }; - stores.insert_or_update_payment(payment.clone()).await?; - self.upsert_pending_payment(&stores, payment, Vec::new()).await?; + self.record_wallet_tx( + txid, + &tx, + PaymentStatus::Pending, + ConfirmationStatus::Unconfirmed, + ) + .await?; }, _ => { continue; @@ -1158,6 +993,82 @@ impl Wallet { Ok(()) } + /// Records the wallet transaction `txid` with the given status, resolving the payment it + /// belongs to and keeping its pending-store entry in step with the record. + async fn record_wallet_tx( + &self, txid: Txid, tx: &Transaction, payment_status: PaymentStatus, + confirmation_status: ConfirmationStatus, + ) -> Result<(), Error> { + // Hold the cross-store lock from payment-id resolution through the last write: + // a funding-record write landing in between would leave the id resolved + // against a torn candidate index and the generic fallback below overwriting + // (or duplicating) the record that write had just made. + let stores = self.payment_stores.lock().await; + + let mut payment_id = self + .find_payment_by_txid(txid) + .await? + .unwrap_or_else(|| PaymentId(txid.to_byte_array())); + + match self + .apply_funding_status_update_locked(&stores, payment_id, txid, confirmation_status) + .await? + { + FundingStatusUpdate::Applied => return Ok(()), + FundingStatusUpdate::NotFunding => {}, + // Not part of the funding payment's history (e.g. a close spending the + // funding outpoint): record it under its own id below instead, unless a + // settled funding payment sits there already. + FundingStatusUpdate::Foreign => { + match self.foreign_transaction_payment_id(payment_id, txid).await? { + Some(fallback_id) => payment_id = fallback_id, + None => { + log_debug!( + self.logger, + "Skipping wallet event for transaction {} of a settled funding payment", + txid, + ); + return Ok(()); + }, + } + }, + } + + // A record written from the wallet's own view would misread a shared input of + // an interactively negotiated funding as wholly this node's, and once the + // record is classified or settled its amount and fee are never written again. + // So a fact that cannot be read fails the pass, as a write that fails does, + // rather than write the record on that view. + let provenance = self.read_tx_provenance(txid, tx).await?; + let payment = { + let locked_wallet = self.inner.lock().expect("lock"); + self.create_payment_from_tx( + &locked_wallet, + txid, + payment_id, + tx, + &provenance, + payment_status, + confirmation_status, + ) + }; + + stores.insert_or_update_payment(payment.clone()).await?; + + if payment_status == PaymentStatus::Pending { + self.upsert_pending_payment(&stores, payment, Vec::new()).await?; + } else { + // The transaction was first observed already confirmed through the reorg + // depth, so the record is written settled and never graduates. An entry + // under its id that no record promoted yet -- the signed rounds of a splice + // whose transaction nothing had observed before -- tracked this payment + // alone, and with the payment settled tracks nothing further, as the entry + // of a graduated record does. + stores.remove_pending_payment(&payment_id).await?; + } + Ok(()) + } + /// Classifies the transactions of the given payments from the facts this node has recorded /// about them, for records that do not say what their transaction is. /// From c0e28299625a6dc22ed7d6aebdccf0e2a34a7152 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Tue, 17 Nov 2026 10:53:33 +0100 Subject: [PATCH 03/11] Drop the generic update path for pending entries Pending entries implemented the store's generic update interface, with merge rules covering cases only tests exercised. Wallet sync was its one production user, so most of those rules guarded nothing real. Replace it with a single merge of what wallet sync observes about a payment, keeping the rules sync relies on. Stored entries are read and written as before. Written with the help of an AI tool. Co-Authored-By: HAL 9000 --- src/payment/pending_payment_store.rs | 170 ++++++++------------------- src/wallet/mod.rs | 101 +++++++++------- 2 files changed, 109 insertions(+), 162 deletions(-) diff --git a/src/payment/pending_payment_store.rs b/src/payment/pending_payment_store.rs index fc603e616b..9c994d465b 100644 --- a/src/payment/pending_payment_store.rs +++ b/src/payment/pending_payment_store.rs @@ -9,8 +9,8 @@ use bitcoin::Txid; use lightning::impl_writeable_tlv_based; use lightning::ln::channelmanager::PaymentId; -use crate::data_store::{StorableObject, StorableObjectUpdate, UpdatableObject}; -use crate::payment::store::{Channel, PaymentDetailsUpdate, TransactionType}; +use crate::data_store::{StorableObject, UpdatableObject}; +use crate::payment::store::{Channel, TransactionType}; use crate::payment::{PaymentDetails, PaymentKind}; /// One candidate transaction in an interactive-funding (splice) RBF history, holding this node's @@ -83,15 +83,13 @@ pub(crate) struct PendingPaymentDetails { } impl PendingPaymentDetails { - pub(crate) fn new( - details: PaymentDetails, conflicting_txids: Vec, candidates: Vec, - ) -> Self { + pub(crate) fn new(details: PaymentDetails, conflicting_txids: Vec) -> Self { Self { id: details.id, details: Some(details), conflicting_txids, funding_channels: Vec::new(), - candidates, + candidates: Vec::new(), locked_rounds: Vec::new(), } } @@ -163,57 +161,21 @@ impl PendingPaymentDetails { } } - /// Whether this entry tracks nothing anymore and can be dropped. - pub(crate) fn is_empty(&self) -> bool { - self.details.is_none() && self.candidates.is_empty() && self.locked_rounds.is_empty() - } -} - -impl_writeable_tlv_based!(PendingPaymentDetails, { - (0, id, required), - (2, details, option), - (4, conflicting_txids, optional_vec), - (6, funding_channels, optional_vec), - (8, candidates, optional_vec), - (10, locked_rounds, optional_vec), -}); - -#[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) struct PendingPaymentDetailsUpdate { - pub id: PaymentId, - pub payment_update: Option, - pub conflicting_txids: Option>, - pub candidates: Vec, -} - -impl StorableObject for PendingPaymentDetails { - type Id = PaymentId; - - fn id(&self) -> Self::Id { - self.id - } -} - -impl UpdatableObject for PendingPaymentDetails { - type Update = PendingPaymentDetailsUpdate; - - fn update(&mut self, update: Self::Update) -> bool { + /// Merges what wallet sync observed about the entry's payment into it: `payment`'s update is + /// applied to the recorded payment, if any, and a non-empty `conflicting_txids` replaces the + /// recorded conflicts. The payment's current txid never stays listed as its own conflict. + /// Returns whether the entry changed. + pub(crate) fn merge_observed( + &mut self, payment: &PaymentDetails, conflicting_txids: Vec, + ) -> bool { let mut updated = false; - - // Update the underlying payment details if present. An entry with no record yet is not - // given one here: only the writer that observed the transaction knows what the record - // says, and it sets the field directly. - if let (Some(payment_update), Some(details)) = - (update.payment_update, self.details.as_mut()) - { - updated |= details.update(payment_update); + if let Some(details) = self.details.as_mut() { + updated |= details.update(payment.to_update()); } - if let Some(new_conflicting_txids) = update.conflicting_txids { - if self.conflicting_txids != new_conflicting_txids { - self.conflicting_txids = new_conflicting_txids; - updated = true; - } + if !conflicting_txids.is_empty() && self.conflicting_txids != conflicting_txids { + self.conflicting_txids = conflicting_txids; + updated = true; } if let Some(PaymentKind::Onchain { txid, .. }) = @@ -225,54 +187,29 @@ impl UpdatableObject for PendingPaymentDetails { updated |= self.conflicting_txids.len() != conflicts_len; } - // Each funding-record write passes the candidate history as of its own round, so a - // non-empty update replaces the stored list. An empty update (e.g. a non-funding - // payment) leaves it untouched. Dropping an abandoned round, the only writer that - // shrinks it, goes through the store's `mutate` instead. - if !update.candidates.is_empty() && self.candidates != update.candidates { - self.candidates = update.candidates; - updated = true; - } - updated } - fn to_update(&self) -> Self::Update { - self.into() + /// Whether this entry tracks nothing anymore and can be dropped. + pub(crate) fn is_empty(&self) -> bool { + self.details.is_none() && self.candidates.is_empty() && self.locked_rounds.is_empty() } } -impl StorableObjectUpdate for PendingPaymentDetailsUpdate { - fn id(&self) -> ::Id { - self.id - } -} +impl_writeable_tlv_based!(PendingPaymentDetails, { + (0, id, required), + (2, details, option), + (4, conflicting_txids, optional_vec), + (6, funding_channels, optional_vec), + (8, candidates, optional_vec), + (10, locked_rounds, optional_vec), +}); -impl From<&PendingPaymentDetails> for PendingPaymentDetailsUpdate { - fn from(value: &PendingPaymentDetails) -> Self { - match &value.details { - // For an entry without a record yet, a payment-tracking merge can only apply its - // candidate history. - None => Self { - id: value.id, - payment_update: None, - conflicting_txids: None, - candidates: value.candidates.clone(), - }, - Some(details) => { - let conflicting_txids = if value.conflicting_txids.is_empty() { - None - } else { - Some(value.conflicting_txids.clone()) - }; - Self { - id: details.id, - payment_update: Some(details.to_update()), - conflicting_txids, - candidates: value.candidates.clone(), - } - }, - } +impl StorableObject for PendingPaymentDetails { + type Id = PaymentId; + + fn id(&self) -> Self::Id { + self.id } } @@ -403,8 +340,8 @@ mod tests { PaymentDirection::Outbound, PaymentStatus::Pending, ); - let pending = - PendingPaymentDetails::new(details, vec![first_txid, counterparty_txid], candidates); + let mut pending = PendingPaymentDetails::new(details, vec![first_txid, counterparty_txid]); + pending.candidates = candidates; // Each candidate resolves to its own figures, so a non-last candidate that confirms reports // its own (lower) fee rather than the last-broadcast candidate's. @@ -442,16 +379,10 @@ mod tests { let mut pending_payment = PendingPaymentDetails::new( pending_onchain_payment(payment_id, replacement_txid), vec![original_txid], - Vec::new(), ); - let update = PendingPaymentDetails::new( - pending_onchain_payment(payment_id, original_txid), - Vec::new(), - Vec::new(), - ) - .to_update(); + let observed = pending_onchain_payment(payment_id, original_txid); - assert!(pending_payment.update(update)); + assert!(pending_payment.merge_observed(&observed, Vec::new())); assert_eq!( pending_payment.conflicting_txids(), Vec::::new(), @@ -464,16 +395,16 @@ mod tests { // An entry carrying a payment record and its candidate history. let payment_id = PaymentId([7u8; 32]); let txid = Txid::from_byte_array([8u8; 32]); - let record = PendingPaymentDetails::new( + let mut record = PendingPaymentDetails::new( pending_onchain_payment(payment_id, txid), vec![Txid::from_byte_array([9u8; 32])], - vec![FundingTxCandidate { - txid, - amount_msat: Some(1_000), - fee_paid_msat: Some(100), - awaiting_broadcast: false, - }], ); + record.candidates = vec![FundingTxCandidate { + txid, + amount_msat: Some(1_000), + fee_paid_msat: Some(100), + awaiting_broadcast: false, + }]; let encoded = record.encode(); let decoded = PendingPaymentDetails::read(&mut &encoded[..]).unwrap(); @@ -495,7 +426,10 @@ mod tests { fn entry(candidates: Vec) -> PendingPaymentDetails { let payment_id = PaymentId([1u8; 32]); let txid = candidates.last().expect("at least one candidate").txid; - PendingPaymentDetails::new(pending_onchain_payment(payment_id, txid), vec![], candidates) + let mut entry = + PendingPaymentDetails::new(pending_onchain_payment(payment_id, txid), vec![]); + entry.candidates = candidates; + entry } /// An entry written by a node from before the rounds LDK promoted were kept on it reads as an @@ -524,8 +458,8 @@ mod tests { assert_eq!(decoded, stored); } - /// The rounds LDK promoted round-trip with the entry, absent or present, and the merge of a - /// record's full update, as wallet sync writes it, leaves them. + /// The rounds LDK promoted round-trip with the entry, absent or present, and the merge of what + /// wallet sync observed about the payment leaves them. #[test] fn locked_rounds_round_trip_and_survive_a_merge() { let mut stored = entry(vec![candidate(2, false)]); @@ -539,9 +473,9 @@ mod tests { Readable::read(&mut &stored.encode()[..]).expect("encoding must round-trip"); assert_eq!(decoded, stored); - let synced = entry(vec![candidate(2, false), candidate(3, false)]); - assert!(stored.update(synced.to_update())); - assert_eq!(stored.candidates().len(), 2); + let observed = pending_onchain_payment(stored.id, test_txid(3)); + assert!(stored.merge_observed(&observed, Vec::new())); + assert_eq!(stored.candidates(), &[candidate(2, false)]); assert_eq!(stored.locked_rounds(), &[test_txid(2)]); } } diff --git a/src/wallet/mod.rs b/src/wallet/mod.rs index 5cc62a5bbd..901dc9f4fb 100644 --- a/src/wallet/mod.rs +++ b/src/wallet/mod.rs @@ -68,8 +68,6 @@ use crate::data_store::{KeepAllEntries, KeepLeastRecentlyUsed}; use crate::data_store::{StorableObject, UpdatableObject}; use crate::fee_estimator::{ConfirmationTarget, FeeEstimator, OnchainFeeEstimator}; use crate::logger::{log_debug, log_error, log_info, log_trace, log_warn, LdkLogger, Logger}; -#[cfg(test)] -use crate::payment::pending_payment_store::PendingPaymentDetailsUpdate; use crate::payment::store::{Channel, ConfirmationStatus, PaymentDetailsUpdate}; use crate::payment::{ FundingTxCandidate, PaymentDetails, PaymentDirection, PaymentKind, PaymentStatus, @@ -3781,9 +3779,7 @@ impl Wallet { return Ok(None); } Ok(match existing { - None => { - Some(PendingPaymentDetails::new(payment, conflicting_txids, Vec::new())) - }, + None => Some(PendingPaymentDetails::new(payment, conflicting_txids)), // Promote an entry that has no record yet: wallet sync saw the splice // transaction before this node recorded a payment for it. The entry keeps // its signed rounds and gains the record. @@ -3793,9 +3789,7 @@ impl Wallet { Some(entry) }, Some(mut tracked) => { - let fresh = - PendingPaymentDetails::new(payment, conflicting_txids, Vec::new()); - tracked.update(fresh.to_update()).then_some(tracked) + tracked.merge_observed(&payment, conflicting_txids).then_some(tracked) }, }) }) @@ -5264,8 +5258,23 @@ mod tests { async fn track_pending(wallet: &Wallet, details: PaymentDetails, conflicting_txids: Vec) { let stores = wallet.payment_stores.lock().await; stores.insert_or_update_payment(details.clone()).await.unwrap(); - let entry = PendingPaymentDetails::new(details, conflicting_txids, Vec::new()); - stores.pending_payment_store().insert_or_update(entry).await.unwrap(); + stores + .pending_payment_store() + .mutate(&details.id, |existing| match existing { + Some(existing) => { + let mut merged = existing.clone(); + merged.merge_observed(&details, conflicting_txids).then_some(merged) + }, + None => Some(PendingPaymentDetails::new(details.clone(), conflicting_txids)), + }) + .await + .unwrap(); + } + + /// Writes `entry` where the store has no entry under its id yet. + async fn insert_entry(wallet: &Wallet, entry: PendingPaymentDetails) { + assert!(entry_of(wallet, &entry.id).await.is_none()); + wallet.payment_stores.pending_payment_store().insert(entry).await.unwrap(); } /// Records that wallet sync saw `conflicting_txids` conflict with the payment's transaction. @@ -5273,11 +5282,18 @@ mod tests { wallet .payment_stores .pending_payment_store() - .update(PendingPaymentDetailsUpdate { - id, - payment_update: None, - conflicting_txids: Some(conflicting_txids), - candidates: Vec::new(), + .mutate(&id, |existing| { + let mut entry = existing?.clone(); + let current_txid = match entry.details().map(|details| &details.kind) { + Some(PaymentKind::Onchain { txid, .. }) => Some(*txid), + _ => None, + }; + let mut conflicting_txids = conflicting_txids; + conflicting_txids.retain(|txid| Some(*txid) != current_txid); + (entry.conflicting_txids != conflicting_txids).then(|| { + entry.conflicting_txids = conflicting_txids; + entry + }) }) .await .unwrap(); @@ -8256,8 +8272,8 @@ mod tests { // classification above landed. let mut stale = interactive_funding_details(payment_id, txid, Some(0), Some(0)); stale.kind = PaymentKind::Onchain { txid, status: confirmed, tx_type }; - let entry = PendingPaymentDetails::new(stale, Vec::new(), Vec::new()); - wallet.payment_stores.pending_payment_store().insert_or_update(entry).await.unwrap(); + let entry = PendingPaymentDetails::new(stale, Vec::new()); + insert_entry(&wallet, entry).await; let block_id = |height| BlockId { height, hash: bitcoin::BlockHash::from_byte_array([7u8; 32]) }; @@ -8306,8 +8322,8 @@ mod tests { status: confirmed, tx_type: Some(TransactionType::InteractiveFunding { channels: vec![] }), }; - let entry = PendingPaymentDetails::new(snapshot, Vec::new(), Vec::new()); - wallet.payment_stores.pending_payment_store().insert_or_update(entry).await.unwrap(); + let entry = PendingPaymentDetails::new(snapshot, Vec::new()); + insert_entry(&wallet, entry).await; let block_id = |height| BlockId { height, hash: bitcoin::BlockHash::from_byte_array([7u8; 32]) }; @@ -8363,8 +8379,9 @@ mod tests { }, ]; let details = interactive_funding_details(payment_id, txid3, Some(1_000_000), Some(700)); - let entry = PendingPaymentDetails::new(details, Vec::new(), candidates); - wallet.payment_stores.pending_payment_store().insert_or_update(entry).await.unwrap(); + let mut entry = PendingPaymentDetails::new(details, Vec::new()); + entry.candidates = candidates; + insert_entry(&wallet, entry).await; // The first candidate resolves via the txid-derived id and the active candidate via the // record's current txid; the middle one must resolve through the candidate history. @@ -9190,8 +9207,9 @@ mod tests { fee_paid_msat: Some(500), awaiting_broadcast: false, }]; - let entry = PendingPaymentDetails::new(snapshot, vec![close_txid], candidates); - wallet.payment_stores.pending_payment_store().insert_or_update(entry).await.unwrap(); + let mut entry = PendingPaymentDetails::new(snapshot, vec![close_txid]); + entry.candidates = candidates; + insert_entry(&wallet, entry).await; insert_confirmed_tx(&wallet, close_tx, 5); @@ -9241,8 +9259,9 @@ mod tests { fee_paid_msat: Some(500), awaiting_broadcast: false, }]; - let entry = PendingPaymentDetails::new(snapshot, vec![close_txid], candidates); - wallet.payment_stores.pending_payment_store().insert_or_update(entry).await.unwrap(); + let mut entry = PendingPaymentDetails::new(snapshot, vec![close_txid]); + entry.candidates = candidates; + insert_entry(&wallet, entry).await; insert_confirmed_tx(&wallet, close_tx, 5); @@ -10209,13 +10228,8 @@ mod tests { PaymentStatus::Pending, ); wallet.payment_stores.payment_store().insert_or_update(duplicate.clone()).await.unwrap(); - let duplicate_entry = PendingPaymentDetails::new(duplicate.clone(), Vec::new(), Vec::new()); - wallet - .payment_stores - .pending_payment_store() - .insert_or_update(duplicate_entry.clone()) - .await - .unwrap(); + let duplicate_entry = PendingPaymentDetails::new(duplicate.clone(), Vec::new()); + insert_entry(&wallet, duplicate_entry.clone()).await; let entry_before = entry_of(&wallet, &id).await.expect("entry"); let rounds = entry_before.candidates().to_vec(); @@ -12201,7 +12215,6 @@ mod tests { let entry = PendingPaymentDetails::new( funding_payment(id, close_txid, PaymentStatus::Pending), Vec::new(), - Vec::new(), ); wallet.payment_stores.pending_payment_store().insert(entry).await.unwrap(); @@ -12225,16 +12238,16 @@ mod tests { // A pending record listing the funding transaction among its candidates: its // classification can still be written, and these facts are what would write it. let id = PaymentId([44u8; 32]); - let entry = PendingPaymentDetails::new( + let mut entry = PendingPaymentDetails::new( funding_payment(id, Txid::from_byte_array([45u8; 32]), PaymentStatus::Pending), Vec::new(), - vec![FundingTxCandidate { - txid: funding_txid, - amount_msat: Some(1_000), - fee_paid_msat: Some(10), - awaiting_broadcast: false, - }], ); + entry.candidates = vec![FundingTxCandidate { + txid: funding_txid, + amount_msat: Some(1_000), + fee_paid_msat: Some(10), + awaiting_broadcast: false, + }]; wallet.payment_stores.pending_payment_store().insert(entry).await.unwrap(); chain_tip_changed(&wallet, LONG_AFTER).await; @@ -12546,7 +12559,7 @@ mod tests { wallet .payment_stores .pending_payment_store() - .insert(PendingPaymentDetails::new(payment, Vec::new(), Vec::new())) + .insert(PendingPaymentDetails::new(payment, Vec::new())) .await .unwrap(); } @@ -12712,7 +12725,7 @@ mod tests { wallet .payment_stores .pending_payment_store() - .insert(PendingPaymentDetails::new(payment.clone(), vec![original_txid], Vec::new())) + .insert(PendingPaymentDetails::new(payment.clone(), vec![original_txid])) .await .unwrap(); @@ -12756,7 +12769,7 @@ mod tests { wallet .payment_stores .pending_payment_store() - .insert(PendingPaymentDetails::new(payment, vec![original_txid], Vec::new())) + .insert(PendingPaymentDetails::new(payment, vec![original_txid])) .await .unwrap(); @@ -12844,7 +12857,7 @@ mod tests { PaymentStatus::Pending, ); wallet.payment_stores.payment_store().insert(details.clone()).await.unwrap(); - let entry = PendingPaymentDetails::new(details, vec![txid_a], Vec::new()); + let entry = PendingPaymentDetails::new(details, vec![txid_a]); wallet.payment_stores.pending_payment_store().insert(entry).await.unwrap(); // Bump again: B -> C. From 25ee8ce74182ee2f419e534e6ed99f9e6174ac58 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Tue, 17 Nov 2026 11:02:29 +0100 Subject: [PATCH 04/11] Track only the txid in pending payment entries Each pending entry mirrored the full payment record, so every confirmation or reorg wrote both stores, and the copies could disagree: a late classification left the mirror's transaction type stale, and a failed mirror write left a confirmed payment that never graduated. Entries now keep only the record's current txid, and the payment store is the sole source of status, confirmation, direction and type. An entry is written only when its txid, conflicts or channels change; the channels of an interactive funding are set from its classification. The chain-tip pass reads each record, skips one it cannot read, and removes the entry of a settled record. The persisted entry format changes without a compatibility read, as no release has written it. Written with the help of an AI tool. Co-Authored-By: HAL 9000 --- src/payment/pending_payment_store.rs | 192 +++----- src/wallet/mod.rs | 647 +++++++++++++++++++-------- src/wallet/payment_stores.rs | 13 - 3 files changed, 532 insertions(+), 320 deletions(-) diff --git a/src/payment/pending_payment_store.rs b/src/payment/pending_payment_store.rs index 9c994d465b..c463d41569 100644 --- a/src/payment/pending_payment_store.rs +++ b/src/payment/pending_payment_store.rs @@ -9,9 +9,8 @@ use bitcoin::Txid; use lightning::impl_writeable_tlv_based; use lightning::ln::channelmanager::PaymentId; -use crate::data_store::{StorableObject, UpdatableObject}; -use crate::payment::store::{Channel, TransactionType}; -use crate::payment::{PaymentDetails, PaymentKind}; +use crate::data_store::StorableObject; +use crate::payment::store::Channel; /// One candidate transaction in an interactive-funding (splice) RBF history, holding this node's /// share of the funding amount and fee for that candidate. Both are `None` for a candidate this @@ -46,10 +45,12 @@ impl_writeable_tlv_based!(FundingTxCandidate, { /// A pending payment tracked by LDK Node, keyed by [`PaymentId`]. /// +/// The payment's record in the payment store is what says its status, confirmation, direction and +/// transaction type; an entry only indexes the transactions that may still change the record. /// Each part of an entry is written by a different subsystem and is present on its own schedule, /// so all of them are optional. Signing a round of a splice adds the round to `candidates` and /// lists the `funding_channels` it belongs to, before any transaction anyone has seen; wallet -/// sync adds `details` once it observes the transaction, and records `conflicting_txids` for any +/// sync sets `txid` once it observes the transaction, and records `conflicting_txids` for any /// wallet transaction; the `ChannelReady` arm records `locked_rounds`. A splice uses all of them; /// the fields do not partition by payment type. An entry with none of them tracks no payment and /// is removed. @@ -57,18 +58,18 @@ impl_writeable_tlv_based!(FundingTxCandidate, { pub(crate) struct PendingPaymentDetails { /// The payment this entry tracks. pub id: PaymentId, - /// The full payment details, or `None` for a splice whose transaction wallet sync has yet to - /// observe — including one this node has signed that was never broadcast. - pub details: Option, + /// The payment record's current transaction, or `None` for a splice whose transaction wallet + /// sync has yet to observe — including one this node has signed that was never broadcast — + /// and which therefore has no payment record yet. + pub txid: Option, /// Transaction IDs wallet sync observed to have replaced or to conflict with this /// payment, used to map later events about those txids back to this record. This is /// BDK's view, distinct from `candidates`: it can list conflicts that were never /// negotiated candidates, while a candidate replaced between wallet syncs may never /// appear here (it gets no `TxReplaced` event of its own). pub conflicting_txids: Vec, - /// The channels whose interactive funding `candidates` are rounds of, as the signing of a - /// round recorded them. Empty for a non-funding payment and for a record wallet sync created - /// on its own, whose channels its classification lists instead. + /// The channels whose interactive funding this entry tracks, as the signing of a round or the + /// record's classification listed them. Empty for a non-funding payment. pub funding_channels: Vec, /// For interactive funding (splices), this node's per-candidate funding figures across the /// RBF history, keyed by each candidate's txid and recorded as each round is signed. @@ -83,10 +84,10 @@ pub(crate) struct PendingPaymentDetails { } impl PendingPaymentDetails { - pub(crate) fn new(details: PaymentDetails, conflicting_txids: Vec) -> Self { + pub(crate) fn new(id: PaymentId, txid: Txid, conflicting_txids: Vec) -> Self { Self { - id: details.id, - details: Some(details), + id, + txid: Some(txid), conflicting_txids, funding_channels: Vec::new(), candidates: Vec::new(), @@ -102,7 +103,7 @@ impl PendingPaymentDetails { ) -> Self { Self { id, - details: None, + txid: None, conflicting_txids: Vec::new(), funding_channels, candidates, @@ -110,9 +111,10 @@ impl PendingPaymentDetails { } } - /// The full payment details, or `None` for a splice whose transaction has not been observed. - pub(crate) fn details(&self) -> Option<&PaymentDetails> { - self.details.as_ref() + /// The payment record's current transaction, or `None` for a splice whose transaction has not + /// been observed. + pub(crate) fn txid(&self) -> Option { + self.txid } /// Transaction IDs that have replaced or conflict with this payment. @@ -146,59 +148,50 @@ impl PendingPaymentDetails { &self.candidates } - /// The channels of the interactive funding this entry tracks: those the signing of a round - /// recorded, else those its classification lists. + /// The channels of the interactive funding this entry tracks. pub(crate) fn funding_channels(&self) -> &[Channel] { - if !self.funding_channels.is_empty() { - return &self.funding_channels; - } - match self.details.as_ref().map(|details| &details.kind) { - Some(PaymentKind::Onchain { - tx_type: Some(TransactionType::InteractiveFunding { channels }), - .. - }) => channels, - _ => &[], - } + &self.funding_channels } - /// Merges what wallet sync observed about the entry's payment into it: `payment`'s update is - /// applied to the recorded payment, if any, and a non-empty `conflicting_txids` replaces the - /// recorded conflicts. The payment's current txid never stays listed as its own conflict. - /// Returns whether the entry changed. - pub(crate) fn merge_observed( - &mut self, payment: &PaymentDetails, conflicting_txids: Vec, - ) -> bool { - let mut updated = false; - if let Some(details) = self.details.as_mut() { - updated |= details.update(payment.to_update()); + /// Lists `channels` as the channels of the interactive funding this entry tracks, unless it + /// lists some already. Returns whether the entry changed. + pub(crate) fn track_funding_channels(&mut self, channels: &[Channel]) -> bool { + if !self.funding_channels.is_empty() || channels.is_empty() { + return false; } + self.funding_channels = channels.to_vec(); + true + } + + /// Merges what wallet sync observed about the entry's payment into it: `txid` becomes the + /// record's current transaction, and a non-empty `conflicting_txids` replaces the recorded + /// conflicts. The current txid never stays listed as its own conflict. Returns whether the + /// entry changed. + pub(crate) fn merge_observed(&mut self, txid: Txid, conflicting_txids: Vec) -> bool { + let mut updated = self.txid != Some(txid); + self.txid = Some(txid); if !conflicting_txids.is_empty() && self.conflicting_txids != conflicting_txids { self.conflicting_txids = conflicting_txids; updated = true; } - if let Some(PaymentKind::Onchain { txid, .. }) = - self.details.as_ref().map(|details| &details.kind) - { - let txid = *txid; - let conflicts_len = self.conflicting_txids.len(); - self.conflicting_txids.retain(|conflicting_txid| *conflicting_txid != txid); - updated |= self.conflicting_txids.len() != conflicts_len; - } + let conflicts_len = self.conflicting_txids.len(); + self.conflicting_txids.retain(|conflicting_txid| *conflicting_txid != txid); + updated |= self.conflicting_txids.len() != conflicts_len; updated } /// Whether this entry tracks nothing anymore and can be dropped. pub(crate) fn is_empty(&self) -> bool { - self.details.is_none() && self.candidates.is_empty() && self.locked_rounds.is_empty() + self.txid.is_none() && self.candidates.is_empty() && self.locked_rounds.is_empty() } } impl_writeable_tlv_based!(PendingPaymentDetails, { (0, id, required), - (2, details, option), + (2, txid, option), (4, conflicting_txids, optional_vec), (6, funding_channels, optional_vec), (8, candidates, optional_vec), @@ -293,8 +286,6 @@ mod tests { use lightning::util::ser::{Readable, Writeable}; use super::*; - use crate::payment::store::ConfirmationStatus; - use crate::payment::{PaymentDirection, PaymentKind, PaymentStatus}; #[test] fn pending_payment_candidate_lookup() { @@ -326,21 +317,8 @@ mod tests { }, ]; - // The stored details only need to be a valid funding payment; `candidate` resolves figures - // purely from the recorded candidate list. - let details = PaymentDetails::new( - payment_id, - PaymentKind::Onchain { - txid: rbf_txid, - status: ConfirmationStatus::Unconfirmed, - tx_type: None, - }, - Some(1_000_000), - Some(5_000), - PaymentDirection::Outbound, - PaymentStatus::Pending, - ); - let mut pending = PendingPaymentDetails::new(details, vec![first_txid, counterparty_txid]); + let mut pending = + PendingPaymentDetails::new(payment_id, rbf_txid, vec![first_txid, counterparty_txid]); pending.candidates = candidates; // Each candidate resolves to its own figures, so a non-last candidate that confirms reports @@ -359,30 +337,17 @@ mod tests { Txid::from_byte_array([byte; 32]) } - fn pending_onchain_payment(payment_id: PaymentId, txid: Txid) -> PaymentDetails { - PaymentDetails::new( - payment_id, - PaymentKind::Onchain { txid, status: ConfirmationStatus::Unconfirmed, tx_type: None }, - Some(1_000), - Some(100), - PaymentDirection::Outbound, - PaymentStatus::Pending, - ) - } - #[test] fn pending_onchain_conflicts_exclude_current_txid_after_txid_rotation() { let original_txid = test_txid(1); let replacement_txid = test_txid(2); let payment_id = PaymentId(original_txid.to_byte_array()); - let mut pending_payment = PendingPaymentDetails::new( - pending_onchain_payment(payment_id, replacement_txid), - vec![original_txid], - ); - let observed = pending_onchain_payment(payment_id, original_txid); + let mut pending_payment = + PendingPaymentDetails::new(payment_id, replacement_txid, vec![original_txid]); - assert!(pending_payment.merge_observed(&observed, Vec::new())); + assert!(pending_payment.merge_observed(original_txid, Vec::new())); + assert_eq!(pending_payment.txid(), Some(original_txid)); assert_eq!( pending_payment.conflicting_txids(), Vec::::new(), @@ -390,15 +355,25 @@ mod tests { ); } + /// Observing the transaction an entry already tracks, with no new conflicts, leaves it as it + /// is: a change of the record's status or confirmation alone is not the entry's to track. + #[test] + fn observing_the_tracked_transaction_again_changes_nothing() { + let txid = test_txid(1); + let mut entry = PendingPaymentDetails::new(PaymentId([1u8; 32]), txid, vec![test_txid(2)]); + let before = entry.clone(); + assert!(!entry.merge_observed(txid, Vec::new())); + assert!(!entry.merge_observed(txid, vec![test_txid(2)])); + assert_eq!(entry, before); + } + #[test] fn tracked_payment_round_trips() { - // An entry carrying a payment record and its candidate history. + // An entry carrying a transaction and its candidate history. let payment_id = PaymentId([7u8; 32]); let txid = Txid::from_byte_array([8u8; 32]); - let mut record = PendingPaymentDetails::new( - pending_onchain_payment(payment_id, txid), - vec![Txid::from_byte_array([9u8; 32])], - ); + let mut record = + PendingPaymentDetails::new(payment_id, txid, vec![Txid::from_byte_array([9u8; 32])]); record.candidates = vec![FundingTxCandidate { txid, amount_msat: Some(1_000), @@ -410,7 +385,14 @@ mod tests { let decoded = PendingPaymentDetails::read(&mut &encoded[..]).unwrap(); assert_eq!(record, decoded); assert_eq!(decoded.id(), payment_id); - assert!(decoded.details().is_some()); + assert_eq!(decoded.txid(), Some(txid)); + + // The rounds of a splice signed before any transaction was observed. + let signed = + PendingPaymentDetails::signed_rounds(payment_id, Vec::new(), record.candidates); + let decoded = PendingPaymentDetails::read(&mut &signed.encode()[..]).unwrap(); + assert_eq!(decoded, signed); + assert_eq!(decoded.txid(), None); } /// A candidate with the given txid byte, with a stake of ours in it if `ours`. @@ -426,38 +408,11 @@ mod tests { fn entry(candidates: Vec) -> PendingPaymentDetails { let payment_id = PaymentId([1u8; 32]); let txid = candidates.last().expect("at least one candidate").txid; - let mut entry = - PendingPaymentDetails::new(pending_onchain_payment(payment_id, txid), vec![]); + let mut entry = PendingPaymentDetails::new(payment_id, txid, vec![]); entry.candidates = candidates; entry } - /// An entry written by a node from before the rounds LDK promoted were kept on it reads as an - /// entry without them, everything else intact. - #[test] - fn an_entry_written_without_locked_rounds_reads_with_none() { - let mut stored = entry(vec![candidate(2, false), candidate(3, true)]); - stored.conflicting_txids = vec![test_txid(9)]; - - let write_as_before = || -> Result, lightning::io::Error> { - let mut written = Vec::new(); - lightning::write_tlv_fields!(&mut written, { - (0, stored.id, required), - (2, stored.details, option), - (4, stored.conflicting_txids, optional_vec), - (6, stored.funding_channels, optional_vec), - (8, stored.candidates, optional_vec), - }); - Ok(written) - }; - let written_before = write_as_before().unwrap(); - - let decoded: PendingPaymentDetails = Readable::read(&mut &written_before[..]) - .expect("an entry written before the rounds were kept still reads"); - assert!(decoded.locked_rounds().is_empty()); - assert_eq!(decoded, stored); - } - /// The rounds LDK promoted round-trip with the entry, absent or present, and the merge of what /// wallet sync observed about the payment leaves them. #[test] @@ -473,8 +428,7 @@ mod tests { Readable::read(&mut &stored.encode()[..]).expect("encoding must round-trip"); assert_eq!(decoded, stored); - let observed = pending_onchain_payment(stored.id, test_txid(3)); - assert!(stored.merge_observed(&observed, Vec::new())); + assert!(stored.merge_observed(test_txid(3), Vec::new())); assert_eq!(stored.candidates(), &[candidate(2, false)]); assert_eq!(stored.locked_rounds(), &[test_txid(2)]); } diff --git a/src/wallet/mod.rs b/src/wallet/mod.rs index 901dc9f4fb..3b1c49649e 100644 --- a/src/wallet/mod.rs +++ b/src/wallet/mod.rs @@ -565,26 +565,41 @@ impl Wallet { /// The transactions of this node's own on-chain sends that have yet to confirm, each with the /// transactions it replaced. + /// + /// A record that cannot be read is left out, so that its send is merely not returned to the + /// wallet's view by this sync. async fn pending_send_txids(&self) -> Vec<(Txid, Vec)> { - self.payment_stores - .pending_payments(|pending| { - pending.details().is_some_and(|details| { - details.direction == PaymentDirection::Outbound - && details.status == PaymentStatus::Pending - }) - }) - .await - .iter() - .filter_map(|pending| match pending.details()?.kind { - // A transaction of a channel carries a type, and is LDK's to rebroadcast. - PaymentKind::Onchain { - txid, - status: ConfirmationStatus::Unconfirmed, - tx_type: None, - } => Some((txid, pending.conflicting_txids().to_vec())), - _ => None, - }) - .collect() + let mut sends = Vec::new(); + for pending in self.payment_stores.pending_payments(|p| p.txid().is_some()).await { + let record = match self.payment_stores.payment(&pending.id()).await { + Ok(Some(record)) => record, + Ok(None) => continue, + Err(e) => { + log_error!( + self.logger, + "Failed to read payment {} to check for a pending send: {}", + pending.id(), + e + ); + continue; + }, + }; + if record.direction != PaymentDirection::Outbound + || record.status != PaymentStatus::Pending + { + continue; + } + // A transaction of a channel carries a type, and is LDK's to rebroadcast. + if let PaymentKind::Onchain { + txid, + status: ConfirmationStatus::Unconfirmed, + tx_type: None, + } = record.kind + { + sends.push((txid, pending.conflicting_txids().to_vec())); + } + } + sends } /// Returns the given sends to the wallet's view if a chain source update evicted them. @@ -783,32 +798,35 @@ impl Wallet { self.record_wallet_tx(txid, &tx, payment_status, confirmation_status).await?; }, WalletEvent::ChainTipChanged { new_tip, .. } => { - let pending_payments: Vec = self - .payment_stores - .pending_payments(|p| match p.details() { - // An entry whose transaction wallet sync has yet to observe doesn't - // have a payment record yet, so it cannot graduate. - None => false, - Some(details) => { - debug_assert!( - details.status == PaymentStatus::Pending, - "Non-pending payment {:?} found in pending store", - details.id, - ); - details.status == PaymentStatus::Pending - && matches!(details.kind, PaymentKind::Onchain { .. }) - }, - }) - .await; + // An entry whose transaction wallet sync has yet to observe doesn't have a + // payment record yet, so it cannot graduate. + let pending_payments: Vec = + self.payment_stores.pending_payments(|p| p.txid().is_some()).await; let mut unconfirmed_outbound_txids: Vec = Vec::new(); let mut unclassified_transactions: Vec<(PaymentId, Txid)> = Vec::new(); for payment in pending_payments { - // The filter admits only entries with a record. - let Some(details) = payment.details() else { - continue; + // The pass is re-derived at every tip, so an entry whose record cannot be + // read now is left for the next one rather than costing the others theirs. + let details = match self.payment_stores.payment(&payment.id()).await { + Ok(Some(details)) => details, + Ok(None) => continue, + Err(e) => { + log_error!( + self.logger, + "Failed to read pending payment {} at chain tip {}: {}", + payment.id(), + new_tip.height, + e + ); + continue; + }, }; + if details.status != PaymentStatus::Pending { + self.remove_entry_of_settled_payment(details.id).await; + continue; + } // A record written before the channel that produced its transaction // reported what the transaction is says nothing about it yet. The report @@ -870,7 +888,11 @@ impl Wallet { .. } => { if self - .fail_funding_payment_lost_to_conflict(&payment, new_tip.height) + .fail_funding_payment_lost_to_conflict( + &payment, + &details, + new_tip.height, + ) .await? { continue; @@ -926,9 +948,9 @@ impl Wallet { }, WalletEvent::TxReplaced { txid, conflicts, .. } => { // See `record_wallet_tx`: id resolution and the writes below must not - // interleave with the funding-record writers. The pending entry written below - // embeds a read of the payment record, which must not go stale against a - // concurrent write either. + // interleave with the funding-record writers. Whether the pending entry is + // written below is decided from a read of the payment record, which must not go + // stale against a concurrent write either. let stores = self.payment_stores.lock().await; let Some(payment_id) = self.find_payment_by_txid(txid).await? else { @@ -962,10 +984,8 @@ impl Wallet { // A terminal record means the entry is the leftover of an interrupted settle // — the record write landed, the entry removal was lost to a crash — and this - // event is the restart's replay of the same transition. Re-embedding the - // record would stamp the terminal status into the entry and hide it from the - // pending listing that repairs such leftovers; finish the interrupted removal - // instead. + // event is the restart's replay of the same transition: finish the interrupted + // removal. if payment.status != PaymentStatus::Pending { stores.remove_pending_payment(&payment_id).await?; continue; @@ -1067,6 +1087,24 @@ impl Wallet { Ok(()) } + /// Removes the entry of the payment `id` if its record is settled, as a write landing between + /// the record's settlement and the entry's removal leaves it. Decided from the record as read + /// under the lock, as a concurrent reorg may have taken the record back to `Pending`. A failure + /// is logged, and the next chain tip tries again. + async fn remove_entry_of_settled_payment(&self, id: PaymentId) { + let stores = self.payment_stores.lock().await; + let result = match stores.payment(&id).await { + Ok(Some(record)) if record.status != PaymentStatus::Pending => { + stores.remove_pending_payment(&id).await + }, + Ok(_) => Ok(()), + Err(e) => Err(e), + }; + if let Err(e) = result { + log_error!(self.logger, "Failed to remove the entry of settled payment {}: {}", id, e); + } + } + /// Classifies the transactions of the given payments from the facts this node has recorded /// about them, for records that do not say what their transaction is. /// @@ -1091,11 +1129,27 @@ impl Wallet { continue; }; + // Taken per payment, like the graduation above. + let stores = self.payment_stores.lock().await; + // An interactive funding's entry tracks its channels. They are listed before the + // record is classified, so that a failure in between leaves the record unclassified + // for the next chain tip to retry. + if let TransactionType::InteractiveFunding { channels } = &tx_type { + let unclassified = matches!( + stores.payment(&payment_id).await?, + Some(PaymentDetails { kind: PaymentKind::Onchain { tx_type: None, .. }, .. }) + ); + if unclassified { + stores + .mutate_pending_payment(&payment_id, |existing| { + let mut entry = existing?.clone(); + entry.track_funding_channels(channels).then_some(entry) + }) + .await?; + } + } let mut update = PaymentDetailsUpdate::new(payment_id); update.tx_type = Some(Some(tx_type)); - // Taken per payment, like the graduation above: the write touches one record and - // leaves its pending entry alone. - let stores = self.payment_stores.lock().await; let classified = stores .mutate_payment(&payment_id, |existing| { let current = existing?; @@ -1263,11 +1317,7 @@ impl Wallet { async fn pending_referenced_txids(&self) -> HashSet { let mut txids = HashSet::new(); for entry in self.payment_stores.pending_payments(|_| true).await { - if let Some(PaymentKind::Onchain { txid, .. }) = - entry.details().map(|details| &details.kind) - { - txids.insert(*txid); - } + txids.extend(entry.txid()); txids.extend(entry.candidates().iter().map(|candidate| candidate.txid)); txids.extend(entry.conflicting_txids().iter().copied()); txids.extend(entry.locked_rounds().iter().copied()); @@ -1327,23 +1377,23 @@ impl Wallet { /// confirm. Nor does a round's absence from the wallet's transaction graph: the graph learns a /// transaction from wallet sync alone, and the counterparty has the same signed round and may /// broadcast it, so a round the wallet never saw is not counted as one that cannot confirm. + /// + /// `payment` and `record` are the entry and its record as the tip pass listed them; the + /// decision is made from both as read again under the lock. async fn fail_funding_payment_lost_to_conflict( - &self, payment: &PendingPaymentDetails, tip_height: u32, + &self, payment: &PendingPaymentDetails, record: &PaymentDetails, tip_height: u32, ) -> Result { - let payment_id = match payment.details() { - Some(details) => match details.kind { - PaymentKind::Onchain { - status: ConfirmationStatus::Unconfirmed, - tx_type: - Some( - TransactionType::Funding { .. } - | TransactionType::InteractiveFunding { .. }, - ), - .. - } => details.id, - _ => return Ok(false), - }, - None => return Ok(false), + let payment_id = match record.kind { + PaymentKind::Onchain { + status: ConfirmationStatus::Unconfirmed, + tx_type: + Some( + TransactionType::Funding { .. } + | TransactionType::InteractiveFunding { .. }, + ), + .. + } => record.id, + _ => return Ok(false), }; if payment.conflicting_txids().is_empty() { return Ok(false); @@ -1364,20 +1414,18 @@ impl Wallet { // between leaves a `Failed` record with a lingering entry. Finish that removal from the // record's status rather than by asking again whether the rounds can confirm: the failure // is already recorded, and the graph may no longer contain the round that caused it. - if let Some(PaymentDetails { status: PaymentStatus::Failed, .. }) = - stores.payment(&payment_id).await? - { - stores.remove_pending_payment(&payment_id).await?; - log_info!( - self.logger, - "Removed the lingering entry of failed funding payment {}", - payment_id, - ); - return Ok(true); - } - - let Some(details) = entry.details() else { - return Ok(false); + let details = match stores.payment(&payment_id).await? { + Some(PaymentDetails { status: PaymentStatus::Failed, .. }) => { + stores.remove_pending_payment(&payment_id).await?; + log_info!( + self.logger, + "Removed the lingering entry of failed funding payment {}", + payment_id, + ); + return Ok(true); + }, + Some(details) if details.status == PaymentStatus::Pending => details, + _ => return Ok(false), }; let (conflicting_txids, candidates) = (&entry.conflicting_txids, &entry.candidates); let record_txid = match details.kind { @@ -1568,8 +1616,19 @@ impl Wallet { }; let entries = stores.pending_payments(|entry| tracks_channel(entry, channel_id)).await; for entry in entries { - let details = match entry.details() { - Some(details) => details, + let details = match entry.txid() { + Some(_) => match stores.payment(&entry.id()).await? { + Some(details) => details, + None => { + log_debug!( + self.logger, + "Funding payment {} {} has no record: leaving its entry as it is", + entry.id(), + occasion, + ); + continue; + }, + }, // An entry with no payment record yet — wallet sync has not observed a // transaction of this splice — has no payment to fail. The drop pass has taken // back its rounds that were never broadcast, so the rounds left are ones LDK @@ -3349,7 +3408,7 @@ impl Wallet { // splice — has no record to hand back or remove: only its history shrinks, and with // the last round of ours it loses the rest of the history too. An entry left tracking // nothing goes. - if entry.details().is_none() { + if entry.txid().is_none() { if handed_back.is_none() { self.withdraw_unshared_attributions(&entry, payment_id).await?; } @@ -3380,7 +3439,8 @@ impl Wallet { continue; } - let mut mirrored = None; + let mut current_txid = None; + let mut record_channels = Vec::new(); let mut history_only = false; match handed_back { Some(active) => { @@ -3391,8 +3451,7 @@ impl Wallet { let current = existing?; if !waits_on_abandoned(current) { history_only = true; - mirrored = Some(current.clone()) - .filter(|current| current.status == PaymentStatus::Pending); + current_txid = pending_onchain_txid(current); return None; } let mut update = PaymentDetailsUpdate::new(payment_id); @@ -3402,7 +3461,7 @@ impl Wallet { update.fee_paid_msat = Some(active.fee_paid_msat); let mut updated = current.clone(); updated.update(update); - mirrored = Some(updated.clone()); + current_txid = Some(active.txid); Some(updated) }) .await?; @@ -3432,20 +3491,27 @@ impl Wallet { // No round of ours remains, so the remaining rounds are the counterparty's // alone, and wallet sync's to record from its own view once they confirm, as // it would have had this node never joined: they lose their attribution to the - // payment, and the entry its history and channels, so that a confirmation + // payment, and the entry its history, so that a confirmation // applied to the record takes no figures from the history either. The record // itself is left as it stands. The attribution goes before the entry's write, // so that a drop cut short is finished by the replayed event. self.withdraw_unshared_attributions(&entry, payment_id).await?; history_only = true; - mirrored = record.filter(|current| current.status == PaymentStatus::Pending); + current_txid = record.as_ref().and_then(pending_onchain_txid); + if let Some(PaymentKind::Onchain { + tx_type: Some(TransactionType::InteractiveFunding { channels }), + .. + }) = record.map(|record| record.kind) + { + record_channels = channels; + } }, } if history_only { // The record does not wait on the dropped rounds: wallet sync moved it on, or an // earlier drop was cut short between the two stores. Only its history shrinks, and - // the entry's copy of the record catches up with the record while the record is - // still pending. + // the entry catches up with the record's transaction while the record is still + // pending. log_warn!( self.logger, "Funding payment {} does not wait on abandoned splice round(s) {:?}: \ @@ -3457,14 +3523,16 @@ impl Wallet { stores .mutate_pending_payment(&payment_id, |existing| { let mut entry = existing?.clone(); + // With its history gone, the entry tracks the channels of the record's own + // classification, if any. if handed_back.is_none() { entry.candidates.clear(); - entry.funding_channels.clear(); + entry.funding_channels = record_channels; } else { entry.candidates.retain(|c| !abandoned_txids.contains(&c.txid)); } - if let Some(mirrored) = mirrored { - entry.details = Some(mirrored); + if let Some(txid) = current_txid { + entry.txid = Some(txid); } Some(entry) }) @@ -3757,41 +3825,38 @@ impl Wallet { PaymentDetails::new(payment_id, kind, amount_msat, fee_paid_msat, direction, payment_status) } - /// Inserts or refreshes the pending-store entry tracking `payment` toward graduation, - /// atomically with reading the entry's current state. + /// Inserts or refreshes the pending-store entry tracking `payment` toward graduation. The + /// entry is written only when it is new or the transaction, conflicts or channels it tracks + /// change: a change of the record's status or confirmation alone is the record's to carry. + /// + /// Every write of an on-chain payment record happens under the lock `stores` holds, so the + /// record read here cannot go stale before the entry is written. async fn upsert_pending_payment( &self, stores: &PaymentStoresGuard<'_>, payment: PaymentDetails, conflicting_txids: Vec, ) -> Result<(), Error> { let id = payment.id; + // Only `Pending` payments belong in the pending store. + let record = stores.payment(&id).await?.unwrap_or(payment); + if record.status != PaymentStatus::Pending { + return Ok(()); + } + let (txid, channels) = match &record.kind { + PaymentKind::Onchain { txid, tx_type, .. } => match tx_type { + Some(TransactionType::InteractiveFunding { channels }) => (*txid, &channels[..]), + _ => (*txid, &[][..]), + }, + _ => return Ok(()), + }; stores - .mutate_pending_payment_async(&id, move |existing| async move { - // Only `Pending` payments belong in the pending store. The authoritative - // status is re-read inside the store's critical section, where it cannot go - // stale against graduation. - let is_pending = stores - .payment(&id) - .await? - .map_or(payment.status == PaymentStatus::Pending, |recorded| { - recorded.status == PaymentStatus::Pending - }); - if !is_pending { - return Ok(None); - } - Ok(match existing { - None => Some(PendingPaymentDetails::new(payment, conflicting_txids)), - // Promote an entry that has no record yet: wallet sync saw the splice - // transaction before this node recorded a payment for it. The entry keeps - // its signed rounds and gains the record. - Some(mut entry) if entry.details().is_none() => { - entry.details = Some(payment); - entry.conflicting_txids = conflicting_txids; - Some(entry) - }, - Some(mut tracked) => { - tracked.merge_observed(&payment, conflicting_txids).then_some(tracked) - }, - }) + .mutate_pending_payment(&id, |existing| { + let mut changed = existing.is_none(); + let mut entry = existing + .cloned() + .unwrap_or_else(|| PendingPaymentDetails::new(id, txid, Vec::new())); + changed |= entry.merge_observed(txid, conflicting_txids); + changed |= entry.track_funding_channels(channels); + changed.then_some(entry) }) .await?; Ok(()) @@ -3836,9 +3901,7 @@ impl Wallet { } let owns = |p: &PendingPaymentDetails| { - p.details().is_some_and( - |d| matches!(d.kind, PaymentKind::Onchain { txid, .. } if txid == target_txid), - ) + p.txid() == Some(target_txid) // A middle RBF round is not the record's current txid and may never have // received a `TxReplaced` event of its own, so map any of its candidate txids // (an earlier RBF round may confirm) back to the record. @@ -3939,10 +4002,9 @@ impl Wallet { let Some(payment) = handled else { return Ok(outcome); }; - // Mirror the refreshed confirmation status onto the pending entry: `ChainTipChanged` - // graduates by reading the pending entry's details, so it must see the new status. This is - // the same dual-write the default `TxConfirmed` path performs; an empty conflicting-txids - // list leaves any stored conflicts intact (the update treats absent as "unchanged"). + // The confirmed candidate may have become the record's transaction, which the pending entry + // then has to track; as on the default `TxConfirmed` path, the entry is written only if + // that changes it. An empty conflicting-txids list leaves any stored conflicts intact. if payment.status == PaymentStatus::Pending { self.upsert_pending_payment(stores, payment, Vec::new()).await?; } @@ -4364,6 +4426,14 @@ fn aggregate_local_stakes(candidate: &FundingCandidate) -> LocalStakeAggregate { } } +/// The transaction of `record` while it is a pending on-chain payment. +fn pending_onchain_txid(record: &PaymentDetails) -> Option { + match record.kind { + PaymentKind::Onchain { txid, .. } if record.status == PaymentStatus::Pending => Some(txid), + _ => None, + } +} + /// Whether `entry` tracks the funding payment of a splice into `channel_id`. fn tracks_channel(entry: &PendingPaymentDetails, channel_id: ChannelId) -> bool { entry.funding_channels().iter().any(|channel| channel.channel_id == channel_id) @@ -5258,19 +5328,46 @@ mod tests { async fn track_pending(wallet: &Wallet, details: PaymentDetails, conflicting_txids: Vec) { let stores = wallet.payment_stores.lock().await; stores.insert_or_update_payment(details.clone()).await.unwrap(); + let tracked = entry_for(&details, Vec::new()); stores .pending_payment_store() - .mutate(&details.id, |existing| match existing { - Some(existing) => { - let mut merged = existing.clone(); - merged.merge_observed(&details, conflicting_txids).then_some(merged) - }, - None => Some(PendingPaymentDetails::new(details.clone(), conflicting_txids)), + .mutate(&details.id, |existing| { + let mut entry = existing.cloned().unwrap_or(tracked); + entry.merge_observed(onchain_txid(&details), conflicting_txids); + entry.track_funding_channels(&details_channels(&details)); + Some(entry) }) .await .unwrap(); } + /// The transaction of the on-chain payment `details`. + fn onchain_txid(details: &PaymentDetails) -> Txid { + match details.kind { + PaymentKind::Onchain { txid, .. } => txid, + _ => panic!("not an on-chain payment: {:?}", details.kind), + } + } + + /// The channels of `details` if it is an interactive funding. + fn details_channels(details: &PaymentDetails) -> Vec { + match &details.kind { + PaymentKind::Onchain { + tx_type: Some(TransactionType::InteractiveFunding { channels }), + .. + } => channels.clone(), + _ => Vec::new(), + } + } + + /// The entry wallet sync writes for the pending on-chain payment `details`. + fn entry_for(details: &PaymentDetails, conflicting_txids: Vec) -> PendingPaymentDetails { + let mut entry = + PendingPaymentDetails::new(details.id, onchain_txid(details), conflicting_txids); + entry.track_funding_channels(&details_channels(details)); + entry + } + /// Writes `entry` where the store has no entry under its id yet. async fn insert_entry(wallet: &Wallet, entry: PendingPaymentDetails) { assert!(entry_of(wallet, &entry.id).await.is_none()); @@ -5284,10 +5381,7 @@ mod tests { .pending_payment_store() .mutate(&id, |existing| { let mut entry = existing?.clone(); - let current_txid = match entry.details().map(|details| &details.kind) { - Some(PaymentKind::Onchain { txid, .. }) => Some(*txid), - _ => None, - }; + let current_txid = entry.txid(); let mut conflicting_txids = conflicting_txids; conflicting_txids.retain(|txid| Some(*txid) != current_txid); (entry.conflicting_txids != conflicting_txids).then(|| { @@ -6465,7 +6559,7 @@ mod tests { .unwrap() .expect("the round identifies its payment"); let entry = entry_of(&wallet, &id).await.expect("entry"); - assert!(entry.details().is_none()); + assert!(entry.txid().is_none()); assert!(entry.candidate(txid).expect("candidate").awaiting_broadcast); assert_eq!( entry.funding_channels(), @@ -6714,7 +6808,7 @@ mod tests { assert_eq!(payments[0].amount_msat, Some(500_300_000)); assert_eq!(payments[0].fee_paid_msat, Some(300_000)); let entry = entry_of(&wallet, &id).await.expect("entry"); - assert_eq!(entry.details().map(|details| details.id), Some(id)); + assert_eq!(entry.txid(), Some(onchain_txid(&payments[0]))); assert!(entry.candidate(txid).expect("candidate").awaiting_broadcast); } @@ -6977,7 +7071,7 @@ mod tests { assert_eq!(payment.status, PaymentStatus::Pending); assert!(matches!(payment.kind, PaymentKind::Onchain { txid: t, .. } if t == bump_txid)); let entry = entry_of(&wallet, &bump_id).await.expect("entry"); - assert_eq!(entry.details(), Some(&payment)); + assert_eq!(entry.txid(), Some(onchain_txid(&payment))); assert!(entry.candidate(bump_txid).expect("candidate").awaiting_broadcast); let failed = record_of(&wallet, &failed_id).await.expect("the failed record stays"); assert_eq!(failed.status, PaymentStatus::Failed); @@ -7396,7 +7490,7 @@ mod tests { ); assert_eq!(payment.amount_msat, Some(500_300_000)); assert_eq!(payment.fee_paid_msat, Some(300_000)); - assert_eq!(record.details(), Some(&payment)); + assert_eq!(record.txid(), Some(onchain_txid(&payment))); assert_eq!(wallet.find_payment_by_txid(txid).await.unwrap(), Some(id)); } @@ -7833,7 +7927,7 @@ mod tests { assert_eq!(record_of(&wallet, &id).await, Some(payment.clone())); let record = entry_of(&wallet, &id).await.expect("record"); assert_eq!(record.candidates().iter().map(|c| c.txid).collect::>(), vec![txid]); - assert_eq!(record.details(), Some(&payment)); + assert_eq!(record.txid(), Some(onchain_txid(&payment))); assert!(record.candidate(bump_txid).is_none()); } @@ -7867,7 +7961,7 @@ mod tests { assert_eq!(record_of(&wallet, &id).await, Some(payment.clone())); let record = entry_of(&wallet, &id).await.expect("record"); assert!(record.candidates().is_empty()); - assert_eq!(record.details(), Some(&payment)); + assert_eq!(record.txid(), Some(onchain_txid(&payment))); } /// A removal that was cut short between the two stores — the payment record went, the pending @@ -7931,10 +8025,7 @@ mod tests { update.fee_paid_msat = Some(Some(300_000)); wallet.payment_stores.payment_store().update(update).await.unwrap(); let entry = entry_of(&wallet, &id).await.expect("entry"); - assert!(matches!( - entry.details().map(|details| &details.kind), - Some(PaymentKind::Onchain { txid: t, .. }) if *t == bump_txid - )); + assert_eq!(entry.txid(), Some(bump_txid)); wallet.drop_abandoned_splice_rounds(channel_id, &[txid]).await.unwrap(); @@ -7943,7 +8034,7 @@ mod tests { let payment = record_of(&wallet, &id).await.expect("payment"); assert!(matches!(payment.kind, PaymentKind::Onchain { txid: t, .. } if t == txid)); assert_eq!(payment.amount_msat, Some(500_300_000)); - assert_eq!(entry.details(), Some(&payment)); + assert_eq!(entry.txid(), Some(onchain_txid(&payment))); assert!(entry.candidate(bump_txid).is_none()); } @@ -8061,9 +8152,8 @@ mod tests { } /// A record that graduated while its pending entry lingers — the entry's removal is still - /// owed — loses the dropped round from its history but keeps the entry's pending copy of the - /// record: the pass that cleans up lingering entries goes by that copy, and a graduated one - /// would leave the entry behind for good. + /// owed — loses the dropped round from its history, while the entry keeps tracking the + /// record's transaction for the chain-tip pass to remove it. #[tokio::test] async fn dropping_leaves_the_entry_of_a_graduated_record_pending() { let store: Arc = Arc::new(DynStoreWrapper(InMemoryStore::new())); @@ -8100,7 +8190,7 @@ mod tests { assert!(matches!(payment.kind, PaymentKind::Onchain { txid: t, .. } if t == bump_txid)); let entry = entry_of(&wallet, &id).await.expect("entry"); assert_eq!(entry.candidates().iter().map(|c| c.txid).collect::>(), vec![txid]); - assert_eq!(entry.details().map(|details| details.status), Some(PaymentStatus::Pending)); + assert_eq!(entry.txid(), Some(bump_txid)); } /// The signing write fails at the pending store: no payment record is minted for a round @@ -8272,7 +8362,7 @@ mod tests { // classification above landed. let mut stale = interactive_funding_details(payment_id, txid, Some(0), Some(0)); stale.kind = PaymentKind::Onchain { txid, status: confirmed, tx_type }; - let entry = PendingPaymentDetails::new(stale, Vec::new()); + let entry = entry_for(&stale, Vec::new()); insert_entry(&wallet, entry).await; let block_id = @@ -8322,7 +8412,7 @@ mod tests { status: confirmed, tx_type: Some(TransactionType::InteractiveFunding { channels: vec![] }), }; - let entry = PendingPaymentDetails::new(snapshot, Vec::new()); + let entry = entry_for(&snapshot, Vec::new()); insert_entry(&wallet, entry).await; let block_id = @@ -8346,6 +8436,193 @@ mod tests { ); } + /// A confirmation and a reorg back to unconfirmed change only the payment record: the entry + /// tracks the same transaction throughout, so neither writes the pending store, and the record + /// still graduates and returns to `Pending`. A reorg after graduation tracks it again. + #[tokio::test] + async fn status_changes_leave_the_pending_store_unwritten() { + let fail_store = + FailSwitchStore::failing_only(PENDING_PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE); + let store: Arc = Arc::new(DynStoreWrapper(fail_store.clone())); + let wallet = new_test_wallet(Arc::clone(&store), false).await; + + let tx = wallet_paying_tx(&wallet, 1); + let txid = tx.compute_txid(); + let id = PaymentId(txid.to_byte_array()); + observe_unconfirmed(&wallet, &tx).await; + assert!(entry_of(&wallet, &id).await.is_some()); + + fail_store.fail_writes.store(true, Ordering::Release); + let height = 10; + let confirmed = WalletEvent::TxConfirmed { + txid, + tx: Arc::new(tx.clone()), + block_time: confirmed_block_time(height), + old_block_time: None, + }; + let unconfirmed = WalletEvent::TxUnconfirmed { + txid, + tx: Arc::new(tx.clone()), + old_block_time: Some(confirmed_block_time(height)), + }; + insert_confirmed_tx(&wallet, tx.clone(), height); + assert!(wallet.update_payment_store(vec![confirmed.clone()]).await.is_ok()); + let record = record_of(&wallet, &id).await.expect("record"); + assert_eq!(record.status, PaymentStatus::Pending); + assert!(matches!( + record.kind, + PaymentKind::Onchain { status: ConfirmationStatus::Confirmed { .. }, .. } + )); + + assert!(wallet.update_payment_store(vec![unconfirmed.clone()]).await.is_ok()); + let record = record_of(&wallet, &id).await.expect("record"); + assert_eq!(record.status, PaymentStatus::Pending); + assert!(matches!( + record.kind, + PaymentKind::Onchain { status: ConfirmationStatus::Unconfirmed, .. } + )); + + assert!(wallet.update_payment_store(vec![confirmed]).await.is_ok()); + assert_eq!(fail_store.failed_writes.load(Ordering::Acquire), 0); + let block_id = + |height| BlockId { height, hash: bitcoin::BlockHash::from_byte_array([7u8; 32]) }; + let tip = WalletEvent::ChainTipChanged { + old_tip: block_id(height), + new_tip: block_id(height + ANTI_REORG_DELAY - 1), + }; + assert!(wallet.update_payment_store(vec![tip]).await.is_ok()); + assert_eq!(record_of(&wallet, &id).await.expect("record").status, PaymentStatus::Succeeded); + assert!(entry_of(&wallet, &id).await.is_none()); + + fail_store.fail_writes.store(false, Ordering::Release); + wallet.update_payment_store(vec![unconfirmed]).await.unwrap(); + assert_eq!(record_of(&wallet, &id).await.expect("record").status, PaymentStatus::Pending); + assert!(entry_of(&wallet, &id).await.is_some(), "a reorged-out payment is tracked again"); + } + + /// A record the chain-tip pass classifies as an interactive funding gets its entry tracking the + /// funding's channels, and its transaction is no longer one of this node's plain sends for the + /// wallet to return to its view. + #[tokio::test] + async fn a_late_funding_classification_tracks_the_channels() { + let store: Arc = Arc::new(DynStoreWrapper(InMemoryStore::new())); + let wallet = new_test_wallet(Arc::clone(&store), false).await; + let (counterparty_node_id, channel_id) = test_counterparty_and_channel(); + let channel = Channel { counterparty_node_id, channel_id }; + + let (spend, id) = replaceable_spend(&wallet, 0x31, None).await; + let txid = spend.compute_txid(); + assert!(wallet.pending_send_txids().await.iter().any(|(t, _)| *t == txid)); + + wallet + .record_channel_tx_facts(ChannelTxFacts::new(txid).with_self_role( + TransactionType::InteractiveFunding { channels: vec![channel.clone()] }, + )) + .await + .unwrap(); + let block_id = + |height| BlockId { height, hash: bitcoin::BlockHash::from_byte_array([7u8; 32]) }; + let tip = WalletEvent::ChainTipChanged { old_tip: block_id(5), new_tip: block_id(6) }; + wallet.update_payment_store(vec![tip]).await.unwrap(); + + assert!(matches!( + record_of(&wallet, &id).await.expect("record").kind, + PaymentKind::Onchain { tx_type: Some(TransactionType::InteractiveFunding { .. }), .. } + )); + let entry = entry_of(&wallet, &id).await.expect("entry"); + assert_eq!(entry.funding_channels(), &[channel]); + assert!(tracks_channel(&entry, channel_id)); + assert!( + !wallet.pending_send_txids().await.iter().any(|(t, _)| *t == txid), + "a funding transaction is LDK's to rebroadcast", + ); + } + + /// The chain-tip pass removes the entry of a record that settled while the entry lingered. + #[tokio::test] + async fn the_tip_pass_removes_the_entry_of_a_settled_record() { + let store: Arc = Arc::new(DynStoreWrapper(InMemoryStore::new())); + let wallet = new_test_wallet(Arc::clone(&store), false).await; + + let txid = Txid::from_byte_array([0x41; 32]); + let id = PaymentId(txid.to_byte_array()); + let payment = PaymentDetails::new( + id, + PaymentKind::Onchain { txid, status: ConfirmationStatus::Unconfirmed, tx_type: None }, + Some(1_000), + Some(100), + PaymentDirection::Outbound, + PaymentStatus::Pending, + ); + track_pending(&wallet, payment, Vec::new()).await; + let mut update = PaymentDetailsUpdate::new(id); + update.status = Some(PaymentStatus::Succeeded); + wallet.payment_stores.payment_store().update(update).await.unwrap(); + + let block_id = + |height| BlockId { height, hash: bitcoin::BlockHash::from_byte_array([7u8; 32]) }; + let tip = WalletEvent::ChainTipChanged { old_tip: block_id(5), new_tip: block_id(6) }; + wallet.update_payment_store(vec![tip]).await.unwrap(); + + assert_eq!(record_of(&wallet, &id).await.expect("record").status, PaymentStatus::Succeeded); + assert!(entry_of(&wallet, &id).await.is_none()); + } + + /// A record the chain-tip pass cannot read is skipped for this tip, and the pass goes on with + /// the other entries. + #[tokio::test] + async fn an_unreadable_record_does_not_stop_the_tip_pass() { + let fail_store = FailSwitchStore::failing_only(PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE); + let store: Arc = Arc::new(DynStoreWrapper(fail_store.clone())); + let wallet = new_test_wallet(Arc::clone(&store), false).await; + + let confirmed_at = |byte: u8| { + let txid = Txid::from_byte_array([byte; 32]); + let mut payment = PaymentDetails::new( + PaymentId(txid.to_byte_array()), + PaymentKind::Onchain { txid, status: confirmed_status(), tx_type: None }, + Some(1_000), + Some(100), + PaymentDirection::Outbound, + PaymentStatus::Pending, + ); + payment.latest_update_timestamp = 0; + payment + }; + let (unreadable, readable) = (confirmed_at(0x51), confirmed_at(0x52)); + track_pending(&wallet, unreadable.clone(), Vec::new()).await; + track_pending(&wallet, readable.clone(), Vec::new()).await; + + // A restarted wallet has nothing cached, so its reads reach the store; only the readable + // record is read into the cache before reads start failing. + let restarted = new_test_wallet(Arc::clone(&store), true).await; + for id in [unreadable.id, readable.id] { + insert_entry(&restarted, entry_of(&wallet, &id).await.expect("entry")).await; + } + assert!(record_of(&restarted, &readable.id).await.is_some()); + fail_store.fail_reads.store(true, Ordering::Release); + + let block_id = + |height| BlockId { height, hash: bitcoin::BlockHash::from_byte_array([7u8; 32]) }; + let tip = WalletEvent::ChainTipChanged { + old_tip: block_id(100), + new_tip: block_id(100 + ANTI_REORG_DELAY - 1), + }; + assert!(restarted.update_payment_store(vec![tip]).await.is_ok()); + fail_store.fail_reads.store(false, Ordering::Release); + + assert_eq!( + record_of(&restarted, &readable.id).await.expect("record").status, + PaymentStatus::Succeeded + ); + assert!(entry_of(&restarted, &readable.id).await.is_none()); + assert_eq!( + record_of(&restarted, &unreadable.id).await.expect("record").status, + PaymentStatus::Pending + ); + assert!(entry_of(&restarted, &unreadable.id).await.is_some()); + } + /// A middle RBF candidate must map back to the funding record: it is neither the record's /// id (here the txid-derived id of the first candidate), nor its current txid (the active /// candidate), nor in `conflicting_txids` (it never got a `TxReplaced` event of its own). @@ -8379,7 +8656,7 @@ mod tests { }, ]; let details = interactive_funding_details(payment_id, txid3, Some(1_000_000), Some(700)); - let mut entry = PendingPaymentDetails::new(details, Vec::new()); + let mut entry = entry_for(&details, Vec::new()); entry.candidates = candidates; insert_entry(&wallet, entry).await; @@ -9029,10 +9306,7 @@ mod tests { "the round is not recorded a second time" ); let entry = entry_of(&wallet, &payment_id).await.unwrap(); - assert!(matches!( - entry.details().unwrap().kind, - PaymentKind::Onchain { status: ConfirmationStatus::Confirmed { .. }, .. } - )); + assert_eq!(entry.txid(), Some(first_txid), "the entry tracks the round that confirmed"); } /// A confirmed conflict that is one of the record's own candidates is RBF resolution, not a @@ -9207,7 +9481,7 @@ mod tests { fee_paid_msat: Some(500), awaiting_broadcast: false, }]; - let mut entry = PendingPaymentDetails::new(snapshot, vec![close_txid]); + let mut entry = entry_for(&snapshot, vec![close_txid]); entry.candidates = candidates; insert_entry(&wallet, entry).await; @@ -9259,7 +9533,7 @@ mod tests { fee_paid_msat: Some(500), awaiting_broadcast: false, }]; - let mut entry = PendingPaymentDetails::new(snapshot, vec![close_txid]); + let mut entry = entry_for(&snapshot, vec![close_txid]); entry.candidates = candidates; insert_entry(&wallet, entry).await; @@ -9791,7 +10065,7 @@ mod tests { assert_eq!(payment.fee_paid_msat, fee_paid_msat); assert_eq!(payment.direction, direction); let entry = entry_of(&wallet, &id).await.expect("entry"); - assert_eq!(entry.details(), Some(payment)); + assert_eq!(entry.txid(), Some(onchain_txid(payment))); assert!(entry_of(&wallet, &duplicate_id).await.is_none()); assert_eq!(wallet.find_payment_by_txid(counterparty_txid).await.unwrap(), Some(id)); } @@ -9882,7 +10156,7 @@ mod tests { payments[0].kind ); let entry = entry_of(&wallet, &id).await.expect("entry"); - assert_eq!(entry.details(), Some(&payments[0])); + assert_eq!(entry.txid(), Some(onchain_txid(&payments[0]))); assert!(record_of(&wallet, &duplicate_id).await.is_none()); } @@ -10083,10 +10357,10 @@ mod tests { ); assert!(entry.candidate(bump_txid).expect("candidate").awaiting_broadcast); // The signing writes no payment record: the one wallet sync made for the first round - // still describes that round, and the entry still mirrors it. + // still describes that round, and the entry still tracks it. let payment = record_of(&wallet, &id).await.expect("payment"); assert!(matches!(payment.kind, PaymentKind::Onchain { txid: t, .. } if t == txid)); - assert_eq!(entry.details(), Some(&payment)); + assert_eq!(entry.txid(), Some(onchain_txid(&payment))); assert_eq!(record_of(&wallet, &duplicate_id).await, Some(duplicate)); assert!(entry_of(&wallet, &duplicate_id).await.is_some()); @@ -10228,7 +10502,7 @@ mod tests { PaymentStatus::Pending, ); wallet.payment_stores.payment_store().insert_or_update(duplicate.clone()).await.unwrap(); - let duplicate_entry = PendingPaymentDetails::new(duplicate.clone(), Vec::new()); + let duplicate_entry = entry_for(&duplicate, Vec::new()); insert_entry(&wallet, duplicate_entry.clone()).await; let entry_before = entry_of(&wallet, &id).await.expect("entry"); let rounds = entry_before.candidates().to_vec(); @@ -10258,7 +10532,7 @@ mod tests { wallet.merge_duplicate_candidate_records(&guard, id, &rounds).await.unwrap(); } let entry = entry_of(&wallet, &id).await.expect("entry"); - assert_eq!(entry.details(), Some(&payment)); + assert_eq!(entry.txid(), Some(onchain_txid(&payment))); let payments = wallet.payment_stores.payment_store().list_page(None).await.unwrap().objects; assert_eq!(payments.len(), 1, "the duplicate must be merged away"); assert_eq!(payments[0].id, id); @@ -10491,7 +10765,7 @@ mod tests { "the round can still confirm, so nothing is failed", ); let entry = entry_of(&wallet, &id).await.expect("the entry stays"); - assert!(entry.details().is_none()); + assert!(entry.txid().is_none()); assert!(entry.candidate(txid).is_some()); } @@ -10516,7 +10790,7 @@ mod tests { "the locked round can still confirm, so nothing is failed", ); let entry = entry_of(&wallet, &id).await.expect("the entry stays"); - assert!(entry.details().is_none()); + assert!(entry.txid().is_none()); assert!(entry.candidate(txid).is_some()); assert_eq!(entry.locked_rounds(), &[txid]); } @@ -10551,7 +10825,7 @@ mod tests { wallet.record_signed_funding(&tx, &candidates).await.unwrap(); let id = wallet.find_payment_by_txid(txid).await.unwrap().expect("recorded"); let entry = entry_of(&wallet, &id).await.expect("the entry"); - assert!(entry.details().is_none()); + assert!(entry.txid().is_none()); assert!(entry.candidate(external_txid).is_some_and(|round| round.amount_msat.is_some())); (external_txid, id) } @@ -12212,10 +12486,7 @@ mod tests { .expect("the funding is spent") }; let id = PaymentId([46u8; 32]); - let entry = PendingPaymentDetails::new( - funding_payment(id, close_txid, PaymentStatus::Pending), - Vec::new(), - ); + let entry = entry_for(&funding_payment(id, close_txid, PaymentStatus::Pending), Vec::new()); wallet.payment_stores.pending_payment_store().insert(entry).await.unwrap(); chain_tip_changed(&wallet, LONG_AFTER).await; @@ -12238,8 +12509,8 @@ mod tests { // A pending record listing the funding transaction among its candidates: its // classification can still be written, and these facts are what would write it. let id = PaymentId([44u8; 32]); - let mut entry = PendingPaymentDetails::new( - funding_payment(id, Txid::from_byte_array([45u8; 32]), PaymentStatus::Pending), + let mut entry = entry_for( + &funding_payment(id, Txid::from_byte_array([45u8; 32]), PaymentStatus::Pending), Vec::new(), ); entry.candidates = vec![FundingTxCandidate { @@ -12559,7 +12830,7 @@ mod tests { wallet .payment_stores .pending_payment_store() - .insert(PendingPaymentDetails::new(payment, Vec::new())) + .insert(entry_for(&payment, Vec::new())) .await .unwrap(); } @@ -12725,7 +12996,7 @@ mod tests { wallet .payment_stores .pending_payment_store() - .insert(PendingPaymentDetails::new(payment.clone(), vec![original_txid])) + .insert(entry_for(&payment, vec![original_txid])) .await .unwrap(); @@ -12737,7 +13008,7 @@ mod tests { assert!(is_in_wallet_view(&wallet, bump_txid)); assert!(!is_in_wallet_view(&wallet, original_txid)); let entry = wallet.payment_stores.pending_payment(&payment_id).await.unwrap().unwrap(); - assert_eq!(entry.details().unwrap().kind, payment.kind); + assert_eq!(entry.txid(), Some(onchain_txid(&payment))); } /// A fee bump cannot return over the transaction it replaced once that one confirmed, and @@ -12769,7 +13040,7 @@ mod tests { wallet .payment_stores .pending_payment_store() - .insert(PendingPaymentDetails::new(payment, vec![original_txid])) + .insert(entry_for(&payment, vec![original_txid])) .await .unwrap(); @@ -12857,7 +13128,7 @@ mod tests { PaymentStatus::Pending, ); wallet.payment_stores.payment_store().insert(details.clone()).await.unwrap(); - let entry = PendingPaymentDetails::new(details, vec![txid_a]); + let entry = entry_for(&details, vec![txid_a]); wallet.payment_stores.pending_payment_store().insert(entry).await.unwrap(); // Bump again: B -> C. diff --git a/src/wallet/payment_stores.rs b/src/wallet/payment_stores.rs index cbc7b27e58..e00f5d598e 100644 --- a/src/wallet/payment_stores.rs +++ b/src/wallet/payment_stores.rs @@ -8,7 +8,6 @@ //! The wallet's payment stores behind one API, so that every write the wallet makes to them //! happens under the lock that keeps a payment record and its pending-store entry consistent. -use std::future::Future; use std::ops::Deref; use std::sync::Arc; @@ -147,16 +146,4 @@ impl PaymentStoresGuard<'_> { { self.stores.pending_payment_store.mutate(id, f).await } - - /// [`Self::mutate_pending_payment`] with a transformation that awaits fallible reads; see - /// [`DataStore::mutate_with`](crate::data_store::DataStore::mutate_with). - pub(super) async fn mutate_pending_payment_async( - &self, id: &PaymentId, f: F, - ) -> Result, Error> - where - F: FnOnce(Option) -> Fut, - Fut: Future, Error>>, - { - self.stores.pending_payment_store.mutate_with(id, f).await - } } From e4392fd5586d9711ed0d6db800d76c2c49d3ef0c Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Tue, 17 Nov 2026 11:09:37 +0100 Subject: [PATCH 05/11] Read a transaction's facts once per wallet event A wallet event resolved the payment of its transaction through a lenient read of the transaction's channel facts, and then read the same facts again, strictly, to record the transaction from its provenance. Absent facts are not cached, so an ordinary transaction cost two facts reads per event, and a signing re-read the signed round's facts while resolving its payment id. Each event and each signing now reads the transaction's own facts once and hands that read to both payment resolution and provenance. A failed read still falls back to the pending entries for resolution and still fails the event only where a record would be written from the transaction. Resolution also returns the entry it matched, which the funding status update takes instead of reading it again. Written with the help of an AI tool. Co-Authored-By: HAL 9000 --- src/wallet/mod.rs | 216 +++++++++++++++++++++++++++++------ src/wallet/payment_stores.rs | 5 - 2 files changed, 183 insertions(+), 38 deletions(-) diff --git a/src/wallet/mod.rs b/src/wallet/mod.rs index 3b1c49649e..87174c5287 100644 --- a/src/wallet/mod.rs +++ b/src/wallet/mod.rs @@ -429,11 +429,11 @@ impl Wallet { } /// [`Self::tx_provenance`] for a decision that must not be taken on a partial answer: a fact - /// that cannot be read fails the caller rather than being left out. + /// that cannot be read fails the caller rather than being left out. `self_facts` is the + /// caller's read of `tx`'s own facts. async fn read_tx_provenance( - &self, txid: Txid, tx: &Transaction, + &self, self_facts: Option, tx: &Transaction, ) -> Result { - let self_facts = self.channel_tx_facts_store.get(&txid).await?; let parents: HashSet = tx.input.iter().map(|input| input.previous_output.txid).collect(); let mut parent_facts = HashMap::new(); @@ -1023,13 +1023,24 @@ impl Wallet { // (or duplicating) the record that write had just made. let stores = self.payment_stores.lock().await; - let mut payment_id = self - .find_payment_by_txid(txid) - .await? - .unwrap_or_else(|| PaymentId(txid.to_byte_array())); + // One read of the transaction's facts serves both resolving its payment and, should the + // record be written from the transaction, its provenance. + let self_facts = self.channel_tx_facts_store.get(&txid).await; + let (found_id, found_entry) = self.find_payment_of_tx(txid, &self_facts).await?; + let mut payment_id = found_id.unwrap_or_else(|| PaymentId(txid.to_byte_array())); + let entry = match found_entry { + Some(entry) => Some(entry), + None => stores.pending_payment(&payment_id).await?, + }; match self - .apply_funding_status_update_locked(&stores, payment_id, txid, confirmation_status) + .apply_funding_status_update_locked( + &stores, + payment_id, + entry, + txid, + confirmation_status, + ) .await? { FundingStatusUpdate::Applied => return Ok(()), @@ -1057,7 +1068,7 @@ impl Wallet { // record is classified or settled its amount and fee are never written again. // So a fact that cannot be read fails the pass, as a write that fails does, // rather than write the record on that view. - let provenance = self.read_tx_provenance(txid, tx).await?; + let provenance = self.read_tx_provenance(self_facts?, tx).await?; let payment = { let locked_wallet = self.inner.lock().expect("lock"); self.create_payment_from_tx( @@ -2989,11 +3000,18 @@ impl Wallet { /// A history no live record tracks gets a fresh id. The caller holds the cross-store lock: /// resolved outside it, the id could go stale against a record wallet sync creates for the /// same transaction before the caller's write. + /// `signed_facts` is the caller's read of the facts of the round `signed_txid`. async fn resolve_interactive_funding_id( - &self, stores: &PaymentStoresGuard<'_>, candidates: &[FundingCandidate], + &self, stores: &PaymentStoresGuard<'_>, candidates: &[FundingCandidate], signed_txid: Txid, + signed_facts: &Result, Error>, ) -> Result { for candidate in candidates.iter() { - if let Some(id) = self.find_payment_by_txid(candidate.txid).await? { + let found = if candidate.txid == signed_txid { + self.find_payment_of_tx(candidate.txid, signed_facts).await?.0 + } else { + self.find_payment_by_txid(candidate.txid).await? + }; + if let Some(id) = found { let failed = stores .payment(&id) .await? @@ -3135,11 +3153,25 @@ impl Wallet { // it. Those facts are immutable, so a replay adopts them rather than deriving figures // afresh: LDK may have adjusted the contribution's fee fields since, and a second answer // would be refused rather than recorded, leaving the event replaying forever. - let recorded_figures = - self.channel_tx_facts(&txid).await.and_then(|facts| facts.local_figures); + let signed_facts = self.channel_tx_facts_store.get(&txid).await; + let recorded_figures = match &signed_facts { + Ok(facts) => facts.as_ref().and_then(|facts| facts.local_figures.clone()), + Err(e) => { + log_error!( + self.logger, + "Failed to read what this node recorded about transaction {}: {}", + txid, + e, + ); + None + }, + }; let payment_id = match &recorded_figures { Some(figures) => figures.funding_payment_id, - None => self.resolve_interactive_funding_id(&stores, candidates).await?, + None => { + self.resolve_interactive_funding_id(&stores, candidates, txid, &signed_facts) + .await? + }, }; let (figures, mut history) = match self.interactive_funding_figures(payment_id, candidates, signed_round, tx) { @@ -3698,8 +3730,15 @@ impl Wallet { // anything the record needs — the actively-broadcast candidate stays the record's // current txid. if matches!(status, ConfirmationStatus::Confirmed { .. }) { + let entry = stores.pending_payment(&id).await?; match self - .apply_funding_status_update_locked(stores, id, duplicate_txid, status.clone()) + .apply_funding_status_update_locked( + stores, + id, + entry, + duplicate_txid, + status.clone(), + ) .await? { FundingStatusUpdate::Applied => {}, @@ -3889,15 +3928,36 @@ impl Wallet { /// graduated out of the pending store. Otherwise the pending store is asked, by the record's /// own transaction, by its candidate history and by the conflicts wallet sync listed for it. async fn find_payment_by_txid(&self, target_txid: Txid) -> Result, Error> { - if let Some(figures) = - self.channel_tx_facts(&target_txid).await.and_then(|facts| facts.local_figures) - { - return Ok(Some(figures.funding_payment_id)); + let self_facts = self.channel_tx_facts_store.get(&target_txid).await; + Ok(self.find_payment_of_tx(target_txid, &self_facts).await?.0) + } + + /// [`Self::find_payment_by_txid`] from an already made read of the transaction's own facts, + /// returning the pending entry the payment was found through, if any. A failed read is + /// logged and leaves the answer to the pending store. + async fn find_payment_of_tx( + &self, target_txid: Txid, self_facts: &Result, Error>, + ) -> Result<(Option, Option), Error> { + match self_facts { + Ok(facts) => { + if let Some(figures) = facts.as_ref().and_then(|facts| facts.local_figures.as_ref()) + { + return Ok((Some(figures.funding_payment_id), None)); + } + }, + Err(e) => { + log_error!( + self.logger, + "Failed to read what this node recorded about transaction {}: {}", + target_txid, + e, + ); + }, } let direct_payment_id = PaymentId(target_txid.to_byte_array()); - if self.payment_stores.has_pending_payment(&direct_payment_id).await? { - return Ok(Some(direct_payment_id)); + if let Some(entry) = self.payment_stores.pending_payment(&direct_payment_id).await? { + return Ok((Some(direct_payment_id), Some(entry))); } let owns = |p: &PendingPaymentDetails| { @@ -3907,7 +3967,7 @@ impl Wallet { // (an earlier RBF round may confirm) back to the record. || p.candidate(target_txid).is_some() }; - let matches = self + let mut matches = self .payment_stores .pending_payments(|p| owns(p) || p.conflicting_txids().contains(&target_txid)) .await; @@ -3915,11 +3975,13 @@ impl Wallet { // records as its own (a splice round that replaced a close, say) matches both. The entry // that owns it is its record; the conflict listing is only how a replaced round of a // record with no candidates (an ordinary payment's RBF history) maps back to its record. - if let Some(entry) = matches.iter().find(|p| owns(p)).or(matches.first()) { - return Ok(Some(entry.id())); + let index = matches.iter().position(|p| owns(p)).unwrap_or(0); + if index < matches.len() { + let entry = matches.swap_remove(index); + return Ok((Some(entry.id()), Some(entry))); } - Ok(None) + Ok((None, None)) } /// If `payment_id` refers to a classified funding payment, refreshes its confirmation status @@ -3935,16 +3997,16 @@ impl Wallet { /// through its own last write, not just across this call — so that a funding-record writer's /// two-store write pair cannot interleave with the caller's decision sequence. The `stores` guard /// proves the lock is held across this call; the rest of that contract is the caller's. + /// `pending_payment` is the entry under `payment_id`, read under the same hold of the lock. async fn apply_funding_status_update_locked( - &self, stores: &PaymentStoresGuard<'_>, payment_id: PaymentId, event_txid: Txid, + &self, stores: &PaymentStoresGuard<'_>, payment_id: PaymentId, + pending_payment: Option, event_txid: Txid, confirmation_status: ConfirmationStatus, ) -> Result { - // The caller's wallet-level lock keeps the candidate history stable while we await its - // read. The funding-type gate, the candidate lookup, and the write then share the payment - // store's mutation lock: against a separate payment `get`, a funding-record write merging - // in between would have its `tx_type` and contribution figures clobbered by this stale - // snapshot. - let pending_payment = stores.pending_payment(&payment_id).await?; + // The caller's lock keeps the candidate history stable. The funding-type gate, the + // candidate lookup, and the write then share the payment store's mutation lock: against a + // separate payment `get`, a funding-record write merging in between would have its + // `tx_type` and contribution figures clobbered by this stale snapshot. let mut outcome = FundingStatusUpdate::NotFunding; let mut handled = None; stores @@ -4062,7 +4124,8 @@ impl Wallet { // re-signed by this node alone. Fee-bumping a pending splice goes through // `bump_channel_funding_fee` instead. A fact that cannot be read is no answer about the // transaction, and refuses the replacement with the error. - let provenance = self.read_tx_provenance(txid, &old_tx).await?; + let self_facts = self.channel_tx_facts_store.get(&txid).await?; + let provenance = self.read_tx_provenance(self_facts, &old_tx).await?; if let Some(tx_type) = provenance.classify(&old_tx) { log_error!( self.logger, @@ -9584,6 +9647,93 @@ mod tests { assert_eq!(reads, 2, "recording an unknown transaction re-read the payment store"); } + /// A transaction nothing is on record about has no facts, and an absent record is not cached, + /// so every read of its facts reaches the store. Resolving its payment and recording it from + /// its provenance share one read of its own facts; only its parents' facts are read besides. + #[tokio::test] + async fn an_ordinary_transaction_has_its_own_facts_read_once_per_wallet_event() { + let counting_store = ReadCountingStore::new(); + let store: Arc = Arc::new(DynStoreWrapper(counting_store.clone())); + let wallet = new_test_wallet(Arc::clone(&store), false).await; + + let tx = wallet_paying_tx(&wallet, 1); + let txid = tx.compute_txid(); + let parents: HashSet = + tx.input.iter().map(|input| input.previous_output.txid).collect(); + let reads_before = counting_store.reads(CHANNEL_TX_FACTS_PERSISTENCE_PRIMARY_NAMESPACE); + let event = WalletEvent::TxUnconfirmed { txid, tx: Arc::new(tx), old_block_time: None }; + wallet.update_payment_store(vec![event]).await.unwrap(); + let reads = + counting_store.reads(CHANNEL_TX_FACTS_PERSISTENCE_PRIMARY_NAMESPACE) - reads_before; + + assert!(record_of(&wallet, &PaymentId(txid.to_byte_array())).await.is_some()); + assert_eq!(reads, 1 + parents.len(), "the event read the transaction's own facts twice"); + } + + /// After a restart emptied the facts cache, the read of a listed splice round's facts fails. + /// The round still resolves to its funding payment through the pending entry listing it: a + /// wallet event for it is not recorded from the wallet's view, under the round's own id or + /// the payment's, while no record exists yet, and once the record exists the event updates + /// it, needing no facts. + #[tokio::test] + async fn a_listed_round_whose_facts_cannot_be_read_resolves_through_its_entry() { + let fail_store = + FailSwitchStore::failing_only(CHANNEL_TX_FACTS_PERSISTENCE_PRIMARY_NAMESPACE); + let store: Arc = Arc::new(DynStoreWrapper(fail_store.clone())); + let wallet = new_test_wallet(Arc::clone(&store), false).await; + let (counterparty_node_id, channel_id) = test_counterparty_and_channel(); + + let (tx, contribution) = splice_out_round(&wallet, 1, 500_000, 300); + let txid = tx.compute_txid(); + let candidates = + splice_candidates(counterparty_node_id, channel_id, &[(txid, Some(contribution))]); + wallet.record_signed_funding(&tx, &candidates).await.unwrap(); + let id = wallet.find_payment_by_txid(txid).await.unwrap().expect("id"); + let txid_id = PaymentId(txid.to_byte_array()); + assert_ne!(id, txid_id); + let entry = entry_of(&wallet, &id).await.expect("entry"); + + // No record yet: the event fails rather than record the round from the wallet's view. + let restarted = new_test_wallet(Arc::clone(&store), true).await; + insert_entry(&restarted, entry.clone()).await; + insert_unconfirmed_tx(&restarted, tx.clone()); + let unconfirmed = + WalletEvent::TxUnconfirmed { txid, tx: Arc::new(tx.clone()), old_block_time: None }; + fail_store.fail_reads.store(true, Ordering::Release); + let result = restarted.update_payment_store(vec![unconfirmed.clone()]).await; + fail_store.fail_reads.store(false, Ordering::Release); + assert!(matches!(result, Err(Error::PersistenceFailed)), "{:?}", result); + assert!(record_of(&restarted, &id).await.is_none()); + assert!(record_of(&restarted, &txid_id).await.is_none()); + + // With the reads back the record is written from the round's facts. + restarted.update_payment_store(vec![unconfirmed]).await.unwrap(); + let recorded = record_of(&restarted, &id).await.expect("record"); + assert_eq!(recorded.amount_msat, Some(500_300_000)); + + // The record exists: the confirmation resolves through the entry and updates it. + let reloaded = new_test_wallet(Arc::clone(&store), true).await; + insert_entry(&reloaded, entry_of(&restarted, &id).await.expect("entry")).await; + let confirmed = WalletEvent::TxConfirmed { + txid, + tx: Arc::new(tx), + block_time: confirmed_block_time(100), + old_block_time: None, + }; + fail_store.fail_reads.store(true, Ordering::Release); + let result = reloaded.update_payment_store(vec![confirmed]).await; + fail_store.fail_reads.store(false, Ordering::Release); + assert!(result.is_ok(), "{:?}", result); + let payment = record_of(&reloaded, &id).await.expect("record"); + assert!(matches!( + payment.kind, + PaymentKind::Onchain { txid: t, status: ConfirmationStatus::Confirmed { .. }, .. } + if t == txid + )); + assert_eq!(payment.amount_msat, Some(500_300_000)); + assert!(record_of(&reloaded, &txid_id).await.is_none()); + } + /// A funding record wallet sync created for a round this node had not recorded keeps the /// txid-derived id of its first candidate. Once the payment settles and its entry is removed, a /// wallet event for that candidate no longer resolves through the candidate history — the diff --git a/src/wallet/payment_stores.rs b/src/wallet/payment_stores.rs index e00f5d598e..861d176c21 100644 --- a/src/wallet/payment_stores.rs +++ b/src/wallet/payment_stores.rs @@ -69,11 +69,6 @@ impl PaymentStores { self.pending_payment_store.get(id).await } - /// Whether the pending store has an entry under `id`. - pub(super) async fn has_pending_payment(&self, id: &PaymentId) -> Result { - self.pending_payment_store.contains_key(id).await - } - /// The pending-store entries matching `f`. pub(super) async fn pending_payments bool>( &self, f: F, From 824bd38bf9e15226db51fdcb6255dcd2cb4f7674 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Tue, 17 Nov 2026 11:10:46 +0100 Subject: [PATCH 06/11] Keep recorded splice round figures stable A signing recomputed every round's figures from LDK's current view of the contributions and overwrote the figures of rounds already in the entry, while the rounds' facts keep their first answer. The two could then disagree, and a confirmation applied from the entry reported other figures than a record created from the facts. Rounds already in the entry now keep their recorded figures, and the signed round takes the figures its facts carry, so entry and facts agree. A later signing still clears earlier rounds' broadcast marks. Written with the help of an AI tool. Co-Authored-By: HAL 9000 --- src/wallet/mod.rs | 72 +++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 64 insertions(+), 8 deletions(-) diff --git a/src/wallet/mod.rs b/src/wallet/mod.rs index 87174c5287..8596add59b 100644 --- a/src/wallet/mod.rs +++ b/src/wallet/mod.rs @@ -3181,9 +3181,11 @@ impl Wallet { let figures = recorded_figures.unwrap_or(figures); let direction = figures.direction; // Only the signed round awaits broadcast: LDK broadcast the others once their signatures - // were exchanged. + // were exchanged. Its figures are those its facts carry, so the entry agrees with them. if let Some(signed) = history.iter_mut().find(|candidate| candidate.txid == txid) { signed.awaiting_broadcast = true; + signed.amount_msat = figures.amount_msat; + signed.fee_paid_msat = figures.fee_paid_msat; } let prior_pending = stores.pending_payment(&payment_id).await?; @@ -3191,12 +3193,13 @@ impl Wallet { if prior_pending.as_ref().is_some_and(|entry| entry.candidate(txid).is_some()) { return Ok(SignedFundingRecord::Recorded); } - // Merge LDK's history into the recorded one — refreshing the rounds both list, appending - // the new ones — rather than replace it: LDK's history omits a recorded round it has since - // abandoned, whose removal is `drop_abandoned_splice_rounds`' job once LDK reports the - // failure, so a recorded round LDK no longer lists must survive the write. + // Merge LDK's history into the recorded one — appending the new rounds — rather than + // replace it: LDK's history omits a recorded round it has since abandoned, whose removal is + // `drop_abandoned_splice_rounds`' job once LDK reports the failure, so a recorded round LDK + // no longer lists must survive the write. A recorded round keeps its figures, which its + // immutable facts carry too, however LDK has since adjusted the contribution's fee fields. // - // Refreshing an earlier round clears its awaiting-broadcast mark, which is right only + // The merge clears an earlier round's awaiting-broadcast mark, which is right only // because LDK refuses a new negotiation while one awaits signatures and handles events in // order, stopping at the first failure: the earlier round's `SpliceNegotiated` event was // pushed before this signing event and has been handled by now. Should LDK ever reorder @@ -3205,7 +3208,7 @@ impl Wallet { prior_pending.as_ref().map(|entry| entry.candidates().to_vec()).unwrap_or_default(); for candidate in history { match recorded.iter_mut().find(|stored| stored.txid == candidate.txid) { - Some(stored) => *stored = candidate, + Some(stored) => stored.awaiting_broadcast = false, None => recorded.push(candidate), } } @@ -6821,7 +6824,60 @@ mod tests { assert_eq!(figures.funding_payment_id, id); assert_eq!(figures.fee_paid_msat, Some(300_000), "the recorded share stands"); let entry = entry_of(&wallet, &id).await.expect("entry"); - assert!(entry.candidate(txid).expect("candidate").awaiting_broadcast); + let round = entry.candidate(txid).expect("candidate"); + assert!(round.awaiting_broadcast); + assert_eq!( + (round.amount_msat, round.fee_paid_msat), + (figures.amount_msat, figures.fee_paid_msat), + "the entry reports the figures the facts record", + ); + } + + /// A later signing lists the earlier rounds of the history again, from a contribution LDK may + /// have adjusted the fee fields of since. The rounds already recorded keep their figures, + /// which their immutable facts carry too, so a confirmation reports the same figures whether + /// it is applied from the entry or recorded from the facts. + #[tokio::test] + async fn a_later_signing_keeps_the_recorded_figures_of_earlier_rounds() { + let store: Arc = Arc::new(DynStoreWrapper(InMemoryStore::new())); + let wallet = new_test_wallet(Arc::clone(&store), false).await; + let (counterparty_node_id, channel_id) = test_counterparty_and_channel(); + + let (tx1, contribution1) = splice_out_round(&wallet, 1, 500_000, 300); + let txid1 = tx1.compute_txid(); + let candidates = + splice_candidates(counterparty_node_id, channel_id, &[(txid1, Some(contribution1))]); + wallet.record_signed_funding(&tx1, &candidates).await.unwrap(); + let id = wallet.find_payment_by_txid(txid1).await.unwrap().expect("id"); + + // The fee bump lists the first round with an adjusted estimated fee. + let splice_out = tx1.output.last().expect("the splice-out output").clone(); + let adjusted = test_funding_contribution_with_outputs(900, 253, &[splice_out]); + let (tx2, contribution2) = splice_out_round(&wallet, 2, 500_000, 600); + let txid2 = tx2.compute_txid(); + let candidates = splice_candidates( + counterparty_node_id, + channel_id, + &[(txid1, Some(adjusted)), (txid2, Some(contribution2))], + ); + wallet.record_signed_funding(&tx2, &candidates).await.unwrap(); + + let figures = wallet + .channel_tx_facts(&txid1) + .await + .expect("facts") + .local_figures + .expect("this node's share"); + assert_eq!(figures.fee_paid_msat, Some(300_000)); + let entry = entry_of(&wallet, &id).await.expect("entry"); + let round = entry.candidate(txid1).expect("candidate"); + assert!(!round.awaiting_broadcast, "the later signing clears the earlier round's mark"); + assert_eq!( + (round.amount_msat, round.fee_paid_msat), + (figures.amount_msat, figures.fee_paid_msat), + "the entry keeps the figures the facts record", + ); + assert!(entry.candidate(txid2).expect("candidate").awaiting_broadcast); } /// The counterparty broadcasts the round it has our signatures for before this node has From 7e43e38cbfb86662df9f7a87c5eae61856d7e01a Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Tue, 17 Nov 2026 11:13:01 +0100 Subject: [PATCH 07/11] Group pending entry funding fields together The channels, candidate rounds and locked rounds of a pending entry only ever apply to interactive funding, yet sat as three independent lists beside the fields every entry uses, and each site that cleared the funding state had to clear all three by hand. Gather them in an optional FundingRounds that a non-funding entry leaves unset, so clearing a splice's whole funding state is a single assignment. The persisted format changes, which is fine as it is unreleased; sites that clear only part of the state keep doing so. Written with the help of an AI tool. Co-Authored-By: HAL 9000 --- src/payment/pending_payment_store.rs | 124 +++++++++++++++------------ src/wallet/mod.rs | 44 +++++----- 2 files changed, 92 insertions(+), 76 deletions(-) diff --git a/src/payment/pending_payment_store.rs b/src/payment/pending_payment_store.rs index c463d41569..cae9ebe70e 100644 --- a/src/payment/pending_payment_store.rs +++ b/src/payment/pending_payment_store.rs @@ -43,17 +43,40 @@ impl_writeable_tlv_based!(FundingTxCandidate, { (6, awaiting_broadcast, required), }); +/// The interactive-funding (splice) part of a [`PendingPaymentDetails`] entry. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct FundingRounds { + /// The channels whose interactive funding the entry tracks, as the signing of a round or the + /// record's classification listed them. + pub channels: Vec, + /// This node's per-candidate funding figures across the RBF history, keyed by each + /// candidate's txid and recorded as each round is signed. + pub rounds: Vec, + /// The candidates LDK promoted to the channel's funding, as `ChannelReady` reported them. + /// A zero-conf splice locks before its transaction confirms, and every later splice builds + /// on it, so such a round can still confirm once the channel's funding has moved on from + /// it and once the channel has closed, when LDK no longer tracks it. Kept apart from the + /// rounds, which each funding-record write replaces as a whole. + pub locked: Vec, +} + +impl_writeable_tlv_based!(FundingRounds, { + (0, channels, optional_vec), + (2, rounds, optional_vec), + (4, locked, optional_vec), +}); + /// A pending payment tracked by LDK Node, keyed by [`PaymentId`]. /// /// The payment's record in the payment store is what says its status, confirmation, direction and /// transaction type; an entry only indexes the transactions that may still change the record. /// Each part of an entry is written by a different subsystem and is present on its own schedule, -/// so all of them are optional. Signing a round of a splice adds the round to `candidates` and -/// lists the `funding_channels` it belongs to, before any transaction anyone has seen; wallet +/// so all of them are optional. Signing a round of a splice adds the round to the `funding` +/// rounds and lists the channels it belongs to, before any transaction anyone has seen; wallet /// sync sets `txid` once it observes the transaction, and records `conflicting_txids` for any -/// wallet transaction; the `ChannelReady` arm records `locked_rounds`. A splice uses all of them; -/// the fields do not partition by payment type. An entry with none of them tracks no payment and -/// is removed. +/// wallet transaction; the `ChannelReady` arm records locked rounds. A splice uses all of them; +/// the fields do not partition by payment type. An entry with neither a txid nor any funding +/// round tracks no payment and is removed. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct PendingPaymentDetails { /// The payment this entry tracks. @@ -64,35 +87,17 @@ pub(crate) struct PendingPaymentDetails { pub txid: Option, /// Transaction IDs wallet sync observed to have replaced or to conflict with this /// payment, used to map later events about those txids back to this record. This is - /// BDK's view, distinct from `candidates`: it can list conflicts that were never + /// BDK's view, distinct from the funding rounds: it can list conflicts that were never /// negotiated candidates, while a candidate replaced between wallet syncs may never /// appear here (it gets no `TxReplaced` event of its own). pub conflicting_txids: Vec, - /// The channels whose interactive funding this entry tracks, as the signing of a round or the - /// record's classification listed them. Empty for a non-funding payment. - pub funding_channels: Vec, - /// For interactive funding (splices), this node's per-candidate funding figures across the - /// RBF history, keyed by each candidate's txid and recorded as each round is signed. - /// Empty for non-funding payments. - pub candidates: Vec, - /// The candidates LDK promoted to the channel's funding, as `ChannelReady` reported them. - /// A zero-conf splice locks before its transaction confirms, and every later splice builds - /// on it, so such a round can still confirm once the channel's funding has moved on from - /// it and once the channel has closed, when LDK no longer tracks it. Kept apart from the - /// candidates, which each funding-record write replaces as a whole. - pub locked_rounds: Vec, + /// The interactive-funding state of a splice; `None` for a non-funding payment. + pub funding: Option, } impl PendingPaymentDetails { pub(crate) fn new(id: PaymentId, txid: Txid, conflicting_txids: Vec) -> Self { - Self { - id, - txid: Some(txid), - conflicting_txids, - funding_channels: Vec::new(), - candidates: Vec::new(), - locked_rounds: Vec::new(), - } + Self { id, txid: Some(txid), conflicting_txids, funding: None } } /// An entry for the rounds of an interactive funding of `funding_channels` this node has @@ -101,14 +106,9 @@ impl PendingPaymentDetails { pub(crate) fn signed_rounds( id: PaymentId, funding_channels: Vec, candidates: Vec, ) -> Self { - Self { - id, - txid: None, - conflicting_txids: Vec::new(), - funding_channels, - candidates, - locked_rounds: Vec::new(), - } + let funding = + FundingRounds { channels: funding_channels, rounds: candidates, locked: Vec::new() }; + Self { id, txid: None, conflicting_txids: Vec::new(), funding: Some(funding) } } /// The payment record's current transaction, or `None` for a splice whose transaction has not @@ -122,44 +122,61 @@ impl PendingPaymentDetails { &self.conflicting_txids } + /// The interactive-funding state, created empty if the entry has none yet. + pub(crate) fn funding_mut(&mut self) -> &mut FundingRounds { + self.funding.get_or_insert_with(FundingRounds::default) + } + /// The rounds LDK promoted to the channel's funding, as `ChannelReady` reported them. pub(crate) fn locked_rounds(&self) -> &[Txid] { - &self.locked_rounds + self.funding.as_ref().map_or(&[], |funding| &funding.locked) } /// Records that LDK promoted the round with the given txid to the channel's funding. Returns /// whether the record changed: a round recorded as promoted already leaves it as it is. pub(crate) fn record_locked_round(&mut self, txid: Txid) -> bool { - if self.locked_rounds.contains(&txid) { + if self.locked_rounds().contains(&txid) { return false; } - self.locked_rounds.push(txid); + self.funding_mut().locked.push(txid); true } /// Returns this node's recorded funding figures for the candidate with the given txid, if any. pub(crate) fn candidate(&self, txid: Txid) -> Option<&FundingTxCandidate> { - self.candidates.iter().find(|candidate| candidate.txid == txid) + self.candidates().iter().find(|candidate| candidate.txid == txid) } /// This node's recorded funding figures across the candidate history, in LDK's order; empty /// for a splice without a signed round yet and for non-funding payments. pub(crate) fn candidates(&self) -> &[FundingTxCandidate] { - &self.candidates + self.funding.as_ref().map_or(&[], |funding| &funding.rounds) + } + + /// Replaces the recorded candidate history. + pub(crate) fn set_candidates(&mut self, candidates: Vec) { + self.funding_mut().rounds = candidates; + } + + /// Drops the candidates with the given txids from the recorded history. + pub(crate) fn drop_candidates(&mut self, txids: &[Txid]) { + if let Some(funding) = self.funding.as_mut() { + funding.rounds.retain(|candidate| !txids.contains(&candidate.txid)); + } } /// The channels of the interactive funding this entry tracks. pub(crate) fn funding_channels(&self) -> &[Channel] { - &self.funding_channels + self.funding.as_ref().map_or(&[], |funding| &funding.channels) } /// Lists `channels` as the channels of the interactive funding this entry tracks, unless it /// lists some already. Returns whether the entry changed. pub(crate) fn track_funding_channels(&mut self, channels: &[Channel]) -> bool { - if !self.funding_channels.is_empty() || channels.is_empty() { + if !self.funding_channels().is_empty() || channels.is_empty() { return false; } - self.funding_channels = channels.to_vec(); + self.funding_mut().channels = channels.to_vec(); true } @@ -185,7 +202,7 @@ impl PendingPaymentDetails { /// Whether this entry tracks nothing anymore and can be dropped. pub(crate) fn is_empty(&self) -> bool { - self.txid.is_none() && self.candidates.is_empty() && self.locked_rounds.is_empty() + self.txid.is_none() && self.candidates().is_empty() && self.locked_rounds().is_empty() } } @@ -193,9 +210,7 @@ impl_writeable_tlv_based!(PendingPaymentDetails, { (0, id, required), (2, txid, option), (4, conflicting_txids, optional_vec), - (6, funding_channels, optional_vec), - (8, candidates, optional_vec), - (10, locked_rounds, optional_vec), + (6, funding, option), }); impl StorableObject for PendingPaymentDetails { @@ -319,7 +334,7 @@ mod tests { let mut pending = PendingPaymentDetails::new(payment_id, rbf_txid, vec![first_txid, counterparty_txid]); - pending.candidates = candidates; + pending.set_candidates(candidates); // Each candidate resolves to its own figures, so a non-last candidate that confirms reports // its own (lower) fee rather than the last-broadcast candidate's. @@ -374,12 +389,12 @@ mod tests { let txid = Txid::from_byte_array([8u8; 32]); let mut record = PendingPaymentDetails::new(payment_id, txid, vec![Txid::from_byte_array([9u8; 32])]); - record.candidates = vec![FundingTxCandidate { + record.set_candidates(vec![FundingTxCandidate { txid, amount_msat: Some(1_000), fee_paid_msat: Some(100), awaiting_broadcast: false, - }]; + }]); let encoded = record.encode(); let decoded = PendingPaymentDetails::read(&mut &encoded[..]).unwrap(); @@ -388,8 +403,11 @@ mod tests { assert_eq!(decoded.txid(), Some(txid)); // The rounds of a splice signed before any transaction was observed. - let signed = - PendingPaymentDetails::signed_rounds(payment_id, Vec::new(), record.candidates); + let signed = PendingPaymentDetails::signed_rounds( + payment_id, + Vec::new(), + record.candidates().to_vec(), + ); let decoded = PendingPaymentDetails::read(&mut &signed.encode()[..]).unwrap(); assert_eq!(decoded, signed); assert_eq!(decoded.txid(), None); @@ -409,7 +427,7 @@ mod tests { let payment_id = PaymentId([1u8; 32]); let txid = candidates.last().expect("at least one candidate").txid; let mut entry = PendingPaymentDetails::new(payment_id, txid, vec![]); - entry.candidates = candidates; + entry.set_candidates(candidates); entry } diff --git a/src/wallet/mod.rs b/src/wallet/mod.rs index 8596add59b..11cfa90228 100644 --- a/src/wallet/mod.rs +++ b/src/wallet/mod.rs @@ -1438,7 +1438,7 @@ impl Wallet { Some(details) if details.status == PaymentStatus::Pending => details, _ => return Ok(false), }; - let (conflicting_txids, candidates) = (&entry.conflicting_txids, &entry.candidates); + let (conflicting_txids, candidates) = (&entry.conflicting_txids, entry.candidates()); let record_txid = match details.kind { PaymentKind::Onchain { txid, @@ -3271,12 +3271,11 @@ impl Wallet { let mut entry = existing.cloned().unwrap_or_else(|| { PendingPaymentDetails::signed_rounds(payment_id, Vec::new(), Vec::new()) }); - if entry.funding_channels.is_empty() && !funding_channels.is_empty() { - entry.funding_channels = funding_channels.clone(); + if entry.track_funding_channels(&funding_channels) { changed = true; } - if entry.candidates != recorded { - entry.candidates = recorded.clone(); + if entry.candidates() != recorded.as_slice() { + entry.set_candidates(recorded.clone()); changed = true; } changed.then_some(entry) @@ -3332,10 +3331,10 @@ impl Wallet { let marked = stores .mutate_pending_payment(&payment_id, |existing| { let mut entry = existing?.clone(); - let round = entry - .candidates - .iter_mut() - .find(|candidate| candidate.txid == txid && candidate.awaiting_broadcast)?; + let round = + entry.funding.as_mut()?.rounds.iter_mut().find(|candidate| { + candidate.txid == txid && candidate.awaiting_broadcast + })?; round.awaiting_broadcast = false; Some(entry) }) @@ -3452,11 +3451,9 @@ impl Wallet { .mutate_pending_payment(&payment_id, |existing| { let mut entry = existing?.clone(); if handed_back.is_some() { - entry.candidates.retain(|c| !abandoned_txids.contains(&c.txid)); + entry.drop_candidates(&abandoned_txids); } else { - entry.candidates.clear(); - entry.locked_rounds.clear(); - entry.funding_channels.clear(); + entry.funding = None; } emptied = entry.is_empty(); (!emptied).then_some(entry) @@ -3561,10 +3558,11 @@ impl Wallet { // With its history gone, the entry tracks the channels of the record's own // classification, if any. if handed_back.is_none() { - entry.candidates.clear(); - entry.funding_channels = record_channels; + let funding = entry.funding_mut(); + funding.rounds.clear(); + funding.channels = record_channels; } else { - entry.candidates.retain(|c| !abandoned_txids.contains(&c.txid)); + entry.drop_candidates(&abandoned_txids); } if let Some(txid) = current_txid { entry.txid = Some(txid); @@ -3669,7 +3667,7 @@ impl Wallet { let mut entry = existing.cloned().unwrap_or_else(|| { PendingPaymentDetails::signed_rounds(id, Vec::new(), Vec::new()) }); - entry.candidates = candidates.clone(); + entry.set_candidates(candidates.clone()); Some(entry) }) .await?; @@ -8776,7 +8774,7 @@ mod tests { ]; let details = interactive_funding_details(payment_id, txid3, Some(1_000_000), Some(700)); let mut entry = entry_for(&details, Vec::new()); - entry.candidates = candidates; + entry.set_candidates(candidates); insert_entry(&wallet, entry).await; // The first candidate resolves via the txid-derived id and the active candidate via the @@ -9330,7 +9328,7 @@ mod tests { let payment = record_of(&wallet, &payment_id).await.unwrap(); assert_eq!(payment.status, PaymentStatus::Pending, "the unseen round can still confirm"); let entry = entry_of(&wallet, &payment_id).await.unwrap(); - assert_eq!(entry.candidates.len(), 2, "both rounds stay on record"); + assert_eq!(entry.candidates().len(), 2, "both rounds stay on record"); // The first round turns up in the mempool, and a second close spends its input and // confirms to depth too: no round can confirm now. @@ -9601,7 +9599,7 @@ mod tests { awaiting_broadcast: false, }]; let mut entry = entry_for(&snapshot, vec![close_txid]); - entry.candidates = candidates; + entry.set_candidates(candidates); insert_entry(&wallet, entry).await; insert_confirmed_tx(&wallet, close_tx, 5); @@ -9653,7 +9651,7 @@ mod tests { awaiting_broadcast: false, }]; let mut entry = entry_for(&snapshot, vec![close_txid]); - entry.candidates = candidates; + entry.set_candidates(candidates); insert_entry(&wallet, entry).await; insert_confirmed_tx(&wallet, close_tx, 5); @@ -12719,12 +12717,12 @@ mod tests { &funding_payment(id, Txid::from_byte_array([45u8; 32]), PaymentStatus::Pending), Vec::new(), ); - entry.candidates = vec![FundingTxCandidate { + entry.set_candidates(vec![FundingTxCandidate { txid: funding_txid, amount_msat: Some(1_000), fee_paid_msat: Some(10), awaiting_broadcast: false, - }]; + }]); wallet.payment_stores.pending_payment_store().insert(entry).await.unwrap(); chain_tip_changed(&wallet, LONG_AFTER).await; From 6c4f0f1368ac8a580f0670a7a60aa3dd08bfe9d0 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Tue, 17 Nov 2026 11:14:52 +0100 Subject: [PATCH 08/11] Rename the pending payment store to a tracker The pending payment store no longer holds payments: its entries only index the on-chain transactions that may still change a payment record. Its name, its entry type and its home in the payment module still suggested a second copy of the payment store. Rename it to OnchainPaymentTracker with TrackedOnchainPayment entries and move it next to the wallet code that maintains it, renaming the accessors to match. The on-disk namespace stays "pending_payments", so persisted entries are read as before. Written with the help of an AI tool. Co-Authored-By: HAL 9000 --- src/builder.rs | 30 +- src/io/mod.rs | 6 +- src/lib.rs | 2 +- src/payment/mod.rs | 2 - src/types.rs | 8 +- src/wallet/mod.rs | 272 +++++++++--------- src/wallet/payment_stores.rs | 55 ++-- .../payment_tracker.rs} | 40 +-- src/wallet/provenance.rs | 2 +- 9 files changed, 209 insertions(+), 208 deletions(-) rename src/{payment/pending_payment_store.rs => wallet/payment_tracker.rs} (93%) diff --git a/src/builder.rs b/src/builder.rs index a8cba83db3..f1e23f8167 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -87,10 +87,10 @@ use crate::io::{ self, CHANNEL_FORWARDING_STATS_PERSISTENCE_SECONDARY_NAMESPACE, CHANNEL_TX_FACTS_PERSISTENCE_PRIMARY_NAMESPACE, CHANNEL_TX_FACTS_PERSISTENCE_SECONDARY_NAMESPACE, - FORWARDED_PAYMENT_PERSISTENCE_PRIMARY_NAMESPACE, PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE, - PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE, - PENDING_PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE, - PENDING_PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE, + FORWARDED_PAYMENT_PERSISTENCE_PRIMARY_NAMESPACE, + ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_PRIMARY_NAMESPACE, + ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_SECONDARY_NAMESPACE, + PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE, PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE, }; use crate::liquidity::client::lsps2::router::LSPS2Router; use crate::liquidity::{LSPS2ServiceConfig, LiquiditySourceBuilder, LspConfig}; @@ -111,8 +111,8 @@ use crate::runtime::{Runtime, RuntimeSpawner}; use crate::tx_broadcaster::TransactionBroadcaster; use crate::types::{ AsyncPersister, ChainMonitor, ChannelManager, ChannelTxFactsStore, DynStore, DynStoreRef, - DynStoreWrapper, GossipSync, Graph, KeysManager, MessageRouter, OnionMessenger, PaymentStore, - PeerManager, PendingPaymentStore, + DynStoreWrapper, GossipSync, Graph, KeysManager, MessageRouter, OnchainPaymentTracker, + OnionMessenger, PaymentStore, PeerManager, }; use crate::wallet::persist::{read_address_pool, KVStoreWalletPersister}; use crate::wallet::provenance::NodeChannelLiveness; @@ -1605,7 +1605,7 @@ fn build_with_store_internal( payment_store_res, channel_forwarding_stats_res, node_metris_res, - pending_payment_store_res, + payment_tracker_res, channel_tx_facts_store_res, address_pool_res, ) = runtime.block_on(async move { @@ -1626,8 +1626,8 @@ fn build_with_store_internal( read_node_metrics(&*kv_store_ref, Arc::clone(&logger_ref)), read_all_objects( &*kv_store_ref, - PENDING_PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE, - PENDING_PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE, + ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_PRIMARY_NAMESPACE, + ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_SECONDARY_NAMESPACE, Arc::clone(&logger_ref), ), read_n_objects( @@ -1963,15 +1963,15 @@ fn build_with_store_internal( }, }; - let pending_payment_store = match pending_payment_store_res { + let payment_tracker = match payment_tracker_res { // NOTE: This store must keep all its entries in memory: the wallet scans it in full on // every chain tip change and to resolve replaced transactions. It stays bounded anyway, // as entries are removed once a payment is no longer pending. - Ok(pending_payments) => Arc::new(PendingPaymentStore::new( - pending_payments, + Ok(tracked_payments) => Arc::new(OnchainPaymentTracker::new( + tracked_payments, KeepAllEntries, - PENDING_PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE.to_string(), - PENDING_PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE.to_string(), + ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_PRIMARY_NAMESPACE.to_string(), + ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_SECONDARY_NAMESPACE.to_string(), Arc::clone(&kv_store), Arc::clone(&logger), )), @@ -2019,7 +2019,7 @@ fn build_with_store_internal( Arc::clone(&runtime), Arc::clone(&config), Arc::clone(&logger), - Arc::clone(&pending_payment_store), + Arc::clone(&payment_tracker), Arc::clone(&channel_tx_facts_store), )); diff --git a/src/io/mod.rs b/src/io/mod.rs index 5ff6aaff06..1388005cc4 100644 --- a/src/io/mod.rs +++ b/src/io/mod.rs @@ -33,9 +33,9 @@ pub(crate) const PEER_INFO_PERSISTENCE_KEY: &str = "peers"; pub(crate) const PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE: &str = "payments"; pub(crate) const PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE: &str = ""; -/// The pending payment information will be persisted under this prefix. -pub(crate) const PENDING_PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE: &str = "pending_payments"; -pub(crate) const PENDING_PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE: &str = ""; +/// Tracked on-chain payments are persisted under this prefix. +pub(crate) const ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_PRIMARY_NAMESPACE: &str = "pending_payments"; +pub(crate) const ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_SECONDARY_NAMESPACE: &str = ""; /// The channel transaction provenance facts will be persisted under this prefix. pub(crate) const CHANNEL_TX_FACTS_PERSISTENCE_PRIMARY_NAMESPACE: &str = "channel_tx_facts"; diff --git a/src/lib.rs b/src/lib.rs index 6c3941134a..f3a33eddf2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3343,7 +3343,7 @@ mod tests { value: Amount::from_sat(change_sat), script_pubkey: test_p2wpkh_script(2), }); - crate::payment::pending_payment_store::test_funding_contribution_with_parts( + crate::wallet::payment_tracker::test_funding_contribution_with_parts( 1_001, 1_000, max_feerate_sat_per_kwu, diff --git a/src/payment/mod.rs b/src/payment/mod.rs index 64bc7b526e..ade8c2a85e 100644 --- a/src/payment/mod.rs +++ b/src/payment/mod.rs @@ -16,7 +16,6 @@ pub(crate) mod forwarding_store; mod hrn; mod metadata; mod onchain; -pub(crate) mod pending_payment_store; mod spontaneous; pub(crate) mod store; #[cfg(feature = "unified-payments")] @@ -34,7 +33,6 @@ pub use forwarding::{ pub(crate) use hrn::HRNResolver; pub(crate) use metadata::PaymentMetadata; pub use onchain::OnchainPayment; -pub(crate) use pending_payment_store::{FundingTxCandidate, PendingPaymentDetails}; pub use spontaneous::SpontaneousPayment; pub use store::{ Channel, ConfirmationStatus, LSPS2Parameters, PageToken, PaymentDetails, PaymentDetailsPage, diff --git a/src/types.rs b/src/types.rs index 39935bd2ba..aac9c880d9 100644 --- a/src/types.rs +++ b/src/types.rs @@ -45,10 +45,9 @@ use crate::liquidity::client::lsps2::router::LSPS2Router; use crate::logger::Logger; use crate::message_handler::NodeCustomMessageHandler; use crate::payment::NodeOffersMessageHandler; -use crate::payment::{ - ChannelPairForwardingStats, ForwardedPaymentDetails, PaymentDetails, PendingPaymentDetails, -}; +use crate::payment::{ChannelPairForwardingStats, ForwardedPaymentDetails, PaymentDetails}; use crate::runtime::RuntimeSpawner; +use crate::wallet::payment_tracker::TrackedOnchainPayment; use crate::wallet::provenance::ChannelTxFacts; #[cfg(feature = "uniffi")] @@ -757,4 +756,5 @@ impl From<&(u64, Vec)> for CustomTlvRecord { } } -pub(crate) type PendingPaymentStore = DataStore, KeepAllEntries>; +pub(crate) type OnchainPaymentTracker = + DataStore, KeepAllEntries>; diff --git a/src/wallet/mod.rs b/src/wallet/mod.rs index 11cfa90228..2ff6cd5eee 100644 --- a/src/wallet/mod.rs +++ b/src/wallet/mod.rs @@ -70,11 +70,11 @@ use crate::fee_estimator::{ConfirmationTarget, FeeEstimator, OnchainFeeEstimator use crate::logger::{log_debug, log_error, log_info, log_trace, log_warn, LdkLogger, Logger}; use crate::payment::store::{Channel, ConfirmationStatus, PaymentDetailsUpdate}; use crate::payment::{ - FundingTxCandidate, PaymentDetails, PaymentDirection, PaymentKind, PaymentStatus, - PendingPaymentDetails, TransactionType, + PaymentDetails, PaymentDirection, PaymentKind, PaymentStatus, TransactionType, }; use crate::runtime::Runtime; -use crate::types::{Broadcaster, ChannelTxFactsStore, PaymentStore, PendingPaymentStore}; +use crate::types::{Broadcaster, ChannelTxFactsStore, OnchainPaymentTracker, PaymentStore}; +use crate::wallet::payment_tracker::{tracks_channel, FundingTxCandidate, TrackedOnchainPayment}; use crate::wallet::provenance::{ ChannelLiveness, ChannelTxFacts, ChannelTxFactsRejection, FactsAdmission, FactsRecordOutcome, FactsRetention, LocalFundingFigures, RetentionCheck, TxProvenance, @@ -107,6 +107,7 @@ pub(crate) enum SignedFundingRecord { } mod payment_stores; +pub(crate) mod payment_tracker; pub(crate) mod persist; pub(crate) mod provenance; pub(crate) mod ser; @@ -207,7 +208,7 @@ impl Wallet { persisted_pool_indices: Vec, broadcaster: Arc, fee_estimator: Arc, chain_source: Arc, payment_store: Arc, runtime: Arc, config: Arc, - logger: Arc, pending_payment_store: Arc, + logger: Arc, payment_tracker: Arc, channel_tx_facts_store: Arc, ) -> Self { let address_pool = Mutex::new(AddressPool::new(persisted_pool_indices, &wallet, &logger)); @@ -226,7 +227,7 @@ impl Wallet { runtime, config, logger, - payment_stores: PaymentStores::new(payment_store, pending_payment_store), + payment_stores: PaymentStores::new(payment_store, payment_tracker), channel_tx_facts_store, channel_liveness: OnceLock::new(), facts_retention: FactsRetention::new(), @@ -570,7 +571,7 @@ impl Wallet { /// wallet's view by this sync. async fn pending_send_txids(&self) -> Vec<(Txid, Vec)> { let mut sends = Vec::new(); - for pending in self.payment_stores.pending_payments(|p| p.txid().is_some()).await { + for pending in self.payment_stores.tracked_payments(|p| p.txid().is_some()).await { let record = match self.payment_stores.payment(&pending.id()).await { Ok(Some(record)) => record, Ok(None) => continue, @@ -800,13 +801,13 @@ impl Wallet { WalletEvent::ChainTipChanged { new_tip, .. } => { // An entry whose transaction wallet sync has yet to observe doesn't have a // payment record yet, so it cannot graduate. - let pending_payments: Vec = - self.payment_stores.pending_payments(|p| p.txid().is_some()).await; + let tracked_payments: Vec = + self.payment_stores.tracked_payments(|p| p.txid().is_some()).await; let mut unconfirmed_outbound_txids: Vec = Vec::new(); let mut unclassified_transactions: Vec<(PaymentId, Txid)> = Vec::new(); - for payment in pending_payments { + for payment in tracked_payments { // The pass is re-derived at every tip, so an entry whose record cannot be // read now is left for the next one rather than costing the others theirs. let details = match self.payment_stores.payment(&payment.id()).await { @@ -878,7 +879,7 @@ impl Wallet { }) .await?; if graduated { - stores.remove_pending_payment(&payment_id).await?; + stores.remove_tracked_payment(&payment_id).await?; } } }, @@ -987,11 +988,11 @@ impl Wallet { // event is the restart's replay of the same transition: finish the interrupted // removal. if payment.status != PaymentStatus::Pending { - stores.remove_pending_payment(&payment_id).await?; + stores.remove_tracked_payment(&payment_id).await?; continue; } - self.upsert_pending_payment(&stores, payment, conflict_txids).await?; + self.upsert_tracked_payment(&stores, payment, conflict_txids).await?; }, WalletEvent::TxDropped { txid, tx } => { self.record_wallet_tx( @@ -1012,7 +1013,7 @@ impl Wallet { } /// Records the wallet transaction `txid` with the given status, resolving the payment it - /// belongs to and keeping its pending-store entry in step with the record. + /// belongs to and keeping its tracker entry in step with the record. async fn record_wallet_tx( &self, txid: Txid, tx: &Transaction, payment_status: PaymentStatus, confirmation_status: ConfirmationStatus, @@ -1030,7 +1031,7 @@ impl Wallet { let mut payment_id = found_id.unwrap_or_else(|| PaymentId(txid.to_byte_array())); let entry = match found_entry { Some(entry) => Some(entry), - None => stores.pending_payment(&payment_id).await?, + None => stores.tracked_payment(&payment_id).await?, }; match self @@ -1085,7 +1086,7 @@ impl Wallet { stores.insert_or_update_payment(payment.clone()).await?; if payment_status == PaymentStatus::Pending { - self.upsert_pending_payment(&stores, payment, Vec::new()).await?; + self.upsert_tracked_payment(&stores, payment, Vec::new()).await?; } else { // The transaction was first observed already confirmed through the reorg // depth, so the record is written settled and never graduates. An entry @@ -1093,7 +1094,7 @@ impl Wallet { // whose transaction nothing had observed before -- tracked this payment // alone, and with the payment settled tracks nothing further, as the entry // of a graduated record does. - stores.remove_pending_payment(&payment_id).await?; + stores.remove_tracked_payment(&payment_id).await?; } Ok(()) } @@ -1106,7 +1107,7 @@ impl Wallet { let stores = self.payment_stores.lock().await; let result = match stores.payment(&id).await { Ok(Some(record)) if record.status != PaymentStatus::Pending => { - stores.remove_pending_payment(&id).await + stores.remove_tracked_payment(&id).await }, Ok(_) => Ok(()), Err(e) => Err(e), @@ -1152,7 +1153,7 @@ impl Wallet { ); if unclassified { stores - .mutate_pending_payment(&payment_id, |existing| { + .mutate_tracked_payment(&payment_id, |existing| { let mut entry = existing?.clone(); entry.track_funding_channels(channels).then_some(entry) }) @@ -1205,7 +1206,7 @@ impl Wallet { else { return; }; - let pending_txids = self.pending_referenced_txids().await; + let pending_txids = self.tracked_txids().await; let mut walk = self.facts_retention.walk().await; for _ in 0..CHANNEL_TX_FACTS_PRUNE_PAGES_PER_TIP { @@ -1322,12 +1323,12 @@ impl Wallet { }) } - /// Every transaction the pending payment store still refers to: each entry's own + /// Every transaction the payment tracker still refers to: each entry's own /// transaction, the interactive-funding rounds it lists as candidates or as locked, and the /// conflicts wallet sync recorded against it. - async fn pending_referenced_txids(&self) -> HashSet { + async fn tracked_txids(&self) -> HashSet { let mut txids = HashSet::new(); - for entry in self.payment_stores.pending_payments(|_| true).await { + for entry in self.payment_stores.tracked_payments(|_| true).await { txids.extend(entry.txid()); txids.extend(entry.candidates().iter().map(|candidate| candidate.txid)); txids.extend(entry.conflicting_txids().iter().copied()); @@ -1392,7 +1393,7 @@ impl Wallet { /// `payment` and `record` are the entry and its record as the tip pass listed them; the /// decision is made from both as read again under the lock. async fn fail_funding_payment_lost_to_conflict( - &self, payment: &PendingPaymentDetails, record: &PaymentDetails, tip_height: u32, + &self, payment: &TrackedOnchainPayment, record: &PaymentDetails, tip_height: u32, ) -> Result { let payment_id = match record.kind { PaymentKind::Onchain { @@ -1416,7 +1417,7 @@ impl Wallet { let stores = self.payment_stores.lock().await; // Re-read the entry under the lock; the listing snapshot may predate a record write. - let entry = match stores.pending_payment(&payment_id).await? { + let entry = match stores.tracked_payment(&payment_id).await? { Some(entry) => entry, None => return Ok(false), }; @@ -1427,7 +1428,7 @@ impl Wallet { // is already recorded, and the graph may no longer contain the round that caused it. let details = match stores.payment(&payment_id).await? { Some(PaymentDetails { status: PaymentStatus::Failed, .. }) => { - stores.remove_pending_payment(&payment_id).await?; + stores.remove_tracked_payment(&payment_id).await?; log_info!( self.logger, "Removed the lingering entry of failed funding payment {}", @@ -1545,7 +1546,7 @@ impl Wallet { }) .await?; if outcome != FundingPaymentFailure::MovedOn { - stores.remove_pending_payment(&payment_id).await?; + stores.remove_tracked_payment(&payment_id).await?; } Ok(outcome) } @@ -1625,7 +1626,7 @@ impl Wallet { format!("of channel {} once splice round {} locked", channel_id, promoted) }, }; - let entries = stores.pending_payments(|entry| tracks_channel(entry, channel_id)).await; + let entries = stores.tracked_payments(|entry| tracks_channel(entry, channel_id)).await; for entry in entries { let details = match entry.txid() { Some(_) => match stores.payment(&entry.id()).await? { @@ -1686,7 +1687,7 @@ impl Wallet { None => None, }; let (Some(newest_round), Some(figures)) = (newest_round, figures) else { - stores.remove_pending_payment(&payment_id).await?; + stores.remove_tracked_payment(&payment_id).await?; log_info!( self.logger, "Removed the entry of unobserved funding payment {} {} without a record: no round of ours with a share on record", @@ -1710,7 +1711,7 @@ impl Wallet { PaymentStatus::Failed, ); stores.insert_or_update_payment(failed).await?; - stores.remove_pending_payment(&payment_id).await?; + stores.remove_tracked_payment(&payment_id).await?; log_info!( self.logger, "Failed unobserved funding payment {} {} under splice round {}: no round of ours can confirm", @@ -1867,7 +1868,7 @@ impl Wallet { &self, stores: &PaymentStoresGuard<'_>, channel_id: ChannelId, txid: Txid, ) -> Result<(), Error> { let entries = stores - .pending_payments(|entry| { + .tracked_payments(|entry| { tracks_channel(entry, channel_id) && entry.candidate(txid).is_some() && !entry.locked_rounds().contains(&txid) @@ -1876,7 +1877,7 @@ impl Wallet { for entry in entries { let payment_id = entry.id(); stores - .mutate_pending_payment(&payment_id, |existing| { + .mutate_tracked_payment(&payment_id, |existing| { let mut entry = existing?.clone(); if !entry.record_locked_round(txid) { return None; @@ -3096,7 +3097,7 @@ impl Wallet { /// the funding payment the round belongs to, so that whoever first observes the transaction — /// wallet sync, whichever party broadcast it — records it under that payment rather than as a /// payment of its own, with this node's figures rather than the wallet's view of a funding - /// output both parties own. The pending store gets the round's place in the channel's splice + /// output both parties own. The payment tracker gets the round's place in the channel's splice /// history, marked as awaiting broadcast until LDK reports the splice negotiated and /// [`Self::record_broadcast_splice_round`] clears the mark: only such a round can be abandoned /// without a trace, and [`Self::drop_abandoned_splice_rounds`] takes it back once LDK no longer @@ -3188,7 +3189,7 @@ impl Wallet { signed.fee_paid_msat = figures.fee_paid_msat; } - let prior_pending = stores.pending_payment(&payment_id).await?; + let prior_pending = stores.tracked_payment(&payment_id).await?; // A replayed signing event re-offers a transaction already recorded; nothing to add. if prior_pending.as_ref().is_some_and(|entry| entry.candidate(txid).is_some()) { return Ok(SignedFundingRecord::Recorded); @@ -3266,10 +3267,10 @@ impl Wallet { } stores - .mutate_pending_payment(&payment_id, |existing| { + .mutate_tracked_payment(&payment_id, |existing| { let mut changed = existing.is_none(); let mut entry = existing.cloned().unwrap_or_else(|| { - PendingPaymentDetails::signed_rounds(payment_id, Vec::new(), Vec::new()) + TrackedOnchainPayment::signed_rounds(payment_id, Vec::new(), Vec::new()) }); if entry.track_funding_channels(&funding_channels) { changed = true; @@ -3322,14 +3323,14 @@ impl Wallet { let stores = self.payment_stores.lock().await; let entries = stores - .pending_payments(|entry| { + .tracked_payments(|entry| { tracks_channel(entry, channel_id) && entry.candidate(txid).is_some() }) .await; for entry in entries { let payment_id = entry.id(); let marked = stores - .mutate_pending_payment(&payment_id, |existing| { + .mutate_tracked_payment(&payment_id, |existing| { let mut entry = existing?.clone(); let round = entry.funding.as_mut()?.rounds.iter_mut().find(|candidate| { @@ -3400,7 +3401,7 @@ impl Wallet { &self, stores: &PaymentStoresGuard<'_>, channel_id: ChannelId, tracked_rounds: &[Txid], ) -> Result<(), Error> { let entries = stores - .pending_payments(|entry| { + .tracked_payments(|entry| { tracks_channel(entry, channel_id) && entry.candidates().iter().any(|candidate| candidate.awaiting_broadcast) }) @@ -3448,7 +3449,7 @@ impl Wallet { } let mut emptied = false; stores - .mutate_pending_payment(&payment_id, |existing| { + .mutate_tracked_payment(&payment_id, |existing| { let mut entry = existing?.clone(); if handed_back.is_some() { entry.drop_candidates(&abandoned_txids); @@ -3460,7 +3461,7 @@ impl Wallet { }) .await?; if emptied { - stores.remove_pending_payment(&payment_id).await?; + stores.remove_tracked_payment(&payment_id).await?; } log_debug!( self.logger, @@ -3510,7 +3511,7 @@ impl Wallet { // for the same reason. stores.remove_payment(&payment_id).await?; self.withdraw_unshared_attributions(&entry, payment_id).await?; - stores.remove_pending_payment(&payment_id).await?; + stores.remove_tracked_payment(&payment_id).await?; log_debug!( self.logger, "Dropped abandoned splice round(s) {:?} and removed funding payment {}: nothing of ours \ @@ -3553,7 +3554,7 @@ impl Wallet { ); } stores - .mutate_pending_payment(&payment_id, |existing| { + .mutate_tracked_payment(&payment_id, |existing| { let mut entry = existing?.clone(); // With its history gone, the entry tracks the channels of the record's own // classification, if any. @@ -3588,7 +3589,7 @@ impl Wallet { /// recorded about the round stays, and the rounds of ours keep their /// figures: they say what the transaction would have been, which the drop does not change. async fn withdraw_unshared_attributions( - &self, entry: &PendingPaymentDetails, payment_id: PaymentId, + &self, entry: &TrackedOnchainPayment, payment_id: PaymentId, ) -> Result<(), Error> { for candidate in entry.candidates() { self.channel_tx_facts_store @@ -3623,7 +3624,7 @@ impl Wallet { ) -> Result<(), Error> { let channels: HashSet = self .payment_stores - .pending_payments(|entry| { + .tracked_payments(|entry| { entry.candidates().iter().any(|candidate| candidate.awaiting_broadcast) }) .await @@ -3651,7 +3652,7 @@ impl Wallet { } /// Records a funding payment the way the node does: the rounds this node signed supply the - /// candidate history, wallet sync writes the payment record and its pending-store entry once + /// candidate history, wallet sync writes the payment record and its tracker entry once /// it observes the transaction, and the duplicates sync created for those rounds are merged /// into the record. Composes that sequence for tests that need a recorded funding payment to /// act on. @@ -3663,9 +3664,9 @@ impl Wallet { let id = details.id; if !candidates.is_empty() { stores - .mutate_pending_payment(&id, |existing| { + .mutate_tracked_payment(&id, |existing| { let mut entry = existing.cloned().unwrap_or_else(|| { - PendingPaymentDetails::signed_rounds(id, Vec::new(), Vec::new()) + TrackedOnchainPayment::signed_rounds(id, Vec::new(), Vec::new()) }); entry.set_candidates(candidates.clone()); Some(entry) @@ -3673,7 +3674,7 @@ impl Wallet { .await?; } stores.insert_or_update_payment(details.clone()).await?; - self.upsert_pending_payment(&stores, details, Vec::new()).await?; + self.upsert_tracked_payment(&stores, details, Vec::new()).await?; self.merge_duplicate_candidate_records(&stores, id, &candidates).await } @@ -3731,7 +3732,7 @@ impl Wallet { // anything the record needs — the actively-broadcast candidate stays the record's // current txid. if matches!(status, ConfirmationStatus::Confirmed { .. }) { - let entry = stores.pending_payment(&id).await?; + let entry = stores.tracked_payment(&id).await?; match self .apply_funding_status_update_locked( stores, @@ -3774,7 +3775,7 @@ impl Wallet { PaymentStatus::Pending, ); stores.insert_or_update_payment(payment.clone()).await?; - self.upsert_pending_payment(stores, payment, Vec::new()).await?; + self.upsert_tracked_payment(stores, payment, Vec::new()).await?; }, FundingStatusUpdate::Foreign => { debug_assert!(false, "a candidate is never foreign to its own payment"); @@ -3791,7 +3792,7 @@ impl Wallet { // the duplicate through its payment record. Removed the other way around, the // leftover pending entry would be unreachable to the retry yet keep shadowing the // funding record in `find_payment_by_txid`'s direct probe. - stores.remove_pending_payment(&duplicate_id).await?; + stores.remove_tracked_payment(&duplicate_id).await?; stores.remove_payment(&duplicate_id).await?; } Ok(()) @@ -3865,18 +3866,18 @@ impl Wallet { PaymentDetails::new(payment_id, kind, amount_msat, fee_paid_msat, direction, payment_status) } - /// Inserts or refreshes the pending-store entry tracking `payment` toward graduation. The + /// Inserts or refreshes the tracker entry tracking `payment` toward graduation. The /// entry is written only when it is new or the transaction, conflicts or channels it tracks /// change: a change of the record's status or confirmation alone is the record's to carry. /// /// Every write of an on-chain payment record happens under the lock `stores` holds, so the /// record read here cannot go stale before the entry is written. - async fn upsert_pending_payment( + async fn upsert_tracked_payment( &self, stores: &PaymentStoresGuard<'_>, payment: PaymentDetails, conflicting_txids: Vec, ) -> Result<(), Error> { let id = payment.id; - // Only `Pending` payments belong in the pending store. + // Only `Pending` payments belong in the payment tracker. let record = stores.payment(&id).await?.unwrap_or(payment); if record.status != PaymentStatus::Pending { return Ok(()); @@ -3889,11 +3890,11 @@ impl Wallet { _ => return Ok(()), }; stores - .mutate_pending_payment(&id, |existing| { + .mutate_tracked_payment(&id, |existing| { let mut changed = existing.is_none(); let mut entry = existing .cloned() - .unwrap_or_else(|| PendingPaymentDetails::new(id, txid, Vec::new())); + .unwrap_or_else(|| TrackedOnchainPayment::new(id, txid, Vec::new())); changed |= entry.merge_observed(txid, conflicting_txids); changed |= entry.track_funding_channels(channels); changed.then_some(entry) @@ -3902,7 +3903,7 @@ impl Wallet { Ok(()) } - /// Removes the payment with the given id from the payment store, along with any pending-store + /// Removes the payment with the given id from the payment store, along with any tracker /// entry indexing its txids. An orphaned entry would keep resolving those txids to the removed /// record — routing later wallet-sync events to a payment that no longer exists — and nothing /// would ever clean it up, since graduation only removes entries whose record is still live. @@ -3916,7 +3917,7 @@ impl Wallet { // in between then leaves an unindexed record (benign, and the retry removes it) rather // than an entry indexing a removed record. let stores = self.payment_stores.lock().await; - stores.remove_pending_payment(payment_id).await?; + stores.remove_tracked_payment(payment_id).await?; stores.remove_payment(payment_id).await } @@ -3926,7 +3927,7 @@ impl Wallet { /// signing recorded about it — about the round it signed and about every other candidate of /// the history, including the rounds this node didn't contribute to. That is the only answer /// that holds before the payment record exists, and the only one left once the record - /// graduated out of the pending store. Otherwise the pending store is asked, by the record's + /// graduated out of the payment tracker. Otherwise the payment tracker is asked, by the record's /// own transaction, by its candidate history and by the conflicts wallet sync listed for it. async fn find_payment_by_txid(&self, target_txid: Txid) -> Result, Error> { let self_facts = self.channel_tx_facts_store.get(&target_txid).await; @@ -3935,10 +3936,10 @@ impl Wallet { /// [`Self::find_payment_by_txid`] from an already made read of the transaction's own facts, /// returning the pending entry the payment was found through, if any. A failed read is - /// logged and leaves the answer to the pending store. + /// logged and leaves the answer to the payment tracker. async fn find_payment_of_tx( &self, target_txid: Txid, self_facts: &Result, Error>, - ) -> Result<(Option, Option), Error> { + ) -> Result<(Option, Option), Error> { match self_facts { Ok(facts) => { if let Some(figures) = facts.as_ref().and_then(|facts| facts.local_figures.as_ref()) @@ -3957,11 +3958,11 @@ impl Wallet { } let direct_payment_id = PaymentId(target_txid.to_byte_array()); - if let Some(entry) = self.payment_stores.pending_payment(&direct_payment_id).await? { + if let Some(entry) = self.payment_stores.tracked_payment(&direct_payment_id).await? { return Ok((Some(direct_payment_id), Some(entry))); } - let owns = |p: &PendingPaymentDetails| { + let owns = |p: &TrackedOnchainPayment| { p.txid() == Some(target_txid) // A middle RBF round is not the record's current txid and may never have // received a `TxReplaced` event of its own, so map any of its candidate txids @@ -3970,7 +3971,7 @@ impl Wallet { }; let mut matches = self .payment_stores - .pending_payments(|p| owns(p) || p.conflicting_txids().contains(&target_txid)) + .tracked_payments(|p| owns(p) || p.conflicting_txids().contains(&target_txid)) .await; // An entry lists the transactions that replaced its own, so a transaction another entry // records as its own (a splice round that replaced a close, say) matches both. The entry @@ -3998,10 +3999,10 @@ impl Wallet { /// through its own last write, not just across this call — so that a funding-record writer's /// two-store write pair cannot interleave with the caller's decision sequence. The `stores` guard /// proves the lock is held across this call; the rest of that contract is the caller's. - /// `pending_payment` is the entry under `payment_id`, read under the same hold of the lock. + /// `tracked_payment` is the entry under `payment_id`, read under the same hold of the lock. async fn apply_funding_status_update_locked( &self, stores: &PaymentStoresGuard<'_>, payment_id: PaymentId, - pending_payment: Option, event_txid: Txid, + tracked_payment: Option, event_txid: Txid, confirmation_status: ConfirmationStatus, ) -> Result { // The caller's lock keeps the candidate history stable. The funding-type gate, the @@ -4030,7 +4031,7 @@ impl Wallet { // transaction that is neither — a close also spends the funding outpoint — must // not overwrite the record. let owns_event_tx = event_txid == current_txid - || pending_payment.as_ref().is_some_and(|p| p.candidate(event_txid).is_some()); + || tracked_payment.as_ref().is_some_and(|p| p.candidate(event_txid).is_some()); if !owns_event_tx { outcome = FundingStatusUpdate::Foreign; return None; @@ -4042,7 +4043,7 @@ impl Wallet { // anyway.) let mut target = payment.clone(); if let Some(candidate) = - pending_payment.as_ref().and_then(|p| p.candidate(event_txid)) + tracked_payment.as_ref().and_then(|p| p.candidate(event_txid)) { target.amount_msat = candidate.amount_msat; target.fee_paid_msat = candidate.fee_paid_msat; @@ -4069,7 +4070,7 @@ impl Wallet { // then has to track; as on the default `TxConfirmed` path, the entry is written only if // that changes it. An empty conflicting-txids list leaves any stored conflicts intact. if payment.status == PaymentStatus::Pending { - self.upsert_pending_payment(stores, payment, Vec::new()).await?; + self.upsert_tracked_payment(stores, payment, Vec::new()).await?; } Ok(FundingStatusUpdate::Applied) } @@ -4394,11 +4395,11 @@ impl Wallet { // Taken after the persister, the order wallet sync takes the two locks in. let stores = self.payment_stores.lock().await; // Wallet sync maps a replaced transaction to its payment with `find_payment_by_txid`. - // From the second bump on, the replaced `txid` matches only through the pending-store + // From the second bump on, the replaced `txid` matches only through the tracker // entry's `conflicting_txids`. A non-empty list in an update replaces the stored one, // so extend it rather than writing just `txid`. let mut conflicting_txids = stores - .pending_payment(&payment.id) + .tracked_payment(&payment.id) .await? .map(|pending| pending.conflicting_txids) .unwrap_or_default(); @@ -4406,7 +4407,7 @@ impl Wallet { conflicting_txids.push(txid); } stores.insert_or_update_payment(new_payment.clone()).await?; - self.upsert_pending_payment(&stores, new_payment, conflicting_txids).await + self.upsert_tracked_payment(&stores, new_payment, conflicting_txids).await } .await; if let Err(e) = recorded { @@ -4498,11 +4499,6 @@ fn pending_onchain_txid(record: &PaymentDetails) -> Option { } } -/// Whether `entry` tracks the funding payment of a splice into `channel_id`. -fn tracks_channel(entry: &PendingPaymentDetails, channel_id: ChannelId) -> bool { - entry.funding_channels().iter().any(|channel| channel.channel_id == channel_id) -} - /// Lists a channel's pending splice rounds that have a transaction — the negotiated predecessors /// and the round awaiting signatures, in LDK's order, each with this node's contribution to it — /// as the [`FundingCandidate`]s LDK hands the broadcaster for the round, for recording the round @@ -4986,14 +4982,14 @@ mod tests { BDK_WALLET_ADDRESS_POOL_SECONDARY_NAMESPACE, CHANNEL_TX_FACTS_PERSISTENCE_PRIMARY_NAMESPACE, CHANNEL_TX_FACTS_PERSISTENCE_SECONDARY_NAMESPACE, + ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_PRIMARY_NAMESPACE, + ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_SECONDARY_NAMESPACE, PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE, PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE, - PENDING_PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE, - PENDING_PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE, }; - use crate::payment::pending_payment_store::{ + use crate::types::{DynStore, DynStoreWrapper, UserChannelId}; + use crate::wallet::payment_tracker::{ test_funding_contribution_with_outputs, test_funding_contribution_with_parts, }; - use crate::types::{DynStore, DynStoreWrapper, UserChannelId}; use crate::wallet::provenance::{ live_channels_of, ChannelOutput, ChannelOutputFact, ChannelOutputRole, LocalFundingFigures, }; @@ -5338,11 +5334,11 @@ mod tests { Arc::clone(&store), Arc::clone(&logger), )); - let pending_payment_store = Arc::new(PendingPaymentStore::new( + let payment_tracker = Arc::new(OnchainPaymentTracker::new( Vec::new(), KeepAllEntries, - PENDING_PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE.to_string(), - PENDING_PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE.to_string(), + ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_PRIMARY_NAMESPACE.to_string(), + ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_SECONDARY_NAMESPACE.to_string(), Arc::clone(&store), Arc::clone(&logger), )); @@ -5370,7 +5366,7 @@ mod tests { runtime, config, logger, - pending_payment_store, + payment_tracker, channel_tx_facts_store, )) } @@ -5379,8 +5375,8 @@ mod tests { wallet.address_pool.lock().unwrap().available.iter().map(|(index, _)| *index).collect() } - async fn entry_of(wallet: &Wallet, id: &PaymentId) -> Option { - wallet.payment_stores.pending_payment_store().get(id).await.unwrap() + async fn entry_of(wallet: &Wallet, id: &PaymentId) -> Option { + wallet.payment_stores.payment_tracker().get(id).await.unwrap() } async fn record_of(wallet: &Wallet, id: &PaymentId) -> Option { @@ -5394,7 +5390,7 @@ mod tests { stores.insert_or_update_payment(details.clone()).await.unwrap(); let tracked = entry_for(&details, Vec::new()); stores - .pending_payment_store() + .payment_tracker() .mutate(&details.id, |existing| { let mut entry = existing.cloned().unwrap_or(tracked); entry.merge_observed(onchain_txid(&details), conflicting_txids); @@ -5425,24 +5421,24 @@ mod tests { } /// The entry wallet sync writes for the pending on-chain payment `details`. - fn entry_for(details: &PaymentDetails, conflicting_txids: Vec) -> PendingPaymentDetails { + fn entry_for(details: &PaymentDetails, conflicting_txids: Vec) -> TrackedOnchainPayment { let mut entry = - PendingPaymentDetails::new(details.id, onchain_txid(details), conflicting_txids); + TrackedOnchainPayment::new(details.id, onchain_txid(details), conflicting_txids); entry.track_funding_channels(&details_channels(details)); entry } /// Writes `entry` where the store has no entry under its id yet. - async fn insert_entry(wallet: &Wallet, entry: PendingPaymentDetails) { + async fn insert_entry(wallet: &Wallet, entry: TrackedOnchainPayment) { assert!(entry_of(wallet, &entry.id).await.is_none()); - wallet.payment_stores.pending_payment_store().insert(entry).await.unwrap(); + wallet.payment_stores.payment_tracker().insert(entry).await.unwrap(); } /// Records that wallet sync saw `conflicting_txids` conflict with the payment's transaction. async fn set_conflicts(wallet: &Wallet, id: PaymentId, conflicting_txids: Vec) { wallet .payment_stores - .pending_payment_store() + .payment_tracker() .mutate(&id, |existing| { let mut entry = existing?.clone(); let current_txid = entry.txid(); @@ -6776,7 +6772,7 @@ mod tests { assert!( wallet .payment_stores - .pending_payment_store() + .payment_tracker() .list_filter(|entry| entry.candidate(txid).is_some()) .await .is_empty(), @@ -6784,14 +6780,14 @@ mod tests { ); } - /// A signing event replayed after its pending-store write was lost re-derives the round's + /// A signing event replayed after its tracker write was lost re-derives the round's /// figures, from a contribution LDK may have adjusted the fee fields of since. The round's /// facts are immutable, so the replay adopts what is on record instead of offering a second /// answer the facts would refuse — which would leave the event replaying forever. #[tokio::test] async fn a_replayed_signing_adopts_the_recorded_figures() { let fail_store = - FailSwitchStore::failing_only(PENDING_PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE); + FailSwitchStore::failing_only(ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_PRIMARY_NAMESPACE); let store: Arc = Arc::new(DynStoreWrapper(fail_store.clone())); let wallet = new_test_wallet(Arc::clone(&store), false).await; let (counterparty_node_id, channel_id) = test_counterparty_and_channel(); @@ -7015,7 +7011,7 @@ mod tests { let mut graduated = PaymentDetailsUpdate::new(id); graduated.status = Some(PaymentStatus::Succeeded); wallet.payment_stores.payment_store().update(graduated).await.unwrap(); - wallet.payment_stores.pending_payment_store().remove(&id).await.unwrap(); + wallet.payment_stores.payment_tracker().remove(&id).await.unwrap(); assert_eq!(wallet.find_payment_by_txid(bump_txid).await.unwrap(), Some(id)); assert_eq!( @@ -7052,7 +7048,7 @@ mod tests { let mut graduated = PaymentDetailsUpdate::new(id); graduated.status = Some(PaymentStatus::Succeeded); wallet.payment_stores.payment_store().update(graduated).await.unwrap(); - wallet.payment_stores.pending_payment_store().remove(&id).await.unwrap(); + wallet.payment_stores.payment_tracker().remove(&id).await.unwrap(); assert_eq!(wallet.find_payment_by_txid(counterparty_txid).await.unwrap(), Some(id)); assert_eq!(wallet.find_payment_by_txid(txid).await.unwrap(), Some(id)); @@ -7097,7 +7093,7 @@ mod tests { let mut graduated = PaymentDetailsUpdate::new(id); graduated.status = Some(PaymentStatus::Succeeded); wallet.payment_stores.payment_store().update(graduated).await.unwrap(); - wallet.payment_stores.pending_payment_store().remove(&id).await.unwrap(); + wallet.payment_stores.payment_tracker().remove(&id).await.unwrap(); assert_eq!(wallet.find_payment_by_txid(counterparty_txid).await.unwrap(), Some(id)); } @@ -7171,7 +7167,7 @@ mod tests { }) .await .unwrap(); - wallet.payment_stores.pending_payment_store().remove(&failed_id).await.unwrap(); + wallet.payment_stores.payment_tracker().remove(&failed_id).await.unwrap(); let (bump_tx, bump_contribution) = splice_out_round(&wallet, 2, 499_000, 700); let bump_txid = bump_tx.compute_txid(); @@ -7228,7 +7224,7 @@ mod tests { }) .await .unwrap(); - wallet.payment_stores.pending_payment_store().remove(&failed_id).await.unwrap(); + wallet.payment_stores.payment_tracker().remove(&failed_id).await.unwrap(); let (bump_tx, bump_contribution) = splice_out_round(&wallet, 3, 498_000, 1_100); let bump_txid = bump_tx.compute_txid(); @@ -7396,7 +7392,7 @@ mod tests { .is_empty()); assert!(wallet .payment_stores - .pending_payment_store() + .payment_tracker() .list_page(None) .await .unwrap() @@ -7427,7 +7423,7 @@ mod tests { .is_empty()); assert!(wallet .payment_stores - .pending_payment_store() + .payment_tracker() .list_page(None) .await .unwrap() @@ -7473,7 +7469,7 @@ mod tests { .is_empty()); assert!(wallet .payment_stores - .pending_payment_store() + .payment_tracker() .list_page(None) .await .unwrap() @@ -8310,13 +8306,13 @@ mod tests { assert_eq!(entry.txid(), Some(bump_txid)); } - /// The signing write fails at the pending store: no payment record is minted for a round + /// The signing write fails at the payment tracker: no payment record is minted for a round /// nothing may broadcast, no entry is left half-written, and the replayed event records the /// round in full once the store recovers. #[tokio::test] async fn a_failed_first_round_signing_write_leaves_no_half_written_record() { let fail_store = - FailSwitchStore::failing_only(PENDING_PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE); + FailSwitchStore::failing_only(ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_PRIMARY_NAMESPACE); let store: Arc = Arc::new(DynStoreWrapper(fail_store.clone())); let wallet = new_test_wallet(Arc::clone(&store), false).await; let (counterparty_node_id, channel_id) = test_counterparty_and_channel(); @@ -8359,7 +8355,7 @@ mod tests { #[tokio::test] async fn a_failed_bump_signing_write_leaves_the_prior_round_tracked() { let fail_store = - FailSwitchStore::failing_only(PENDING_PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE); + FailSwitchStore::failing_only(ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_PRIMARY_NAMESPACE); let store: Arc = Arc::new(DynStoreWrapper(fail_store.clone())); let wallet = new_test_wallet(Arc::clone(&store), false).await; let (counterparty_node_id, channel_id) = test_counterparty_and_channel(); @@ -8451,7 +8447,7 @@ mod tests { assert!(funding_candidates(None, counterparty_node_id, channel_id).is_empty()); } - /// Graduation must decide from the live record and write only the status: a pending-store + /// Graduation must decide from the live record and write only the status: a tracker /// snapshot taken before a concurrent classification landed must not roll the record's /// figures back when the payment graduates to `Succeeded`. #[tokio::test] @@ -8499,7 +8495,7 @@ mod tests { assert!(entry_of(&wallet, &payment_id).await.is_none()); } - /// When the live record has diverged from the pending-store snapshot — here the snapshot + /// When the live record has diverged from the tracker snapshot — here the snapshot /// says Confirmed at graduation depth while the record says Unconfirmed — graduation must /// decline and keep the entry rather than force-writing `Succeeded` from stale state. The /// seeded divergence is synthetic (no current production writer downgrades a record's @@ -8554,12 +8550,12 @@ mod tests { } /// A confirmation and a reorg back to unconfirmed change only the payment record: the entry - /// tracks the same transaction throughout, so neither writes the pending store, and the record + /// tracks the same transaction throughout, so neither writes the payment tracker, and the record /// still graduates and returns to `Pending`. A reorg after graduation tracks it again. #[tokio::test] - async fn status_changes_leave_the_pending_store_unwritten() { + async fn status_changes_leave_the_payment_tracker_unwritten() { let fail_store = - FailSwitchStore::failing_only(PENDING_PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE); + FailSwitchStore::failing_only(ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_PRIMARY_NAMESPACE); let store: Arc = Arc::new(DynStoreWrapper(fail_store.clone())); let wallet = new_test_wallet(Arc::clone(&store), false).await; @@ -8784,7 +8780,7 @@ mod tests { assert_eq!(wallet.find_payment_by_txid(txid2).await.unwrap(), Some(payment_id)); } - /// Removing a payment must also drop its pending-store entry. The entry indexes the + /// Removing a payment must also drop its tracker entry. The entry indexes the /// payment's txids (current, conflicting, and candidates), so leaving it behind keeps /// resolving those txids to the removed record — routing later wallet events to a payment /// that no longer exists — and nothing else ever cleans it up, since graduation only @@ -8895,8 +8891,8 @@ mod tests { ); } - /// Payments without a pending-store entry — lightning payments, and on-chain payments that - /// already graduated — must remove cleanly: the unconditional pending-store removal relies + /// Payments without a tracker entry — lightning payments, and on-chain payments that + /// already graduated — must remove cleanly: the unconditional tracker removal relies /// on removing a missing key being a no-op. #[tokio::test] async fn remove_payment_without_pending_entry() { @@ -10169,7 +10165,7 @@ mod tests { }, ]; let details = interactive_funding_details(funding_id, txid2, Some(1_000_000), Some(400)); - fail_store.fail_next_remove_in(PENDING_PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE); + fail_store.fail_next_remove_in(ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_PRIMARY_NAMESPACE); let res = wallet.record_funding_payment(details.clone(), rounds.clone()).await; assert!(res.is_err(), "the injected remove failure must surface"); @@ -10550,7 +10546,7 @@ mod tests { (bump_txid, Some(bump_contribution)), ], ); - fail_store.fail_next_remove_in(PENDING_PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE); + fail_store.fail_next_remove_in(ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_PRIMARY_NAMESPACE); wallet.record_signed_funding(&bump_tx, &bump_candidates).await.unwrap(); // The signing is recorded in full and the duplicate is left as it was. @@ -10628,12 +10624,12 @@ mod tests { (bump_txid, Some(bump_contribution)), ], ); - fail_store.fail_next_remove_in(PENDING_PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE); + fail_store.fail_next_remove_in(ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_PRIMARY_NAMESPACE); wallet.record_signed_funding(&bump_tx, &bump_candidates).await.unwrap(); // The event's write meets the same failure: it must surface, so the event is replayed, // with the mark cleared and the duplicate untouched. - fail_store.fail_next_remove_in(PENDING_PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE); + fail_store.fail_next_remove_in(ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_PRIMARY_NAMESPACE); let res = wallet.record_broadcast_splice_round(channel_id, bump_txid).await; assert!(res.is_err(), "a failed merge must fail the write"); let entry = entry_of(&wallet, &id).await.expect("entry"); @@ -10654,12 +10650,12 @@ mod tests { /// duplicate leaves the funding record confirmed on the duplicate's transaction, the pending /// entry at its prior status and the duplicate untouched, and a re-run completes the removal: /// the merge is idempotent, so the record's next write or a replayed `SpliceNegotiated` event - /// can finish what a failure cut short. The failure injected is the pending store's, which the + /// can finish what a failure cut short. The failure injected is the payment tracker's, which the /// adoption writes after the payment store. #[tokio::test] async fn a_torn_duplicate_merge_is_completed_by_a_rerun() { let fail_store = - FailSwitchStore::failing_only(PENDING_PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE); + FailSwitchStore::failing_only(ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_PRIMARY_NAMESPACE); let store: Arc = Arc::new(DynStoreWrapper(fail_store.clone())); let wallet = new_test_wallet(store, false).await; let (counterparty_node_id, channel_id) = test_counterparty_and_channel(); @@ -10717,7 +10713,7 @@ mod tests { { let guard = wallet.payment_stores.lock().await; let res = wallet.merge_duplicate_candidate_records(&guard, id, &rounds).await; - assert!(res.is_err(), "the injected pending-store failure must surface"); + assert!(res.is_err(), "the injected tracker failure must surface"); } fail_store.fail_writes.store(false, Ordering::Release); let payment = record_of(&wallet, &id).await.expect("payment"); @@ -11016,7 +11012,7 @@ mod tests { wallet.record_signed_funding(&external_tx, &candidates[..1]).await.unwrap(); assert!(wallet .payment_stores - .pending_payment_store() + .payment_tracker() .list_page(None) .await .unwrap() @@ -12678,7 +12674,7 @@ mod tests { wallet.set_channel_liveness(TestLiveness::empty()); // The spend is long buried, but its payment is still pending: the facts of what it - // spends are kept for as long as the pending store refers to it, whatever its record + // spends are kept for as long as the payment tracker refers to it, whatever its record // already says of it. let close_txid = { let locked = wallet.inner.lock().unwrap(); @@ -12691,12 +12687,12 @@ mod tests { }; let id = PaymentId([46u8; 32]); let entry = entry_for(&funding_payment(id, close_txid, PaymentStatus::Pending), Vec::new()); - wallet.payment_stores.pending_payment_store().insert(entry).await.unwrap(); + wallet.payment_stores.payment_tracker().insert(entry).await.unwrap(); chain_tip_changed(&wallet, LONG_AFTER).await; assert!(wallet.channel_tx_facts(&funding_txid).await.is_some()); - wallet.payment_stores.pending_payment_store().remove(&id).await.unwrap(); + wallet.payment_stores.payment_tracker().remove(&id).await.unwrap(); chain_tip_changed(&wallet, LONG_AFTER + 1).await; assert!(wallet.channel_tx_facts(&funding_txid).await.is_none()); } @@ -12723,13 +12719,13 @@ mod tests { fee_paid_msat: Some(10), awaiting_broadcast: false, }]); - wallet.payment_stores.pending_payment_store().insert(entry).await.unwrap(); + wallet.payment_stores.payment_tracker().insert(entry).await.unwrap(); chain_tip_changed(&wallet, LONG_AFTER).await; assert!(wallet.channel_tx_facts(&funding_txid).await.is_some()); // Once the payment is no longer pending, nothing refers to the transaction anymore. - wallet.payment_stores.pending_payment_store().remove(&id).await.unwrap(); + wallet.payment_stores.payment_tracker().remove(&id).await.unwrap(); chain_tip_changed(&wallet, LONG_AFTER + 1).await; assert!(wallet.channel_tx_facts(&funding_txid).await.is_none()); } @@ -12925,7 +12921,7 @@ mod tests { let id = PaymentId([23u8; 32]); let txid = Txid::from_byte_array([24u8; 32]); // Wallet sync confirmed the payment through `ANTI_REORG_DELAY` before a writer with a - // `Pending` copy read earlier got to the pending store: the payment graduated, so no entry + // `Pending` copy read earlier got to the payment tracker: the payment graduated, so no entry // belongs there. wallet .payment_stores @@ -12936,7 +12932,7 @@ mod tests { let stores = wallet.payment_stores.lock().await; wallet - .upsert_pending_payment( + .upsert_tracked_payment( &stores, funding_payment(id, txid, PaymentStatus::Pending), Vec::new(), @@ -13033,7 +13029,7 @@ mod tests { wallet.payment_stores.payment_store().insert(payment.clone()).await.unwrap(); wallet .payment_stores - .pending_payment_store() + .payment_tracker() .insert(entry_for(&payment, Vec::new())) .await .unwrap(); @@ -13156,7 +13152,7 @@ mod tests { for snapshot in snapshots.into_iter().skip(baseline) { let is_recorded = snapshot.keys().any(|(primary_namespace, _, _)| { primary_namespace == PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE - || primary_namespace == PENDING_PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE + || primary_namespace == ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_PRIMARY_NAMESPACE }); recorded_at_some_point |= is_recorded; let store: Arc = @@ -13199,7 +13195,7 @@ mod tests { wallet.payment_stores.payment_store().insert(payment.clone()).await.unwrap(); wallet .payment_stores - .pending_payment_store() + .payment_tracker() .insert(entry_for(&payment, vec![original_txid])) .await .unwrap(); @@ -13211,7 +13207,7 @@ mod tests { assert!(is_in_wallet_view(&wallet, bump_txid)); assert!(!is_in_wallet_view(&wallet, original_txid)); - let entry = wallet.payment_stores.pending_payment(&payment_id).await.unwrap().unwrap(); + let entry = wallet.payment_stores.tracked_payment(&payment_id).await.unwrap().unwrap(); assert_eq!(entry.txid(), Some(onchain_txid(&payment))); } @@ -13243,7 +13239,7 @@ mod tests { wallet.payment_stores.payment_store().insert(payment.clone()).await.unwrap(); wallet .payment_stores - .pending_payment_store() + .payment_tracker() .insert(entry_for(&payment, vec![original_txid])) .await .unwrap(); @@ -13255,7 +13251,7 @@ mod tests { assert!(!is_in_wallet_view(&wallet, bump_txid)); } - /// A second bump must add the replaced txid to the pending-store entry's `conflicting_txids`. + /// A second bump must add the replaced txid to the tracker entry's `conflicting_txids`. /// The payment id is derived from the first txid and the payment's txid is the newest one, /// so wallet sync's `TxReplaced` event for an earlier replacement resolves the payment /// only through that list. Without it, the event finds no payment and is skipped. @@ -13333,7 +13329,7 @@ mod tests { ); wallet.payment_stores.payment_store().insert(details.clone()).await.unwrap(); let entry = entry_for(&details, vec![txid_a]); - wallet.payment_stores.pending_payment_store().insert(entry).await.unwrap(); + wallet.payment_stores.payment_tracker().insert(entry).await.unwrap(); // Bump again: B -> C. let txid_c = wallet.bump_fee_rbf(payment_id, None, 0).await.unwrap(); @@ -13343,7 +13339,7 @@ mod tests { // `PaymentId(txid_b)` is not the payment id and the payment's txid is C, so B must be in // `conflicting_txids` for wallet sync to find the payment. - let entry = wallet.payment_stores.pending_payment(&payment_id).await.unwrap().unwrap(); + let entry = wallet.payment_stores.tracked_payment(&payment_id).await.unwrap().unwrap(); assert_eq!(entry.conflicting_txids, vec![txid_a, txid_b]); assert_eq!(wallet.find_payment_by_txid(txid_b).await.unwrap(), Some(payment_id)); } diff --git a/src/wallet/payment_stores.rs b/src/wallet/payment_stores.rs index 861d176c21..c877481dda 100644 --- a/src/wallet/payment_stores.rs +++ b/src/wallet/payment_stores.rs @@ -6,20 +6,21 @@ // accordance with one or both of these licenses. //! The wallet's payment stores behind one API, so that every write the wallet makes to them -//! happens under the lock that keeps a payment record and its pending-store entry consistent. +//! happens under the lock that keeps a payment record and its tracker entry consistent. use std::ops::Deref; use std::sync::Arc; use lightning::ln::channelmanager::PaymentId; -use crate::payment::{PaymentDetails, PendingPaymentDetails}; -use crate::types::{PaymentStore, PendingPaymentStore}; +use crate::payment::PaymentDetails; +use crate::types::{OnchainPaymentTracker, PaymentStore}; +use crate::wallet::payment_tracker::TrackedOnchainPayment; use crate::Error; -/// The wallet's payment store and pending payment store, with the lock serializing their writers. +/// The wallet's payment store and payment tracker, with the lock serializing their writers. /// -/// The writers must observe the payment record and its pending-store entry (candidate history +/// The writers must observe the payment record and its tracker entry (candidate history /// included) as one consistent unit: wallet sync's event arms and the funding-record writers each /// hold the lock from payment-id resolution through their last write. Without the lock, a /// confirmation landing between a writer's two store writes sees the record but not the candidate @@ -33,7 +34,7 @@ use crate::Error; /// guard. pub(super) struct PaymentStores { payment_store: Arc, - pending_payment_store: Arc, + payment_tracker: Arc, update_lock: tokio::sync::Mutex<()>, } @@ -47,9 +48,9 @@ pub(super) struct PaymentStoresGuard<'a> { impl PaymentStores { pub(super) fn new( - payment_store: Arc, pending_payment_store: Arc, + payment_store: Arc, payment_tracker: Arc, ) -> Self { - Self { payment_store, pending_payment_store, update_lock: tokio::sync::Mutex::new(()) } + Self { payment_store, payment_tracker, update_lock: tokio::sync::Mutex::new(()) } } /// Takes the lock for as long as the returned guard lives. @@ -62,18 +63,18 @@ impl PaymentStores { self.payment_store.get(id).await } - /// The pending-store entry stored under `id`, if any. - pub(super) async fn pending_payment( + /// The tracker entry stored under `id`, if any. + pub(super) async fn tracked_payment( &self, id: &PaymentId, - ) -> Result, Error> { - self.pending_payment_store.get(id).await + ) -> Result, Error> { + self.payment_tracker.get(id).await } - /// The pending-store entries matching `f`. - pub(super) async fn pending_payments bool>( + /// The tracker entries matching `f`. + pub(super) async fn tracked_payments bool>( &self, f: F, - ) -> Vec { - self.pending_payment_store.list_filter(f).await + ) -> Vec { + self.payment_tracker.list_filter(f).await } } @@ -84,10 +85,10 @@ impl PaymentStores { &self.payment_store } - /// The pending payment store itself, for tests to set up and inspect entries around the + /// The payment tracker itself, for tests to set up and inspect entries around the /// wallet's API. - pub(super) fn pending_payment_store(&self) -> &PendingPaymentStore { - &self.pending_payment_store + pub(super) fn payment_tracker(&self) -> &OnchainPaymentTracker { + &self.payment_tracker } } @@ -125,20 +126,20 @@ impl PaymentStoresGuard<'_> { self.stores.payment_store.mutate(id, f).await } - /// Removes the pending-store entry stored under `id`, if any. - pub(super) async fn remove_pending_payment(&self, id: &PaymentId) -> Result<(), Error> { - self.stores.pending_payment_store.remove(id).await + /// Removes the tracker entry stored under `id`, if any. + pub(super) async fn remove_tracked_payment(&self, id: &PaymentId) -> Result<(), Error> { + self.stores.payment_tracker.remove(id).await } - /// Transforms the pending-store entry stored under `id` through `f` and persists the result, + /// Transforms the tracker entry stored under `id` through `f` and persists the result, /// all in one critical section of the store; see /// [`DataStore::mutate`](crate::data_store::DataStore::mutate). - pub(super) async fn mutate_pending_payment( + pub(super) async fn mutate_tracked_payment( &self, id: &PaymentId, f: F, - ) -> Result, Error> + ) -> Result, Error> where - F: FnOnce(Option<&PendingPaymentDetails>) -> Option, + F: FnOnce(Option<&TrackedOnchainPayment>) -> Option, { - self.stores.pending_payment_store.mutate(id, f).await + self.stores.payment_tracker.mutate(id, f).await } } diff --git a/src/payment/pending_payment_store.rs b/src/wallet/payment_tracker.rs similarity index 93% rename from src/payment/pending_payment_store.rs rename to src/wallet/payment_tracker.rs index cae9ebe70e..5c79b282e7 100644 --- a/src/payment/pending_payment_store.rs +++ b/src/wallet/payment_tracker.rs @@ -8,6 +8,7 @@ use bitcoin::Txid; use lightning::impl_writeable_tlv_based; use lightning::ln::channelmanager::PaymentId; +use lightning::ln::types::ChannelId; use crate::data_store::StorableObject; use crate::payment::store::Channel; @@ -43,7 +44,7 @@ impl_writeable_tlv_based!(FundingTxCandidate, { (6, awaiting_broadcast, required), }); -/// The interactive-funding (splice) part of a [`PendingPaymentDetails`] entry. +/// The interactive-funding (splice) part of a [`TrackedOnchainPayment`] entry. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub(crate) struct FundingRounds { /// The channels whose interactive funding the entry tracks, as the signing of a round or the @@ -66,7 +67,7 @@ impl_writeable_tlv_based!(FundingRounds, { (4, locked, optional_vec), }); -/// A pending payment tracked by LDK Node, keyed by [`PaymentId`]. +/// A pending on-chain payment tracked by LDK Node, keyed by [`PaymentId`]. /// /// The payment's record in the payment store is what says its status, confirmation, direction and /// transaction type; an entry only indexes the transactions that may still change the record. @@ -78,7 +79,7 @@ impl_writeable_tlv_based!(FundingRounds, { /// the fields do not partition by payment type. An entry with neither a txid nor any funding /// round tracks no payment and is removed. #[derive(Clone, Debug, PartialEq, Eq)] -pub(crate) struct PendingPaymentDetails { +pub(crate) struct TrackedOnchainPayment { /// The payment this entry tracks. pub id: PaymentId, /// The payment record's current transaction, or `None` for a splice whose transaction wallet @@ -95,7 +96,7 @@ pub(crate) struct PendingPaymentDetails { pub funding: Option, } -impl PendingPaymentDetails { +impl TrackedOnchainPayment { pub(crate) fn new(id: PaymentId, txid: Txid, conflicting_txids: Vec) -> Self { Self { id, txid: Some(txid), conflicting_txids, funding: None } } @@ -206,14 +207,14 @@ impl PendingPaymentDetails { } } -impl_writeable_tlv_based!(PendingPaymentDetails, { +impl_writeable_tlv_based!(TrackedOnchainPayment, { (0, id, required), (2, txid, option), (4, conflicting_txids, optional_vec), (6, funding, option), }); -impl StorableObject for PendingPaymentDetails { +impl StorableObject for TrackedOnchainPayment { type Id = PaymentId; fn id(&self) -> Self::Id { @@ -221,6 +222,11 @@ impl StorableObject for PendingPaymentDetails { } } +/// Whether `entry` tracks the funding payment of a splice into `channel_id`. +pub(crate) fn tracks_channel(entry: &TrackedOnchainPayment, channel_id: ChannelId) -> bool { + entry.funding_channels().iter().any(|channel| channel.channel_id == channel_id) +} + /// Builds a [`FundingContribution`] for tests through its `Readable` impl — the only path open /// outside `rust-lightning`, which keeps its builder private. The length-prefixed stream contains /// the required TLV records (the given estimated fee in satoshis, feerate, max feerate, and the @@ -333,7 +339,7 @@ mod tests { ]; let mut pending = - PendingPaymentDetails::new(payment_id, rbf_txid, vec![first_txid, counterparty_txid]); + TrackedOnchainPayment::new(payment_id, rbf_txid, vec![first_txid, counterparty_txid]); pending.set_candidates(candidates); // Each candidate resolves to its own figures, so a non-last candidate that confirms reports @@ -359,7 +365,7 @@ mod tests { let payment_id = PaymentId(original_txid.to_byte_array()); let mut pending_payment = - PendingPaymentDetails::new(payment_id, replacement_txid, vec![original_txid]); + TrackedOnchainPayment::new(payment_id, replacement_txid, vec![original_txid]); assert!(pending_payment.merge_observed(original_txid, Vec::new())); assert_eq!(pending_payment.txid(), Some(original_txid)); @@ -375,7 +381,7 @@ mod tests { #[test] fn observing_the_tracked_transaction_again_changes_nothing() { let txid = test_txid(1); - let mut entry = PendingPaymentDetails::new(PaymentId([1u8; 32]), txid, vec![test_txid(2)]); + let mut entry = TrackedOnchainPayment::new(PaymentId([1u8; 32]), txid, vec![test_txid(2)]); let before = entry.clone(); assert!(!entry.merge_observed(txid, Vec::new())); assert!(!entry.merge_observed(txid, vec![test_txid(2)])); @@ -388,7 +394,7 @@ mod tests { let payment_id = PaymentId([7u8; 32]); let txid = Txid::from_byte_array([8u8; 32]); let mut record = - PendingPaymentDetails::new(payment_id, txid, vec![Txid::from_byte_array([9u8; 32])]); + TrackedOnchainPayment::new(payment_id, txid, vec![Txid::from_byte_array([9u8; 32])]); record.set_candidates(vec![FundingTxCandidate { txid, amount_msat: Some(1_000), @@ -397,18 +403,18 @@ mod tests { }]); let encoded = record.encode(); - let decoded = PendingPaymentDetails::read(&mut &encoded[..]).unwrap(); + let decoded = TrackedOnchainPayment::read(&mut &encoded[..]).unwrap(); assert_eq!(record, decoded); assert_eq!(decoded.id(), payment_id); assert_eq!(decoded.txid(), Some(txid)); // The rounds of a splice signed before any transaction was observed. - let signed = PendingPaymentDetails::signed_rounds( + let signed = TrackedOnchainPayment::signed_rounds( payment_id, Vec::new(), record.candidates().to_vec(), ); - let decoded = PendingPaymentDetails::read(&mut &signed.encode()[..]).unwrap(); + let decoded = TrackedOnchainPayment::read(&mut &signed.encode()[..]).unwrap(); assert_eq!(decoded, signed); assert_eq!(decoded.txid(), None); } @@ -423,10 +429,10 @@ mod tests { } } - fn entry(candidates: Vec) -> PendingPaymentDetails { + fn entry(candidates: Vec) -> TrackedOnchainPayment { let payment_id = PaymentId([1u8; 32]); let txid = candidates.last().expect("at least one candidate").txid; - let mut entry = PendingPaymentDetails::new(payment_id, txid, vec![]); + let mut entry = TrackedOnchainPayment::new(payment_id, txid, vec![]); entry.set_candidates(candidates); entry } @@ -436,13 +442,13 @@ mod tests { #[test] fn locked_rounds_round_trip_and_survive_a_merge() { let mut stored = entry(vec![candidate(2, false)]); - let decoded: PendingPaymentDetails = + let decoded: TrackedOnchainPayment = Readable::read(&mut &stored.encode()[..]).expect("encoding must round-trip"); assert!(decoded.locked_rounds().is_empty()); assert!(stored.record_locked_round(test_txid(2))); assert!(!stored.record_locked_round(test_txid(2))); - let decoded: PendingPaymentDetails = + let decoded: TrackedOnchainPayment = Readable::read(&mut &stored.encode()[..]).expect("encoding must round-trip"); assert_eq!(decoded, stored); diff --git a/src/wallet/provenance.rs b/src/wallet/provenance.rs index 819e5ac498..c2f641a569 100644 --- a/src/wallet/provenance.rs +++ b/src/wallet/provenance.rs @@ -624,7 +624,7 @@ pub(crate) struct RetentionCheck<'a> { pub retention_blocks: u32, /// The channels this node still has on-chain state for. pub live_channels: &'a HashSet, - /// The transactions the pending payment store still refers to — its records' own + /// The transactions the payment tracker still refers to — its records' own /// transactions, their interactive-funding candidates, the rounds that locked and the /// conflicts wallet sync listed. A payment is pending exactly while its classification can /// still be written onto it, so a transaction listed here has yet to reach its record. From 181c4c7582d7196715cdc730142436cbbbbdf8f4 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Tue, 17 Nov 2026 11:15:29 +0100 Subject: [PATCH 09/11] Move funding contribution test builders The test-only builders for funding contributions lived in the payment tracker module, although they have nothing to do with tracked payments and only serve the wallet tests. Move them into a test-only module of the wallet, so the tracker module holds only the tracker and its own tests. Written with the help of an AI tool. Co-Authored-By: HAL 9000 --- src/lib.rs | 2 +- src/wallet/mod.rs | 8 ++-- src/wallet/payment_tracker.rs | 74 --------------------------------- src/wallet/test_utils.rs | 78 +++++++++++++++++++++++++++++++++++ 4 files changed, 84 insertions(+), 78 deletions(-) create mode 100644 src/wallet/test_utils.rs diff --git a/src/lib.rs b/src/lib.rs index f3a33eddf2..ed8b35ff61 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3343,7 +3343,7 @@ mod tests { value: Amount::from_sat(change_sat), script_pubkey: test_p2wpkh_script(2), }); - crate::wallet::payment_tracker::test_funding_contribution_with_parts( + crate::wallet::test_utils::test_funding_contribution_with_parts( 1_001, 1_000, max_feerate_sat_per_kwu, diff --git a/src/wallet/mod.rs b/src/wallet/mod.rs index 2ff6cd5eee..4a7803770e 100644 --- a/src/wallet/mod.rs +++ b/src/wallet/mod.rs @@ -111,6 +111,8 @@ pub(crate) mod payment_tracker; pub(crate) mod persist; pub(crate) mod provenance; pub(crate) mod ser; +#[cfg(test)] +pub(crate) mod test_utils; pub(crate) const DUST_LIMIT_SATS: u64 = 546; @@ -4987,12 +4989,12 @@ mod tests { PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE, PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE, }; use crate::types::{DynStore, DynStoreWrapper, UserChannelId}; - use crate::wallet::payment_tracker::{ - test_funding_contribution_with_outputs, test_funding_contribution_with_parts, - }; use crate::wallet::provenance::{ live_channels_of, ChannelOutput, ChannelOutputFact, ChannelOutputRole, LocalFundingFigures, }; + use crate::wallet::test_utils::{ + test_funding_contribution_with_outputs, test_funding_contribution_with_parts, + }; use crate::{NodeMetrics, PersistedNodeMetrics}; const EXTERNAL_DESCRIPTOR: &str = "wpkh(tprv8ZgxMBicQKsPdy6LMhUtFHAgpocR8GC6QmwMSFpZs7h6Eziw3SpThFfczTDh5rW2krkqffa11UpX3XkeTTB2FvzZKWXqPY54Y6Rq4AQ5R8L/84'/1'/0'/0/*)"; diff --git a/src/wallet/payment_tracker.rs b/src/wallet/payment_tracker.rs index 5c79b282e7..1cb8817a08 100644 --- a/src/wallet/payment_tracker.rs +++ b/src/wallet/payment_tracker.rs @@ -227,80 +227,6 @@ pub(crate) fn tracks_channel(entry: &TrackedOnchainPayment, channel_id: ChannelI entry.funding_channels().iter().any(|channel| channel.channel_id == channel_id) } -/// Builds a [`FundingContribution`] for tests through its `Readable` impl — the only path open -/// outside `rust-lightning`, which keeps its builder private. The length-prefixed stream contains -/// the required TLV records (the given estimated fee in satoshis, feerate, max feerate, and the -/// is-splice flag) plus the given contributed outputs. -/// -/// [`FundingContribution`]: lightning::ln::funding::FundingContribution -#[cfg(test)] -pub(crate) fn test_funding_contribution_with_outputs( - estimated_fee_sat: u64, feerate: u64, outputs: &[bitcoin::TxOut], -) -> lightning::ln::funding::FundingContribution { - test_funding_contribution_with_parts(estimated_fee_sat, feerate, feerate, &[], outputs, None) -} - -/// Builds a [`FundingContribution`] for tests from its parts: the given estimated fee, an input -/// spending output 0 — which must be P2WPKH — of each given previous transaction, the given -/// contributed outputs and change output, and the given input-selection and maximum feerates, -/// with the is-splice flag set. -/// -/// [`FundingContribution`]: lightning::ln::funding::FundingContribution -#[cfg(test)] -pub(crate) fn test_funding_contribution_with_parts( - estimated_fee_sat: u64, feerate: u64, max_feerate: u64, prevtxs: &[bitcoin::Transaction], - outputs: &[bitcoin::TxOut], change_output: Option<&bitcoin::TxOut>, -) -> lightning::ln::funding::FundingContribution { - use lightning::util::ser::{BigSize, Writeable}; - use lightning::util::wallet_utils::ConfirmedUtxo; - let mut records = vec![1, 8]; // (1, estimated_fee) - records.extend_from_slice(&estimated_fee_sat.to_be_bytes()); - if !prevtxs.is_empty() { - let mut input_bytes = Vec::new(); - for prevtx in prevtxs { - ConfirmedUtxo::new_p2wpkh(prevtx.clone(), 0) - .expect("test prevtx output 0 must be P2WPKH") - .write(&mut input_bytes) - .expect("in-memory write must succeed"); - } - records.push(3); // (3, inputs) - BigSize(input_bytes.len() as u64) - .write(&mut records) - .expect("in-memory write must succeed"); - records.extend_from_slice(&input_bytes); - } - if !outputs.is_empty() { - let mut output_bytes = Vec::new(); - for output in outputs { - output.write(&mut output_bytes).expect("in-memory write must succeed"); - } - records.push(5); // (5, outputs) - BigSize(output_bytes.len() as u64) - .write(&mut records) - .expect("in-memory write must succeed"); - records.extend_from_slice(&output_bytes); - } - if let Some(change_output) = change_output { - let change_bytes = change_output.encode(); - records.push(7); // (7, change_output) - BigSize(change_bytes.len() as u64) - .write(&mut records) - .expect("in-memory write must succeed"); - records.extend_from_slice(&change_bytes); - } - records.extend_from_slice(&[9, 8]); // (9, feerate) - records.extend_from_slice(&feerate.to_be_bytes()); - records.extend_from_slice(&[11, 8]); // (11, max_feerate) - records.extend_from_slice(&max_feerate.to_be_bytes()); - records.extend_from_slice(&[13, 1, 1]); // (13, is_splice: true) - let mut tlv_bytes = Vec::new(); - // BigSize length prefix over the TLV records above. - BigSize(records.len() as u64).write(&mut tlv_bytes).expect("in-memory write must succeed"); - tlv_bytes.extend(records); - lightning::util::ser::Readable::read(&mut &tlv_bytes[..]) - .expect("hand-built TLV stream must decode") -} - #[cfg(test)] mod tests { use bitcoin::hashes::Hash; diff --git a/src/wallet/test_utils.rs b/src/wallet/test_utils.rs new file mode 100644 index 0000000000..1faa386897 --- /dev/null +++ b/src/wallet/test_utils.rs @@ -0,0 +1,78 @@ +// This file is Copyright its original authors, visible in version control history. +// +// This file is licensed under the Apache License, Version 2.0 or the MIT license , at your option. You may not use this file except in +// accordance with one or both of these licenses. + +/// Builds a [`FundingContribution`] for tests through its `Readable` impl — the only path open +/// outside `rust-lightning`, which keeps its builder private. The length-prefixed stream contains +/// the required TLV records (the given estimated fee in satoshis, feerate, max feerate, and the +/// is-splice flag) plus the given contributed outputs. +/// +/// [`FundingContribution`]: lightning::ln::funding::FundingContribution +pub(crate) fn test_funding_contribution_with_outputs( + estimated_fee_sat: u64, feerate: u64, outputs: &[bitcoin::TxOut], +) -> lightning::ln::funding::FundingContribution { + test_funding_contribution_with_parts(estimated_fee_sat, feerate, feerate, &[], outputs, None) +} + +/// Builds a [`FundingContribution`] for tests from its parts: the given estimated fee, an input +/// spending output 0 — which must be P2WPKH — of each given previous transaction, the given +/// contributed outputs and change output, and the given input-selection and maximum feerates, +/// with the is-splice flag set. +/// +/// [`FundingContribution`]: lightning::ln::funding::FundingContribution +pub(crate) fn test_funding_contribution_with_parts( + estimated_fee_sat: u64, feerate: u64, max_feerate: u64, prevtxs: &[bitcoin::Transaction], + outputs: &[bitcoin::TxOut], change_output: Option<&bitcoin::TxOut>, +) -> lightning::ln::funding::FundingContribution { + use lightning::util::ser::{BigSize, Writeable}; + use lightning::util::wallet_utils::ConfirmedUtxo; + let mut records = vec![1, 8]; // (1, estimated_fee) + records.extend_from_slice(&estimated_fee_sat.to_be_bytes()); + if !prevtxs.is_empty() { + let mut input_bytes = Vec::new(); + for prevtx in prevtxs { + ConfirmedUtxo::new_p2wpkh(prevtx.clone(), 0) + .expect("test prevtx output 0 must be P2WPKH") + .write(&mut input_bytes) + .expect("in-memory write must succeed"); + } + records.push(3); // (3, inputs) + BigSize(input_bytes.len() as u64) + .write(&mut records) + .expect("in-memory write must succeed"); + records.extend_from_slice(&input_bytes); + } + if !outputs.is_empty() { + let mut output_bytes = Vec::new(); + for output in outputs { + output.write(&mut output_bytes).expect("in-memory write must succeed"); + } + records.push(5); // (5, outputs) + BigSize(output_bytes.len() as u64) + .write(&mut records) + .expect("in-memory write must succeed"); + records.extend_from_slice(&output_bytes); + } + if let Some(change_output) = change_output { + let change_bytes = change_output.encode(); + records.push(7); // (7, change_output) + BigSize(change_bytes.len() as u64) + .write(&mut records) + .expect("in-memory write must succeed"); + records.extend_from_slice(&change_bytes); + } + records.extend_from_slice(&[9, 8]); // (9, feerate) + records.extend_from_slice(&feerate.to_be_bytes()); + records.extend_from_slice(&[11, 8]); // (11, max_feerate) + records.extend_from_slice(&max_feerate.to_be_bytes()); + records.extend_from_slice(&[13, 1, 1]); // (13, is_splice: true) + let mut tlv_bytes = Vec::new(); + // BigSize length prefix over the TLV records above. + BigSize(records.len() as u64).write(&mut tlv_bytes).expect("in-memory write must succeed"); + tlv_bytes.extend(records); + lightning::util::ser::Readable::read(&mut &tlv_bytes[..]) + .expect("hand-built TLV stream must decode") +} From 9c20efb909dcd3021779c54ee306e0eb68f24b70 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Tue, 17 Nov 2026 11:19:48 +0100 Subject: [PATCH 10/11] Tidy the payment tracker entry API The tracker entry carried getters for fields that are already public and thin wrappers around creating its funding state, the lock handler spelled out a bool-to-Option conversion, and a test-only helper lived among the production methods while another test helper duplicated the logic wallet sync uses to track a pending payment. Access the fields directly, inline the wrappers, move the funding test helper into the test module and let the pending-payment helper go through the production upsert path, so tests exercise the same code as the node. Behaviour is unchanged. Written with the help of an AI tool. Co-Authored-By: HAL 9000 --- src/wallet/mod.rs | 176 ++++++++++++++++------------------ src/wallet/payment_tracker.rs | 41 ++------ 2 files changed, 91 insertions(+), 126 deletions(-) diff --git a/src/wallet/mod.rs b/src/wallet/mod.rs index 4a7803770e..44e1fe1ea2 100644 --- a/src/wallet/mod.rs +++ b/src/wallet/mod.rs @@ -573,7 +573,7 @@ impl Wallet { /// wallet's view by this sync. async fn pending_send_txids(&self) -> Vec<(Txid, Vec)> { let mut sends = Vec::new(); - for pending in self.payment_stores.tracked_payments(|p| p.txid().is_some()).await { + for pending in self.payment_stores.tracked_payments(|p| p.txid.is_some()).await { let record = match self.payment_stores.payment(&pending.id()).await { Ok(Some(record)) => record, Ok(None) => continue, @@ -599,7 +599,7 @@ impl Wallet { tx_type: None, } = record.kind { - sends.push((txid, pending.conflicting_txids().to_vec())); + sends.push((txid, pending.conflicting_txids.clone())); } } sends @@ -804,7 +804,7 @@ impl Wallet { // An entry whose transaction wallet sync has yet to observe doesn't have a // payment record yet, so it cannot graduate. let tracked_payments: Vec = - self.payment_stores.tracked_payments(|p| p.txid().is_some()).await; + self.payment_stores.tracked_payments(|p| p.txid.is_some()).await; let mut unconfirmed_outbound_txids: Vec = Vec::new(); let mut unclassified_transactions: Vec<(PaymentId, Txid)> = Vec::new(); @@ -1331,9 +1331,9 @@ impl Wallet { async fn tracked_txids(&self) -> HashSet { let mut txids = HashSet::new(); for entry in self.payment_stores.tracked_payments(|_| true).await { - txids.extend(entry.txid()); + txids.extend(entry.txid); txids.extend(entry.candidates().iter().map(|candidate| candidate.txid)); - txids.extend(entry.conflicting_txids().iter().copied()); + txids.extend(entry.conflicting_txids.iter().copied()); txids.extend(entry.locked_rounds().iter().copied()); } txids @@ -1409,7 +1409,7 @@ impl Wallet { } => record.id, _ => return Ok(false), }; - if payment.conflicting_txids().is_empty() { + if payment.conflicting_txids.is_empty() { return Ok(false); } @@ -1630,7 +1630,7 @@ impl Wallet { }; let entries = stores.tracked_payments(|entry| tracks_channel(entry, channel_id)).await; for entry in entries { - let details = match entry.txid() { + let details = match entry.txid { Some(_) => match stores.payment(&entry.id()).await? { Some(details) => details, None => { @@ -1881,10 +1881,7 @@ impl Wallet { stores .mutate_tracked_payment(&payment_id, |existing| { let mut entry = existing?.clone(); - if !entry.record_locked_round(txid) { - return None; - } - Some(entry) + entry.record_locked_round(txid).then_some(entry) }) .await?; log_info!( @@ -3278,7 +3275,7 @@ impl Wallet { changed = true; } if entry.candidates() != recorded.as_slice() { - entry.set_candidates(recorded.clone()); + entry.funding.get_or_insert_with(Default::default).rounds = recorded.clone(); changed = true; } changed.then_some(entry) @@ -3445,7 +3442,7 @@ impl Wallet { // splice — has no record to hand back or remove: only its history shrinks, and with // the last round of ours it loses the rest of the history too. An entry left tracking // nothing goes. - if entry.txid().is_none() { + if entry.txid.is_none() { if handed_back.is_none() { self.withdraw_unshared_attributions(&entry, payment_id).await?; } @@ -3561,7 +3558,7 @@ impl Wallet { // With its history gone, the entry tracks the channels of the record's own // classification, if any. if handed_back.is_none() { - let funding = entry.funding_mut(); + let funding = entry.funding.get_or_insert_with(Default::default); funding.rounds.clear(); funding.channels = record_channels; } else { @@ -3653,33 +3650,6 @@ impl Wallet { Ok(()) } - /// Records a funding payment the way the node does: the rounds this node signed supply the - /// candidate history, wallet sync writes the payment record and its tracker entry once - /// it observes the transaction, and the duplicates sync created for those rounds are merged - /// into the record. Composes that sequence for tests that need a recorded funding payment to - /// act on. - #[cfg(test)] - async fn record_funding_payment( - &self, details: PaymentDetails, candidates: Vec, - ) -> Result<(), Error> { - let stores = self.payment_stores.lock().await; - let id = details.id; - if !candidates.is_empty() { - stores - .mutate_tracked_payment(&id, |existing| { - let mut entry = existing.cloned().unwrap_or_else(|| { - TrackedOnchainPayment::signed_rounds(id, Vec::new(), Vec::new()) - }); - entry.set_candidates(candidates.clone()); - Some(entry) - }) - .await?; - } - stores.insert_or_update_payment(details.clone()).await?; - self.upsert_tracked_payment(&stores, details, Vec::new()).await?; - self.merge_duplicate_candidate_records(&stores, id, &candidates).await - } - /// Merges duplicate records wallet sync created for this funding payment's candidates before /// they were recorded as such. Sync re-keys an event for a round it cannot attribute to the /// funding record — not yet a candidate, so the funding-status gate reports it foreign — to @@ -3965,7 +3935,7 @@ impl Wallet { } let owns = |p: &TrackedOnchainPayment| { - p.txid() == Some(target_txid) + p.txid == Some(target_txid) // A middle RBF round is not the record's current txid and may never have // received a `TxReplaced` event of its own, so map any of its candidate txids // (an earlier RBF round may confirm) back to the record. @@ -3973,7 +3943,7 @@ impl Wallet { }; let mut matches = self .payment_stores - .tracked_payments(|p| owns(p) || p.conflicting_txids().contains(&target_txid)) + .tracked_payments(|p| owns(p) || p.conflicting_txids.contains(&target_txid)) .await; // An entry lists the transactions that replaced its own, so a transaction another entry // records as its own (a splice round that replaced a close, say) matches both. The entry @@ -5390,17 +5360,33 @@ mod tests { async fn track_pending(wallet: &Wallet, details: PaymentDetails, conflicting_txids: Vec) { let stores = wallet.payment_stores.lock().await; stores.insert_or_update_payment(details.clone()).await.unwrap(); - let tracked = entry_for(&details, Vec::new()); - stores - .payment_tracker() - .mutate(&details.id, |existing| { - let mut entry = existing.cloned().unwrap_or(tracked); - entry.merge_observed(onchain_txid(&details), conflicting_txids); - entry.track_funding_channels(&details_channels(&details)); - Some(entry) - }) - .await - .unwrap(); + wallet.upsert_tracked_payment(&stores, details, conflicting_txids).await.unwrap(); + } + + /// Records a funding payment the way the node does: the rounds this node signed supply the + /// candidate history, wallet sync writes the payment record and its tracker entry once + /// it observes the transaction, and the duplicates sync created for those rounds are merged + /// into the record. Composes that sequence for tests that need a recorded funding payment to + /// act on. + async fn record_funding_payment( + wallet: &Wallet, details: PaymentDetails, candidates: Vec, + ) -> Result<(), Error> { + let stores = wallet.payment_stores.lock().await; + let id = details.id; + if !candidates.is_empty() { + stores + .mutate_tracked_payment(&id, |existing| { + let mut entry = existing.cloned().unwrap_or_else(|| { + TrackedOnchainPayment::signed_rounds(id, Vec::new(), Vec::new()) + }); + entry.funding.get_or_insert_with(Default::default).rounds = candidates.clone(); + Some(entry) + }) + .await?; + } + stores.insert_or_update_payment(details.clone()).await?; + wallet.upsert_tracked_payment(&stores, details, Vec::new()).await?; + wallet.merge_duplicate_candidate_records(&stores, id, &candidates).await } /// The transaction of the on-chain payment `details`. @@ -5443,7 +5429,7 @@ mod tests { .payment_tracker() .mutate(&id, |existing| { let mut entry = existing?.clone(); - let current_txid = entry.txid(); + let current_txid = entry.txid; let mut conflicting_txids = conflicting_txids; conflicting_txids.retain(|txid| Some(*txid) != current_txid); (entry.conflicting_txids != conflicting_txids).then(|| { @@ -6621,7 +6607,7 @@ mod tests { .unwrap() .expect("the round identifies its payment"); let entry = entry_of(&wallet, &id).await.expect("entry"); - assert!(entry.txid().is_none()); + assert!(entry.txid.is_none()); assert!(entry.candidate(txid).expect("candidate").awaiting_broadcast); assert_eq!( entry.funding_channels(), @@ -6923,7 +6909,7 @@ mod tests { assert_eq!(payments[0].amount_msat, Some(500_300_000)); assert_eq!(payments[0].fee_paid_msat, Some(300_000)); let entry = entry_of(&wallet, &id).await.expect("entry"); - assert_eq!(entry.txid(), Some(onchain_txid(&payments[0]))); + assert_eq!(entry.txid, Some(onchain_txid(&payments[0]))); assert!(entry.candidate(txid).expect("candidate").awaiting_broadcast); } @@ -7186,7 +7172,7 @@ mod tests { assert_eq!(payment.status, PaymentStatus::Pending); assert!(matches!(payment.kind, PaymentKind::Onchain { txid: t, .. } if t == bump_txid)); let entry = entry_of(&wallet, &bump_id).await.expect("entry"); - assert_eq!(entry.txid(), Some(onchain_txid(&payment))); + assert_eq!(entry.txid, Some(onchain_txid(&payment))); assert!(entry.candidate(bump_txid).expect("candidate").awaiting_broadcast); let failed = record_of(&wallet, &failed_id).await.expect("the failed record stays"); assert_eq!(failed.status, PaymentStatus::Failed); @@ -7605,7 +7591,7 @@ mod tests { ); assert_eq!(payment.amount_msat, Some(500_300_000)); assert_eq!(payment.fee_paid_msat, Some(300_000)); - assert_eq!(record.txid(), Some(onchain_txid(&payment))); + assert_eq!(record.txid, Some(onchain_txid(&payment))); assert_eq!(wallet.find_payment_by_txid(txid).await.unwrap(), Some(id)); } @@ -8042,7 +8028,7 @@ mod tests { assert_eq!(record_of(&wallet, &id).await, Some(payment.clone())); let record = entry_of(&wallet, &id).await.expect("record"); assert_eq!(record.candidates().iter().map(|c| c.txid).collect::>(), vec![txid]); - assert_eq!(record.txid(), Some(onchain_txid(&payment))); + assert_eq!(record.txid, Some(onchain_txid(&payment))); assert!(record.candidate(bump_txid).is_none()); } @@ -8076,7 +8062,7 @@ mod tests { assert_eq!(record_of(&wallet, &id).await, Some(payment.clone())); let record = entry_of(&wallet, &id).await.expect("record"); assert!(record.candidates().is_empty()); - assert_eq!(record.txid(), Some(onchain_txid(&payment))); + assert_eq!(record.txid, Some(onchain_txid(&payment))); } /// A removal that was cut short between the two stores — the payment record went, the pending @@ -8140,7 +8126,7 @@ mod tests { update.fee_paid_msat = Some(Some(300_000)); wallet.payment_stores.payment_store().update(update).await.unwrap(); let entry = entry_of(&wallet, &id).await.expect("entry"); - assert_eq!(entry.txid(), Some(bump_txid)); + assert_eq!(entry.txid, Some(bump_txid)); wallet.drop_abandoned_splice_rounds(channel_id, &[txid]).await.unwrap(); @@ -8149,7 +8135,7 @@ mod tests { let payment = record_of(&wallet, &id).await.expect("payment"); assert!(matches!(payment.kind, PaymentKind::Onchain { txid: t, .. } if t == txid)); assert_eq!(payment.amount_msat, Some(500_300_000)); - assert_eq!(entry.txid(), Some(onchain_txid(&payment))); + assert_eq!(entry.txid, Some(onchain_txid(&payment))); assert!(entry.candidate(bump_txid).is_none()); } @@ -8305,7 +8291,7 @@ mod tests { assert!(matches!(payment.kind, PaymentKind::Onchain { txid: t, .. } if t == bump_txid)); let entry = entry_of(&wallet, &id).await.expect("entry"); assert_eq!(entry.candidates().iter().map(|c| c.txid).collect::>(), vec![txid]); - assert_eq!(entry.txid(), Some(bump_txid)); + assert_eq!(entry.txid, Some(bump_txid)); } /// The signing write fails at the payment tracker: no payment record is minted for a round @@ -8772,7 +8758,7 @@ mod tests { ]; let details = interactive_funding_details(payment_id, txid3, Some(1_000_000), Some(700)); let mut entry = entry_for(&details, Vec::new()); - entry.set_candidates(candidates); + entry.funding.get_or_insert_with(Default::default).rounds = candidates; insert_entry(&wallet, entry).await; // The first candidate resolves via the txid-derived id and the active candidate via the @@ -8968,7 +8954,7 @@ mod tests { }]; let details = interactive_funding_details(payment_id, splice_txid, Some(1_000_000), Some(500)); - wallet.record_funding_payment(details, candidates).await.unwrap(); + record_funding_payment(&wallet, details, candidates).await.unwrap(); // Sync saw the close double-spend the splice's funding transaction. set_conflicts(&wallet, payment_id, vec![close_txid]).await; @@ -9063,7 +9049,7 @@ mod tests { }]; let details = interactive_funding_details(payment_id, splice_txid, Some(1_000_000), Some(500)); - wallet.record_funding_payment(details, candidates).await.unwrap(); + record_funding_payment(&wallet, details, candidates).await.unwrap(); // Each close was recorded at broadcast, seen unconfirmed, then replaced by the round: // what the `TxReplaced` arm leaves behind. @@ -9163,7 +9149,7 @@ mod tests { }]; let details = interactive_funding_details(payment_id, splice_txid, Some(1_000_000), Some(500)); - wallet.record_funding_payment(details, candidates).await.unwrap(); + record_funding_payment(&wallet, details, candidates).await.unwrap(); set_conflicts(&wallet, payment_id, vec![close_txid]).await; // The round was seen in the mempool; the close is canonically confirmed, so the round, @@ -9232,7 +9218,7 @@ mod tests { ]; let details = interactive_funding_details(payment_id, second_txid, Some(1_000_000), Some(600)); - wallet.record_funding_payment(details, candidates).await.unwrap(); + record_funding_payment(&wallet, details, candidates).await.unwrap(); // A close double-spends the first round's input and confirms through the anti-reorg // depth, while the second round merely drops out of the mempool. @@ -9306,7 +9292,7 @@ mod tests { ]; let details = interactive_funding_details(payment_id, second_txid, Some(1_000_000), Some(600)); - wallet.record_funding_payment(details, candidates).await.unwrap(); + record_funding_payment(&wallet, details, candidates).await.unwrap(); // A close double-spends the input only the second round added and confirms through the // anti-reorg depth. @@ -9374,7 +9360,7 @@ mod tests { ]; let details = interactive_funding_details(payment_id, second_txid, Some(1_000_000), Some(600)); - wallet.record_funding_payment(details, candidates).await.unwrap(); + record_funding_payment(&wallet, details, candidates).await.unwrap(); let close_tx = wallet_paying_tx(&wallet, 2); let close_txid = close_tx.compute_txid(); @@ -9421,7 +9407,7 @@ mod tests { "the round is not recorded a second time" ); let entry = entry_of(&wallet, &payment_id).await.unwrap(); - assert_eq!(entry.txid(), Some(first_txid), "the entry tracks the round that confirmed"); + assert_eq!(entry.txid, Some(first_txid), "the entry tracks the round that confirmed"); } /// A confirmed conflict that is one of the record's own candidates is RBF resolution, not a @@ -9453,7 +9439,7 @@ mod tests { ]; let details = interactive_funding_details(payment_id, splice_txid, Some(1_000_000), Some(500)); - wallet.record_funding_payment(details, candidates).await.unwrap(); + record_funding_payment(&wallet, details, candidates).await.unwrap(); set_conflicts(&wallet, payment_id, vec![bumped_txid]).await; insert_confirmed_tx(&wallet, bumped_tx, 5); @@ -9495,7 +9481,7 @@ mod tests { }]; let details = interactive_funding_details(payment_id, splice_txid, Some(1_000_000), Some(500)); - wallet.record_funding_payment(details, candidates).await.unwrap(); + record_funding_payment(&wallet, details, candidates).await.unwrap(); set_conflicts(&wallet, payment_id, vec![close_txid]).await; insert_confirmed_tx(&wallet, close_tx, 5); @@ -9545,7 +9531,7 @@ mod tests { ]; let details = interactive_funding_details(payment_id, splice_txid, Some(1_000_000), Some(500)); - wallet.record_funding_payment(details, candidates).await.unwrap(); + record_funding_payment(&wallet, details, candidates).await.unwrap(); set_conflicts(&wallet, payment_id, vec![conflict_txid]).await; insert_confirmed_tx(&wallet, conflict_tx, 5); @@ -9597,7 +9583,7 @@ mod tests { awaiting_broadcast: false, }]; let mut entry = entry_for(&snapshot, vec![close_txid]); - entry.set_candidates(candidates); + entry.funding.get_or_insert_with(Default::default).rounds = candidates; insert_entry(&wallet, entry).await; insert_confirmed_tx(&wallet, close_tx, 5); @@ -9649,7 +9635,7 @@ mod tests { awaiting_broadcast: false, }]; let mut entry = entry_for(&snapshot, vec![close_txid]); - entry.set_candidates(candidates); + entry.funding.get_or_insert_with(Default::default).rounds = candidates; insert_entry(&wallet, entry).await; insert_confirmed_tx(&wallet, close_tx, 5); @@ -9894,7 +9880,7 @@ mod tests { let mut details = interactive_funding_details(payment_id, splice_txid, Some(1_000_000), Some(500)); details.direction = PaymentDirection::Inbound; - wallet.record_funding_payment(details, candidates).await.unwrap(); + record_funding_payment(&wallet, details, candidates).await.unwrap(); set_conflicts(&wallet, payment_id, vec![close_txid]).await; insert_unconfirmed_tx(&wallet, splice_tx); @@ -9937,7 +9923,7 @@ mod tests { awaiting_broadcast: false, }]; let details = interactive_funding_details(funding_id, txid1, Some(1_000_000), Some(500)); - wallet.record_funding_payment(details, round1).await.unwrap(); + record_funding_payment(&wallet, details, round1).await.unwrap(); // Wallet sync recorded round 2's confirmation while the round was not yet a candidate: a // duplicate untyped record under the txid-derived id, plus its pending entry. @@ -9969,7 +9955,7 @@ mod tests { }, ]; let details = interactive_funding_details(funding_id, txid2, Some(1_000_000), Some(400)); - wallet.record_funding_payment(details, rounds).await.unwrap(); + record_funding_payment(&wallet, details, rounds).await.unwrap(); // One record: the funding record carries the duplicate's confirmation and the confirmed // candidate's figures; the duplicate and its pending entry are gone, so the round's txid @@ -10036,7 +10022,7 @@ mod tests { }, ]; let details = interactive_funding_details(funding_id, txid2, Some(1_000_000), Some(400)); - wallet.record_funding_payment(details, rounds).await.unwrap(); + record_funding_payment(&wallet, details, rounds).await.unwrap(); let payments = wallet.payment_stores.payment_store().list_page(None).await.unwrap().objects; assert_eq!(payments.len(), 1, "the duplicate must be merged away"); @@ -10103,7 +10089,7 @@ mod tests { }, ]; let details = interactive_funding_details(funding_id, txid2, Some(1_000_000), Some(400)); - wallet.record_funding_payment(details, rounds).await.unwrap(); + record_funding_payment(&wallet, details, rounds).await.unwrap(); let failed = record_of(&wallet, &duplicate_id).await.expect("the failed record stays"); assert_eq!(failed.status, PaymentStatus::Failed); @@ -10137,7 +10123,7 @@ mod tests { awaiting_broadcast: false, }]; let details = interactive_funding_details(funding_id, txid1, Some(1_000_000), Some(500)); - wallet.record_funding_payment(details, round1).await.unwrap(); + record_funding_payment(&wallet, details, round1).await.unwrap(); // Wallet sync recorded round 2's confirmation while the round was not yet a candidate. let duplicate_id = PaymentId(txid2.to_byte_array()); @@ -10168,11 +10154,11 @@ mod tests { ]; let details = interactive_funding_details(funding_id, txid2, Some(1_000_000), Some(400)); fail_store.fail_next_remove_in(ONCHAIN_PAYMENT_TRACKER_PERSISTENCE_PRIMARY_NAMESPACE); - let res = wallet.record_funding_payment(details.clone(), rounds.clone()).await; + let res = record_funding_payment(&wallet, details.clone(), rounds.clone()).await; assert!(res.is_err(), "the injected remove failure must surface"); // The merge re-runs with the record's next write; it must finish the cleanup. - wallet.record_funding_payment(details, rounds).await.unwrap(); + record_funding_payment(&wallet, details, rounds).await.unwrap(); let payments = wallet.payment_stores.payment_store().list_page(None).await.unwrap().objects; assert_eq!(payments.len(), 1, "the duplicate must be merged away"); @@ -10267,7 +10253,7 @@ mod tests { assert_eq!(payment.fee_paid_msat, fee_paid_msat); assert_eq!(payment.direction, direction); let entry = entry_of(&wallet, &id).await.expect("entry"); - assert_eq!(entry.txid(), Some(onchain_txid(payment))); + assert_eq!(entry.txid, Some(onchain_txid(payment))); assert!(entry_of(&wallet, &duplicate_id).await.is_none()); assert_eq!(wallet.find_payment_by_txid(counterparty_txid).await.unwrap(), Some(id)); } @@ -10358,7 +10344,7 @@ mod tests { payments[0].kind ); let entry = entry_of(&wallet, &id).await.expect("entry"); - assert_eq!(entry.txid(), Some(onchain_txid(&payments[0]))); + assert_eq!(entry.txid, Some(onchain_txid(&payments[0]))); assert!(record_of(&wallet, &duplicate_id).await.is_none()); } @@ -10562,7 +10548,7 @@ mod tests { // still describes that round, and the entry still tracks it. let payment = record_of(&wallet, &id).await.expect("payment"); assert!(matches!(payment.kind, PaymentKind::Onchain { txid: t, .. } if t == txid)); - assert_eq!(entry.txid(), Some(onchain_txid(&payment))); + assert_eq!(entry.txid, Some(onchain_txid(&payment))); assert_eq!(record_of(&wallet, &duplicate_id).await, Some(duplicate)); assert!(entry_of(&wallet, &duplicate_id).await.is_some()); @@ -10734,7 +10720,7 @@ mod tests { wallet.merge_duplicate_candidate_records(&guard, id, &rounds).await.unwrap(); } let entry = entry_of(&wallet, &id).await.expect("entry"); - assert_eq!(entry.txid(), Some(onchain_txid(&payment))); + assert_eq!(entry.txid, Some(onchain_txid(&payment))); let payments = wallet.payment_stores.payment_store().list_page(None).await.unwrap().objects; assert_eq!(payments.len(), 1, "the duplicate must be merged away"); assert_eq!(payments[0].id, id); @@ -10967,7 +10953,7 @@ mod tests { "the round can still confirm, so nothing is failed", ); let entry = entry_of(&wallet, &id).await.expect("the entry stays"); - assert!(entry.txid().is_none()); + assert!(entry.txid.is_none()); assert!(entry.candidate(txid).is_some()); } @@ -10992,7 +10978,7 @@ mod tests { "the locked round can still confirm, so nothing is failed", ); let entry = entry_of(&wallet, &id).await.expect("the entry stays"); - assert!(entry.txid().is_none()); + assert!(entry.txid.is_none()); assert!(entry.candidate(txid).is_some()); assert_eq!(entry.locked_rounds(), &[txid]); } @@ -11027,7 +11013,7 @@ mod tests { wallet.record_signed_funding(&tx, &candidates).await.unwrap(); let id = wallet.find_payment_by_txid(txid).await.unwrap().expect("recorded"); let entry = entry_of(&wallet, &id).await.expect("the entry"); - assert!(entry.txid().is_none()); + assert!(entry.txid.is_none()); assert!(entry.candidate(external_txid).is_some_and(|round| round.amount_msat.is_some())); (external_txid, id) } @@ -12715,12 +12701,12 @@ mod tests { &funding_payment(id, Txid::from_byte_array([45u8; 32]), PaymentStatus::Pending), Vec::new(), ); - entry.set_candidates(vec![FundingTxCandidate { + entry.funding.get_or_insert_with(Default::default).rounds = vec![FundingTxCandidate { txid: funding_txid, amount_msat: Some(1_000), fee_paid_msat: Some(10), awaiting_broadcast: false, - }]); + }]; wallet.payment_stores.payment_tracker().insert(entry).await.unwrap(); chain_tip_changed(&wallet, LONG_AFTER).await; @@ -13210,7 +13196,7 @@ mod tests { assert!(is_in_wallet_view(&wallet, bump_txid)); assert!(!is_in_wallet_view(&wallet, original_txid)); let entry = wallet.payment_stores.tracked_payment(&payment_id).await.unwrap().unwrap(); - assert_eq!(entry.txid(), Some(onchain_txid(&payment))); + assert_eq!(entry.txid, Some(onchain_txid(&payment))); } /// A fee bump cannot return over the transaction it replaced once that one confirmed, and diff --git a/src/wallet/payment_tracker.rs b/src/wallet/payment_tracker.rs index 1cb8817a08..4602dae3b0 100644 --- a/src/wallet/payment_tracker.rs +++ b/src/wallet/payment_tracker.rs @@ -112,22 +112,6 @@ impl TrackedOnchainPayment { Self { id, txid: None, conflicting_txids: Vec::new(), funding: Some(funding) } } - /// The payment record's current transaction, or `None` for a splice whose transaction has not - /// been observed. - pub(crate) fn txid(&self) -> Option { - self.txid - } - - /// Transaction IDs that have replaced or conflict with this payment. - pub(crate) fn conflicting_txids(&self) -> &[Txid] { - &self.conflicting_txids - } - - /// The interactive-funding state, created empty if the entry has none yet. - pub(crate) fn funding_mut(&mut self) -> &mut FundingRounds { - self.funding.get_or_insert_with(FundingRounds::default) - } - /// The rounds LDK promoted to the channel's funding, as `ChannelReady` reported them. pub(crate) fn locked_rounds(&self) -> &[Txid] { self.funding.as_ref().map_or(&[], |funding| &funding.locked) @@ -139,7 +123,7 @@ impl TrackedOnchainPayment { if self.locked_rounds().contains(&txid) { return false; } - self.funding_mut().locked.push(txid); + self.funding.get_or_insert_with(FundingRounds::default).locked.push(txid); true } @@ -154,11 +138,6 @@ impl TrackedOnchainPayment { self.funding.as_ref().map_or(&[], |funding| &funding.rounds) } - /// Replaces the recorded candidate history. - pub(crate) fn set_candidates(&mut self, candidates: Vec) { - self.funding_mut().rounds = candidates; - } - /// Drops the candidates with the given txids from the recorded history. pub(crate) fn drop_candidates(&mut self, txids: &[Txid]) { if let Some(funding) = self.funding.as_mut() { @@ -177,7 +156,7 @@ impl TrackedOnchainPayment { if !self.funding_channels().is_empty() || channels.is_empty() { return false; } - self.funding_mut().channels = channels.to_vec(); + self.funding.get_or_insert_with(FundingRounds::default).channels = channels.to_vec(); true } @@ -266,7 +245,7 @@ mod tests { let mut pending = TrackedOnchainPayment::new(payment_id, rbf_txid, vec![first_txid, counterparty_txid]); - pending.set_candidates(candidates); + pending.funding.get_or_insert_with(Default::default).rounds = candidates; // Each candidate resolves to its own figures, so a non-last candidate that confirms reports // its own (lower) fee rather than the last-broadcast candidate's. @@ -294,9 +273,9 @@ mod tests { TrackedOnchainPayment::new(payment_id, replacement_txid, vec![original_txid]); assert!(pending_payment.merge_observed(original_txid, Vec::new())); - assert_eq!(pending_payment.txid(), Some(original_txid)); + assert_eq!(pending_payment.txid, Some(original_txid)); assert_eq!( - pending_payment.conflicting_txids(), + pending_payment.conflicting_txids, Vec::::new(), "current txid must not remain in its own conflict list" ); @@ -321,18 +300,18 @@ mod tests { let txid = Txid::from_byte_array([8u8; 32]); let mut record = TrackedOnchainPayment::new(payment_id, txid, vec![Txid::from_byte_array([9u8; 32])]); - record.set_candidates(vec![FundingTxCandidate { + record.funding.get_or_insert_with(Default::default).rounds = vec![FundingTxCandidate { txid, amount_msat: Some(1_000), fee_paid_msat: Some(100), awaiting_broadcast: false, - }]); + }]; let encoded = record.encode(); let decoded = TrackedOnchainPayment::read(&mut &encoded[..]).unwrap(); assert_eq!(record, decoded); assert_eq!(decoded.id(), payment_id); - assert_eq!(decoded.txid(), Some(txid)); + assert_eq!(decoded.txid, Some(txid)); // The rounds of a splice signed before any transaction was observed. let signed = TrackedOnchainPayment::signed_rounds( @@ -342,7 +321,7 @@ mod tests { ); let decoded = TrackedOnchainPayment::read(&mut &signed.encode()[..]).unwrap(); assert_eq!(decoded, signed); - assert_eq!(decoded.txid(), None); + assert_eq!(decoded.txid, None); } /// A candidate with the given txid byte, with a stake of ours in it if `ours`. @@ -359,7 +338,7 @@ mod tests { let payment_id = PaymentId([1u8; 32]); let txid = candidates.last().expect("at least one candidate").txid; let mut entry = TrackedOnchainPayment::new(payment_id, txid, vec![]); - entry.set_candidates(candidates); + entry.funding.get_or_insert_with(Default::default).rounds = candidates; entry } From 3d522b8bd9a850ddf78793c86e690ee21075c7bf Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Mon, 23 Nov 2026 10:25:09 +0100 Subject: [PATCH 11/11] Test tracking of a record's funding channels Lookups by channel find a tracker entry only through the channels it lists. Nothing tested that these are copied from the record when wallet sync first observes a classified funding, or kept when dropping the last round of ours clears the history of an already classified record. Cover both cases, so that losing the channels in either place fails a test. Clearing them for an unclassified record was covered already. Written with the help of an AI tool. Co-Authored-By: HAL 9000 --- src/wallet/mod.rs | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/wallet/mod.rs b/src/wallet/mod.rs index 44e1fe1ea2..0dbe6c450e 100644 --- a/src/wallet/mod.rs +++ b/src/wallet/mod.rs @@ -7801,6 +7801,11 @@ mod tests { wallet.drop_abandoned_splice_rounds(channel_id, &[counterparty_txid]).await.unwrap(); + let entry = entry_of(&wallet, &id).await.expect("entry"); + assert!(entry.candidates().is_empty()); + assert_eq!(entry.funding_channels(), &details_channels(&observed)); + assert!(tracks_channel(&entry, channel_id)); + insert_confirmed_tx(&wallet, counterparty_tx.clone(), 100); let event = WalletEvent::TxConfirmed { txid: counterparty_txid, @@ -8601,6 +8606,33 @@ mod tests { assert!(entry_of(&wallet, &id).await.is_some(), "a reorged-out payment is tracked again"); } + /// A transaction already known to be an interactive funding when wallet sync first sees it gets + /// an entry tracking the funding's channels. + #[tokio::test] + async fn observing_a_classified_funding_tracks_the_channels() { + let store: Arc = Arc::new(DynStoreWrapper(InMemoryStore::new())); + let wallet = new_test_wallet(Arc::clone(&store), false).await; + let (counterparty_node_id, channel_id) = test_counterparty_and_channel(); + let channel = Channel { counterparty_node_id, channel_id }; + + let (tx, _) = splice_out_round(&wallet, 1, 500_000, 300); + let txid = tx.compute_txid(); + wallet + .record_channel_tx_facts(ChannelTxFacts::new(txid).with_self_role( + TransactionType::InteractiveFunding { channels: vec![channel.clone()] }, + )) + .await + .unwrap(); + observe_unconfirmed(&wallet, &tx).await; + + let id = PaymentId(txid.to_byte_array()); + let record = record_of(&wallet, &id).await.expect("record"); + assert_eq!(details_channels(&record), vec![channel.clone()]); + let entry = entry_of(&wallet, &id).await.expect("entry"); + assert_eq!(entry.funding_channels(), &[channel]); + assert!(tracks_channel(&entry, channel_id)); + } + /// A record the chain-tip pass classifies as an interactive funding gets its entry tracking the /// funding's channels, and its transaction is no longer one of this node's plain sends for the /// wallet to return to its view.