Skip to content

Commit

Permalink
post-review fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
zoedberg committed May 22, 2023
1 parent 7814899 commit 9e0b09b
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 67 deletions.
15 changes: 7 additions & 8 deletions src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::disk;
use crate::disk::{self, INBOUND_PAYMENTS_FNAME, OUTBOUND_PAYMENTS_FNAME};
use crate::hex_utils;
use crate::{
ChannelManager, HTLCStatus, MillisatAmount, NetworkGraph, OnionMessenger, PaymentInfo,
Expand All @@ -16,9 +16,11 @@ use lightning::onion_message::{CustomOnionMessageContents, Destination, OnionMes
use lightning::routing::gossip::NodeId;
use lightning::routing::router::{PaymentParameters, RouteParameters};
use lightning::util::config::{ChannelHandshakeConfig, ChannelHandshakeLimits, UserConfig};
use lightning::util::persist::KVStorePersister;
use lightning::util::ser::{Writeable, Writer};
use lightning_invoice::payment::pay_invoice;
use lightning_invoice::{utils, Currency, Invoice};
use lightning_persister::FilesystemPersister;
use std::env;
use std::io;
use std::io::Write;
Expand Down Expand Up @@ -62,7 +64,7 @@ pub(crate) async fn poll_for_user_input(
keys_manager: Arc<KeysManager>, network_graph: Arc<NetworkGraph>,
onion_messenger: Arc<OnionMessenger>, inbound_payments: Arc<Mutex<PaymentInfoStorage>>,
outbound_payments: Arc<Mutex<PaymentInfoStorage>>, ldk_data_dir: String, network: Network,
logger: Arc<disk::FilesystemLogger>,
logger: Arc<disk::FilesystemLogger>, persister: Arc<FilesystemPersister>,
) {
println!(
"LDK startup successful. Enter \"help\" to view available commands. Press Ctrl-D to quit."
Expand Down Expand Up @@ -158,8 +160,7 @@ pub(crate) async fn poll_for_user_input(

let mut outbound_payments = outbound_payments.lock().unwrap();
send_payment(&*channel_manager, &invoice, &mut outbound_payments);
disk::persist_outbound_payments(ldk_data_dir.clone(), &outbound_payments)
.unwrap();
persister.persist(OUTBOUND_PAYMENTS_FNAME, &*outbound_payments).unwrap();
}
"keysend" => {
let dest_pubkey = match words.next() {
Expand Down Expand Up @@ -197,8 +198,7 @@ pub(crate) async fn poll_for_user_input(
&*keys_manager,
&mut outbound_payments,
);
disk::persist_outbound_payments(ldk_data_dir.clone(), &outbound_payments)
.unwrap();
persister.persist(OUTBOUND_PAYMENTS_FNAME, &*outbound_payments).unwrap();
}
"getinvoice" => {
let amt_str = words.next();
Expand Down Expand Up @@ -235,8 +235,7 @@ pub(crate) async fn poll_for_user_input(
expiry_secs.unwrap(),
Arc::clone(&logger),
);
disk::persist_inbound_payments(ldk_data_dir.clone(), &inbound_payments)
.unwrap();
persister.persist(INBOUND_PAYMENTS_FNAME, &*inbound_payments).unwrap();
}
"connectpeer" => {
let peer_pubkey_and_ip_addr = words.next();
Expand Down
28 changes: 5 additions & 23 deletions src/disk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,18 @@ use bitcoin::Network;
use chrono::Utc;
use lightning::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
use lightning::util::logger::{Logger, Record};
use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
use lightning::util::ser::{Readable, ReadableArgs, Writer};
use std::collections::HashMap;
use std::fs;
use std::fs::File;
use std::io::{BufRead, BufReader, BufWriter};
use std::io::{BufRead, BufReader};
use std::net::SocketAddr;
use std::path::Path;
use std::sync::Arc;

pub(crate) const INBOUND_PAYMENTS_FNAME: &str = "inbound_payments";
pub(crate) const OUTBOUND_PAYMENTS_FNAME: &str = "outbound_payments";

pub(crate) struct FilesystemLogger {
data_dir: String,
}
Expand Down Expand Up @@ -52,27 +55,6 @@ pub(crate) fn persist_channel_peer(path: &Path, peer_info: &str) -> std::io::Res
file.write_all(format!("{}\n", peer_info).as_bytes())
}

pub(crate) fn persist_inbound_payments(
ldk_data_dir: String, inbound_payments: &PaymentInfoStorage,
) -> std::io::Result<()> {
persist_payment_info(Path::new(&format!("{}/inbound_payments", ldk_data_dir)), inbound_payments)
}

pub(crate) fn persist_outbound_payments(
ldk_data_dir: String, outbound_payments: &PaymentInfoStorage,
) -> std::io::Result<()> {
persist_payment_info(
Path::new(&format!("{}/outbound_payments", ldk_data_dir)),
outbound_payments,
)
}

fn persist_payment_info(path: &Path, payment_info: &PaymentInfoStorage) -> std::io::Result<()> {
let mut buf = BufWriter::new(fs::File::create(&path)?);
payment_info.write(&mut buf)?;
buf.into_inner()?.sync_all()
}

pub(crate) fn read_channel_peer_data(
path: &Path,
) -> Result<HashMap<PublicKey, SocketAddr>, std::io::Error> {
Expand Down
59 changes: 23 additions & 36 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use bitcoin::consensus::encode;
use bitcoin::network::constants::Network;
use bitcoin::BlockHash;
use bitcoin_bech32::WitnessProgram;
use disk::{INBOUND_PAYMENTS_FNAME, OUTBOUND_PAYMENTS_FNAME};
use lightning::chain::keysinterface::{
EntropySource, InMemorySigner, KeysManager, SpendableOutputDescriptor,
};
Expand All @@ -33,7 +34,7 @@ use lightning::routing::router::DefaultRouter;
use lightning::util::config::UserConfig;
use lightning::util::persist::KVStorePersister;
use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
use lightning::{chain, impl_writeable_tlv_based};
use lightning::{chain, impl_writeable_tlv_based, impl_writeable_tlv_based_enum};
use lightning_background_processor::{process_events_async, GossipSync};
use lightning_block_sync::init;
use lightning_block_sync::poll;
Expand All @@ -59,28 +60,16 @@ pub(crate) const PENDING_SPENDABLE_OUTPUT_DIR: &'static str = "pending_spendable

#[derive(Copy, Clone)]
pub(crate) enum HTLCStatus {
Pending = 1,
Succeeded = 2,
Failed = 3,
Pending,
Succeeded,
Failed,
}

impl Readable for HTLCStatus {
fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
let val: u8 = Readable::read(r)?;
Ok(match val {
1 => HTLCStatus::Pending,
2 => HTLCStatus::Succeeded,
3 => HTLCStatus::Failed,
_ => panic!("unexpected value for HTLCStatus"),
})
}
}

impl Writeable for HTLCStatus {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), std::io::Error> {
(*self as u8).write(w)
}
}
impl_writeable_tlv_based_enum!(HTLCStatus,
(0, Pending) => {},
(1, Succeeded) => {},
(2, Failed) => {};
);

pub(crate) struct MillisatAmount(Option<u64>);

Expand Down Expand Up @@ -114,10 +103,10 @@ pub(crate) struct PaymentInfo {
}

impl_writeable_tlv_based!(PaymentInfo, {
(0, preimage, option),
(1, secret, option),
(2, status, required),
(3, amt_msat, required),
(0, preimage, required),
(2, secret, required),
(4, status, required),
(6, amt_msat, required),
});

pub(crate) struct PaymentInfoStorage {
Expand Down Expand Up @@ -158,7 +147,7 @@ async fn handle_ldk_events(
network_graph: &NetworkGraph, keys_manager: &KeysManager,
inbound_payments: Arc<Mutex<PaymentInfoStorage>>,
outbound_payments: Arc<Mutex<PaymentInfoStorage>>, persister: &Arc<FilesystemPersister>,
network: Network, event: Event, ldk_data_dir: String,
network: Network, event: Event,
) {
match event {
Event::FundingGenerationReady {
Expand Down Expand Up @@ -263,7 +252,7 @@ async fn handle_ldk_events(
});
}
}
disk::persist_inbound_payments(ldk_data_dir.clone(), &inbound).unwrap();
persister.persist(INBOUND_PAYMENTS_FNAME, &*inbound).unwrap();
}
Event::PaymentSent { payment_preimage, payment_hash, fee_paid_msat, .. } => {
let mut outbound = outbound_payments.lock().unwrap();
Expand All @@ -287,7 +276,7 @@ async fn handle_ldk_events(
io::stdout().flush().unwrap();
}
}
disk::persist_outbound_payments(ldk_data_dir, &outbound).unwrap();
persister.persist(OUTBOUND_PAYMENTS_FNAME, &*outbound).unwrap();
}
Event::OpenChannelRequest { .. } => {
// Unreachable, we don't set manually_accept_inbound_channels
Expand All @@ -310,7 +299,7 @@ async fn handle_ldk_events(
let payment = outbound.payments.get_mut(&payment_hash).unwrap();
payment.status = HTLCStatus::Failed;
}
disk::persist_outbound_payments(ldk_data_dir, &outbound).unwrap();
persister.persist(OUTBOUND_PAYMENTS_FNAME, &*outbound).unwrap();
}
Event::PaymentForwarded {
prev_channel_id,
Expand Down Expand Up @@ -740,12 +729,12 @@ async fn start_ldk() {
});

let inbound_payments = Arc::new(Mutex::new(disk::read_payment_info(Path::new(&format!(
"{}/inbound_payments",
ldk_data_dir
"{}/{}",
ldk_data_dir, INBOUND_PAYMENTS_FNAME
)))));
let outbound_payments = Arc::new(Mutex::new(disk::read_payment_info(Path::new(&format!(
"{}/outbound_payments",
ldk_data_dir
"{}/{}",
ldk_data_dir, OUTBOUND_PAYMENTS_FNAME
)))));

// Step 18: Handle LDK Events
Expand All @@ -757,7 +746,6 @@ async fn start_ldk() {
let outbound_payments_event_listener = Arc::clone(&outbound_payments);
let persister_event_listener = Arc::clone(&persister);
let network = args.network;
let ldk_data_dir_copy = ldk_data_dir.clone();
let event_handler = move |event: Event| {
let channel_manager_event_listener = Arc::clone(&channel_manager_event_listener);
let bitcoind_client_event_listener = Arc::clone(&bitcoind_client_event_listener);
Expand All @@ -766,7 +754,6 @@ async fn start_ldk() {
let inbound_payments_event_listener = Arc::clone(&inbound_payments_event_listener);
let outbound_payments_event_listener = Arc::clone(&outbound_payments_event_listener);
let persister_event_listener = Arc::clone(&persister_event_listener);
let ldk_data_dir_copy = ldk_data_dir_copy.clone();
async move {
handle_ldk_events(
&channel_manager_event_listener,
Expand All @@ -778,7 +765,6 @@ async fn start_ldk() {
&persister_event_listener,
network,
event,
ldk_data_dir_copy,
)
.await;
}
Expand Down Expand Up @@ -894,6 +880,7 @@ async fn start_ldk() {
ldk_data_dir,
network,
Arc::clone(&logger),
Arc::clone(&persister),
)
.await;

Expand Down

0 comments on commit 9e0b09b

Please sign in to comment.