Skip to content

Commit c9ddfae

Browse files
committed
Prefactor: Implement PaymentStore::insert_or_update
We implement an inserting/updating method that will only persist entries that have been changed.
1 parent d92a568 commit c9ddfae

File tree

1 file changed

+46
-1
lines changed

1 file changed

+46
-1
lines changed

src/payment/store.rs

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,8 @@ use lightning::{
2525

2626
use lightning_types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
2727

28+
use std::collections::hash_map;
2829
use std::collections::HashMap;
29-
use std::iter::FromIterator;
3030
use std::ops::Deref;
3131
use std::sync::{Arc, Mutex};
3232
use std::time::{Duration, SystemTime, UNIX_EPOCH};
@@ -448,6 +448,29 @@ impl PaymentDetailsUpdate {
448448
}
449449
}
450450

451+
impl From<&PaymentDetails> for PaymentDetailsUpdate {
452+
fn from(value: &PaymentDetails) -> Self {
453+
let (hash, preimage, secret) = match value.kind {
454+
PaymentKind::Bolt11 { hash, preimage, secret, .. } => (Some(hash), preimage, secret),
455+
PaymentKind::Bolt11Jit { hash, preimage, secret, .. } => (Some(hash), preimage, secret),
456+
PaymentKind::Bolt12Offer { hash, preimage, secret, .. } => (hash, preimage, secret),
457+
PaymentKind::Bolt12Refund { hash, preimage, secret, .. } => (hash, preimage, secret),
458+
PaymentKind::Spontaneous { hash, preimage, .. } => (Some(hash), preimage, None),
459+
_ => (None, None, None),
460+
};
461+
462+
Self {
463+
id: value.id,
464+
hash: Some(hash),
465+
preimage: Some(preimage),
466+
secret: Some(secret),
467+
amount_msat: Some(value.amount_msat),
468+
direction: Some(value.direction),
469+
status: Some(value.status),
470+
}
471+
}
472+
}
473+
451474
pub(crate) struct PaymentStore<L: Deref>
452475
where
453476
L::Target: LdkLogger,
@@ -476,6 +499,28 @@ where
476499
Ok(updated)
477500
}
478501

502+
pub(crate) fn insert_or_update(&self, payment: &PaymentDetails) -> Result<bool, Error> {
503+
let mut locked_payments = self.payments.lock().unwrap();
504+
505+
let updated;
506+
match locked_payments.entry(payment.id) {
507+
hash_map::Entry::Occupied(mut e) => {
508+
let update = payment.into();
509+
updated = e.get_mut().update(&update);
510+
if updated {
511+
self.persist_info(&payment.id, e.get())?;
512+
}
513+
},
514+
hash_map::Entry::Vacant(e) => {
515+
e.insert(payment.clone());
516+
self.persist_info(&payment.id, payment)?;
517+
updated = true;
518+
},
519+
}
520+
521+
Ok(updated)
522+
}
523+
479524
pub(crate) fn remove(&self, id: &PaymentId) -> Result<(), Error> {
480525
let store_key = hex_utils::to_string(&id.0);
481526
self.kv_store

0 commit comments

Comments
 (0)