Skip to content

Commit

Permalink
Add inital implementation of persisted payment store
Browse files Browse the repository at this point in the history
  • Loading branch information
tnull committed Sep 8, 2022
1 parent fdabd21 commit 166dafc
Show file tree
Hide file tree
Showing 4 changed files with 296 additions and 143 deletions.
85 changes: 39 additions & 46 deletions src/event.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
hex, ChannelManager, Error, FilesystemPersister, LdkLiteChainAccess, LdkLiteConfig,
NetworkGraph, PaymentInfo, PaymentInfoStorage, PaymentStatus,
NetworkGraph, PaymentDirection, PaymentInfo, PaymentInfoStorage, PaymentStatus,
};

#[allow(unused_imports)]
Expand Down Expand Up @@ -232,8 +232,7 @@ pub(crate) struct LdkLiteEventHandler {
channel_manager: Arc<ChannelManager>,
network_graph: Arc<NetworkGraph>,
keys_manager: Arc<KeysManager>,
inbound_payments: Arc<PaymentInfoStorage>,
outbound_payments: Arc<PaymentInfoStorage>,
payment_store: Arc<PaymentInfoStorage<FilesystemPersister>>,
logger: Arc<FilesystemLogger>,
_config: Arc<LdkLiteConfig>,
}
Expand All @@ -243,8 +242,8 @@ impl LdkLiteEventHandler {
chain_access: Arc<LdkLiteChainAccess<bdk::sled::Tree>>,
event_queue: Arc<LdkLiteEventQueue<FilesystemPersister>>,
channel_manager: Arc<ChannelManager>, network_graph: Arc<NetworkGraph>,
keys_manager: Arc<KeysManager>, inbound_payments: Arc<PaymentInfoStorage>,
outbound_payments: Arc<PaymentInfoStorage>, logger: Arc<FilesystemLogger>,
keys_manager: Arc<KeysManager>,
payment_store: Arc<PaymentInfoStorage<FilesystemPersister>>, logger: Arc<FilesystemLogger>,
_config: Arc<LdkLiteConfig>,
) -> Self {
Self {
Expand All @@ -253,8 +252,7 @@ impl LdkLiteEventHandler {
channel_manager,
network_graph,
keys_manager,
inbound_payments,
outbound_payments,
payment_store,
logger,
_config,
}
Expand Down Expand Up @@ -339,49 +337,49 @@ impl ldk_events::EventHandler for LdkLiteEventHandler {
(Some(*preimage), None)
}
};
let mut payments = self.inbound_payments.lock().unwrap();
match payments.entry(*payment_hash) {
hash_map::Entry::Occupied(mut e) => {
let payment = e.get_mut();
payment.status = PaymentStatus::Succeeded;
payment.preimage = payment_preimage;
payment.secret = payment_secret;
}
hash_map::Entry::Vacant(e) => {
e.insert(PaymentInfo {

let payment_info =
if let Some(mut payment_info) = self.payment_store.payment(payment_hash) {
payment_info.status = PaymentStatus::Succeeded;
payment_info.preimage = payment_preimage;
payment_info.secret = payment_secret;
payment_info
} else {
PaymentInfo {
preimage: payment_preimage,
hash: *payment_hash,
secret: payment_secret,
status: PaymentStatus::Succeeded,
amount_msat: Some(*amount_msat),
});
}
}
direction: PaymentDirection::Inbound,
status: PaymentStatus::Succeeded,
}
};

self.payment_store.insert_payment(payment_info).unwrap();
}
ldk_events::Event::PaymentSent {
payment_preimage,
payment_hash,
fee_paid_msat,
..
} => {
let mut payments = self.outbound_payments.lock().unwrap();
for (hash, payment) in payments.iter_mut() {
if *hash == *payment_hash {
payment.preimage = Some(*payment_preimage);
payment.status = PaymentStatus::Succeeded;
log_info!(
self.logger,
"Successfully sent payment of {} millisatoshis{} from \
payment hash {:?} with preimage {:?}",
payment.amount_msat.unwrap(),
if let Some(fee) = fee_paid_msat {
format!(" (fee {} msat)", fee)
} else {
"".to_string()
},
hex::to_string(&payment_hash.0),
hex::to_string(&payment_preimage.0)
);
}
if let Some(mut payment_info) = self.payment_store.payment(payment_hash) {
payment_info.preimage = Some(*payment_preimage);
payment_info.status = PaymentStatus::Succeeded;
self.payment_store.insert_payment(payment_info.clone()).unwrap();
log_info!(
self.logger,
"Successfully sent payment of {} millisatoshis{} from \
payment hash {:?} with preimage {:?}",
payment_info.amount_msat.unwrap(),
if let Some(fee) = fee_paid_msat {
format!(" (fee {} msat)", fee)
} else {
"".to_string()
},
hex::to_string(&payment_hash.0),
hex::to_string(&payment_preimage.0)
);
}
self.event_queue
.add_event(LdkLiteEvent::PaymentSuccessful {
Expand All @@ -397,19 +395,14 @@ impl ldk_events::EventHandler for LdkLiteEventHandler {
hex::to_string(&payment_hash.0)
);

let mut payments = self.outbound_payments.lock().unwrap();
if payments.contains_key(&payment_hash) {
let payment = payments.get_mut(&payment_hash).unwrap();
payment.status = PaymentStatus::Failed;
}
self.payment_store.set_payment_status(payment_hash, PaymentStatus::Failed).unwrap();
self.event_queue
.add_event(LdkLiteEvent::PaymentFailed {
payment_hash: *payment_hash,
inner: event.clone(),
})
.unwrap();
}

ldk_events::Event::PaymentPathSuccessful { .. } => {}
ldk_events::Event::PaymentPathFailed { .. } => {}
ldk_events::Event::ProbeSuccessful { .. } => {}
Expand Down
31 changes: 23 additions & 8 deletions src/io.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
use crate::error::LdkLiteError as Error;

use crate::{FilesystemLogger, LdkLiteConfig, NetworkGraph, PeerInfo, Scorer};
use crate::payment_store::{PaymentInfo, PAYMENT_INFO_PERSISTENCE_PREFIX};
use crate::{FilesystemLogger, LdkLiteConfig, NetworkGraph, Scorer};

use lightning::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
use lightning::util::ser::ReadableArgs;

use bitcoin::secp256k1::PublicKey;
use lightning::util::ser::{Readable, ReadableArgs};

use rand::{thread_rng, RngCore};

use std::collections::HashMap;
use std::convert::TryFrom;
use std::fs;
use std::io::{BufRead, BufReader, Write};
use std::net::SocketAddr;
use std::io::{BufReader, Write};
use std::sync::Arc;

pub(crate) fn read_or_generate_seed_file(config: Arc<LdkLiteConfig>) -> Result<[u8; 32], Error> {
Expand Down Expand Up @@ -68,3 +64,22 @@ pub(crate) fn read_scorer(
}
ProbabilisticScorer::new(params, network_graph, logger)
}

pub(crate) fn read_payment_info(config: Arc<LdkLiteConfig>) -> Result<Vec<PaymentInfo>, Error> {
let ldk_data_dir = format!("{}/ldk", &config.storage_dir_path.clone());
let payment_store_path =
format!("{}/{}", ldk_data_dir.clone(), PAYMENT_INFO_PERSISTENCE_PREFIX);
let mut payments = Vec::new();

for entry in fs::read_dir(payment_store_path)? {
let entry = entry?;
if entry.path().is_file() {
let mut f = fs::File::open(entry.path())?;
if let Ok(payment_info) = PaymentInfo::read(&mut f) {
payments.push(payment_info);
}
}
}

Ok(payments)
}
Loading

0 comments on commit 166dafc

Please sign in to comment.