Skip to content

Commit 374943a

Browse files
committed
Add inital implementation of persisted payment store
1 parent d734ff6 commit 374943a

File tree

5 files changed

+313
-140
lines changed

5 files changed

+313
-140
lines changed

src/event.rs

Lines changed: 50 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use crate::{
2-
hex_utils, ChannelManager, Config, Error, KeysManager, NetworkGraph, PaymentInfo,
3-
PaymentInfoStorage, PaymentStatus, Wallet,
2+
hex_utils, ChannelManager, Config, Error, KeysManager, NetworkGraph, PaymentDirection,
3+
PaymentInfo, PaymentInfoStorage, PaymentStatus, Wallet,
44
};
55

66
use crate::logger::{log_error, log_given_level, log_info, log_internal, Logger};
@@ -17,7 +17,7 @@ use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
1717

1818
use bitcoin::secp256k1::Secp256k1;
1919
use rand::{thread_rng, Rng};
20-
use std::collections::{hash_map, VecDeque};
20+
use std::collections::VecDeque;
2121
use std::ops::Deref;
2222
use std::sync::{Arc, Condvar, Mutex};
2323
use std::time::Duration;
@@ -238,8 +238,7 @@ where
238238
channel_manager: Arc<ChannelManager>,
239239
network_graph: Arc<NetworkGraph>,
240240
keys_manager: Arc<KeysManager>,
241-
inbound_payments: Arc<PaymentInfoStorage>,
242-
outbound_payments: Arc<PaymentInfoStorage>,
241+
payment_store: Arc<PaymentInfoStorage<K>>,
243242
tokio_runtime: Arc<tokio::runtime::Runtime>,
244243
logger: L,
245244
_config: Arc<Config>,
@@ -253,18 +252,16 @@ where
253252
pub fn new(
254253
wallet: Arc<Wallet<bdk::sled::Tree>>, event_queue: Arc<EventQueue<K>>,
255254
channel_manager: Arc<ChannelManager>, network_graph: Arc<NetworkGraph>,
256-
keys_manager: Arc<KeysManager>, inbound_payments: Arc<PaymentInfoStorage>,
257-
outbound_payments: Arc<PaymentInfoStorage>, tokio_runtime: Arc<tokio::runtime::Runtime>,
258-
logger: L, _config: Arc<Config>,
255+
keys_manager: Arc<KeysManager>, payment_store: Arc<PaymentInfoStorage<K>>,
256+
tokio_runtime: Arc<tokio::runtime::Runtime>, logger: L, _config: Arc<Config>,
259257
) -> Self {
260258
Self {
261259
event_queue,
262260
wallet,
263261
channel_manager,
264262
network_graph,
265263
keys_manager,
266-
inbound_payments,
267-
outbound_payments,
264+
payment_store,
268265
logger,
269266
tokio_runtime,
270267
_config,
@@ -373,7 +370,9 @@ where
373370
hex_utils::to_string(&payment_hash.0),
374371
);
375372
self.channel_manager.fail_htlc_backwards(&payment_hash);
376-
self.inbound_payments.lock().unwrap().remove(&payment_hash);
373+
self.payment_store
374+
.set_payment_status(&payment_hash, PaymentStatus::Failed)
375+
.expect("Failed to access payment store");
377376
}
378377
}
379378
LdkEvent::PaymentClaimed {
@@ -394,48 +393,51 @@ where
394393
}
395394
PaymentPurpose::SpontaneousPayment(preimage) => (Some(preimage), None),
396395
};
397-
let mut payments = self.inbound_payments.lock().unwrap();
398-
match payments.entry(payment_hash) {
399-
hash_map::Entry::Occupied(mut e) => {
400-
let payment = e.get_mut();
401-
payment.status = PaymentStatus::Succeeded;
402-
payment.preimage = payment_preimage;
403-
payment.secret = payment_secret;
404-
}
405-
hash_map::Entry::Vacant(e) => {
406-
e.insert(PaymentInfo {
396+
397+
let payment_info =
398+
if let Some(mut payment_info) = self.payment_store.payment(&payment_hash) {
399+
payment_info.status = PaymentStatus::Succeeded;
400+
payment_info.preimage = payment_preimage;
401+
payment_info.secret = payment_secret;
402+
payment_info
403+
} else {
404+
PaymentInfo {
407405
preimage: payment_preimage,
406+
hash: payment_hash,
408407
secret: payment_secret,
409-
status: PaymentStatus::Succeeded,
410408
amount_msat: Some(amount_msat),
411-
});
412-
}
413-
}
409+
direction: PaymentDirection::Inbound,
410+
status: PaymentStatus::Succeeded,
411+
}
412+
};
413+
414+
self.payment_store
415+
.insert_payment(payment_info)
416+
.expect("Failed to access payment store");
414417
self.event_queue
415418
.add_event(Event::PaymentReceived { payment_hash, amount_msat })
416419
.expect("Failed to push to event queue");
417420
}
418421
LdkEvent::PaymentSent { payment_preimage, payment_hash, fee_paid_msat, .. } => {
419-
let mut payments = self.outbound_payments.lock().unwrap();
420-
for (hash, payment) in payments.iter_mut() {
421-
if *hash == payment_hash {
422-
payment.preimage = Some(payment_preimage);
423-
payment.status = PaymentStatus::Succeeded;
424-
log_info!(
425-
self.logger,
426-
"Successfully sent payment of {} msats{} from \
427-
payment hash {:?} with preimage {:?}",
428-
payment.amount_msat.unwrap(),
429-
if let Some(fee) = fee_paid_msat {
430-
format!(" (fee {} msats)", fee)
431-
} else {
432-
"".to_string()
433-
},
434-
hex_utils::to_string(&payment_hash.0),
435-
hex_utils::to_string(&payment_preimage.0)
436-
);
437-
break;
438-
}
422+
if let Some(mut payment_info) = self.payment_store.payment(&payment_hash) {
423+
payment_info.preimage = Some(payment_preimage);
424+
payment_info.status = PaymentStatus::Succeeded;
425+
self.payment_store
426+
.insert_payment(payment_info.clone())
427+
.expect("Failed to access payment store");
428+
log_info!(
429+
self.logger,
430+
"Successfully sent payment of {} msats{} from \
431+
payment hash {:?} with preimage {:?}",
432+
payment_info.amount_msat.unwrap(),
433+
if let Some(fee) = fee_paid_msat {
434+
format!(" (fee {} msat)", fee)
435+
} else {
436+
"".to_string()
437+
},
438+
hex_utils::to_string(&payment_hash.0),
439+
hex_utils::to_string(&payment_preimage.0)
440+
);
439441
}
440442
self.event_queue
441443
.add_event(Event::PaymentSuccessful { payment_hash })
@@ -448,12 +450,9 @@ where
448450
hex_utils::to_string(&payment_hash.0)
449451
);
450452

451-
let mut payments = self.outbound_payments.lock().unwrap();
452-
if payments.contains_key(&payment_hash) {
453-
let payment = payments.get_mut(&payment_hash).unwrap();
454-
assert_eq!(payment.status, PaymentStatus::Pending);
455-
payment.status = PaymentStatus::Failed;
456-
}
453+
self.payment_store
454+
.set_payment_status(&payment_hash, PaymentStatus::Failed)
455+
.expect("Failed to access payment store");
457456
self.event_queue
458457
.add_event(Event::PaymentFailed { payment_hash })
459458
.expect("Failed to push to event queue");

src/io_utils.rs

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1+
use crate::payment_store::{PaymentInfo, PAYMENT_INFO_PERSISTENCE_PREFIX};
12
use crate::{Config, Error, FilesystemLogger, NetworkGraph, Scorer};
23

34
use lightning::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
4-
use lightning::util::ser::ReadableArgs;
5+
use lightning::util::ser::{Readable, ReadableArgs};
56

67
use rand::{thread_rng, RngCore};
78

@@ -61,3 +62,25 @@ pub(crate) fn read_scorer(
6162
}
6263
ProbabilisticScorer::new(params, network_graph, logger)
6364
}
65+
66+
pub(crate) fn read_payment_info(config: &Config) -> Vec<PaymentInfo> {
67+
let ldk_data_dir = format!("{}/ldk", config.storage_dir_path);
68+
let payment_store_path = format!("{}/{}", ldk_data_dir, PAYMENT_INFO_PERSISTENCE_PREFIX);
69+
let mut payments = Vec::new();
70+
71+
if let Ok(res) = fs::read_dir(payment_store_path) {
72+
for entry in res {
73+
if let Ok(entry) = entry {
74+
if entry.path().is_file() {
75+
if let Ok(mut f) = fs::File::open(entry.path()) {
76+
if let Ok(payment_info) = PaymentInfo::read(&mut f) {
77+
payments.push(payment_info);
78+
}
79+
}
80+
}
81+
}
82+
}
83+
}
84+
85+
payments
86+
}

0 commit comments

Comments
 (0)