Skip to content

Commit f065431

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 6174430 commit f065431

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};
@@ -440,6 +440,29 @@ impl PaymentDetailsUpdate {
440440
}
441441
}
442442

443+
impl From<&PaymentDetails> for PaymentDetailsUpdate {
444+
fn from(value: &PaymentDetails) -> Self {
445+
let (hash, preimage, secret) = match value.kind {
446+
PaymentKind::Bolt11 { hash, preimage, secret, .. } => (Some(hash), preimage, secret),
447+
PaymentKind::Bolt11Jit { hash, preimage, secret, .. } => (Some(hash), preimage, secret),
448+
PaymentKind::Bolt12Offer { hash, preimage, secret, .. } => (hash, preimage, secret),
449+
PaymentKind::Bolt12Refund { hash, preimage, secret, .. } => (hash, preimage, secret),
450+
PaymentKind::Spontaneous { hash, preimage, .. } => (Some(hash), preimage, None),
451+
_ => (None, None, None),
452+
};
453+
454+
Self {
455+
id: value.id,
456+
hash: Some(hash),
457+
preimage: Some(preimage),
458+
secret: Some(secret),
459+
amount_msat: Some(value.amount_msat),
460+
direction: Some(value.direction),
461+
status: Some(value.status),
462+
}
463+
}
464+
}
465+
443466
pub(crate) struct PaymentStore<L: Deref>
444467
where
445468
L::Target: Logger,
@@ -468,6 +491,28 @@ where
468491
Ok(updated)
469492
}
470493

494+
pub(crate) fn insert_or_update(&self, payment: &PaymentDetails) -> Result<bool, Error> {
495+
let mut locked_payments = self.payments.lock().unwrap();
496+
497+
let updated;
498+
match locked_payments.entry(payment.id) {
499+
hash_map::Entry::Occupied(mut e) => {
500+
let update = payment.into();
501+
updated = e.get_mut().update(&update);
502+
if updated {
503+
self.persist_info(&payment.id, e.get())?;
504+
}
505+
},
506+
hash_map::Entry::Vacant(e) => {
507+
e.insert(payment.clone());
508+
self.persist_info(&payment.id, payment)?;
509+
updated = true;
510+
},
511+
}
512+
513+
Ok(updated)
514+
}
515+
471516
pub(crate) fn remove(&self, id: &PaymentId) -> Result<(), Error> {
472517
let store_key = hex_utils::to_string(&id.0);
473518
self.kv_store

0 commit comments

Comments
 (0)