Skip to content

Commit

Permalink
post-review fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
zoedberg committed Jul 16, 2023
1 parent 7814899 commit c54c387
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 108 deletions.
97 changes: 49 additions & 48 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 @@ -156,10 +158,12 @@ 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();
send_payment(
&channel_manager,
&invoice,
&mut outbound_payments.lock().unwrap(),
persister.clone(),
);
}
"keysend" => {
let dest_pubkey = match words.next() {
Expand Down Expand Up @@ -189,16 +193,14 @@ pub(crate) async fn poll_for_user_input(
continue;
}
};
let mut outbound_payments = outbound_payments.lock().unwrap();
keysend(
&*channel_manager,
&channel_manager,
dest_pubkey,
amt_msat,
&*keys_manager,
&mut outbound_payments,
&mut outbound_payments.lock().unwrap(),
persister.clone(),
);
disk::persist_outbound_payments(ldk_data_dir.clone(), &outbound_payments)
.unwrap();
}
"getinvoice" => {
let amt_str = words.next();
Expand Down Expand Up @@ -229,14 +231,13 @@ pub(crate) async fn poll_for_user_input(
get_invoice(
amt_msat.unwrap(),
&mut inbound_payments,
&*channel_manager,
&channel_manager,
Arc::clone(&keys_manager),
network,
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 Expand Up @@ -665,40 +666,40 @@ fn open_channel(
}

fn send_payment(
channel_manager: &ChannelManager, invoice: &Invoice, outbound_payments: &mut PaymentInfoStorage,
channel_manager: &ChannelManager, invoice: &Invoice,
outbound_payments: &mut PaymentInfoStorage, persister: Arc<FilesystemPersister>,
) {
let status =
match pay_invoice(invoice, Retry::Timeout(Duration::from_secs(10)), channel_manager) {
Ok(_payment_id) => {
let payee_pubkey = invoice.recover_payee_pub_key();
let amt_msat = invoice.amount_milli_satoshis().unwrap();
println!("EVENT: initiated sending {} msats to {}", amt_msat, payee_pubkey);
print!("> ");
HTLCStatus::Pending
}
Err(e) => {
println!("ERROR: failed to send payment: {:?}", e);
print!("> ");
HTLCStatus::Failed
}
};
let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
let payment_secret = Some(invoice.payment_secret().clone());

let payment_hash = PaymentHash((*invoice.payment_hash()).into_inner());
let payment_secret = Some(*invoice.payment_secret());
outbound_payments.payments.insert(
payment_hash,
PaymentInfo {
preimage: None,
secret: payment_secret,
status,
status: HTLCStatus::Pending,
amt_msat: MillisatAmount(invoice.amount_milli_satoshis()),
},
);
persister.persist(OUTBOUND_PAYMENTS_FNAME, &*outbound_payments).unwrap();
match pay_invoice(invoice, Retry::Timeout(Duration::from_secs(10)), channel_manager) {
Ok(_payment_id) => {
let payee_pubkey = invoice.recover_payee_pub_key();
let amt_msat = invoice.amount_milli_satoshis().unwrap();
println!("EVENT: initiated sending {} msats to {}", amt_msat, payee_pubkey);
print!("> ");
}
Err(e) => {
println!("ERROR: failed to send payment: {:?}", e);
print!("> ");
outbound_payments.payments.get_mut(&payment_hash).unwrap().status = HTLCStatus::Failed;
persister.persist(OUTBOUND_PAYMENTS_FNAME, &*outbound_payments).unwrap();
}
};
}

fn keysend<E: EntropySource>(
channel_manager: &ChannelManager, payee_pubkey: PublicKey, amt_msat: u64, entropy_source: &E,
outbound_payments: &mut PaymentInfoStorage,
outbound_payments: &mut PaymentInfoStorage, persister: Arc<FilesystemPersister>,
) {
let payment_preimage = PaymentPreimage(entropy_source.get_secure_random_bytes());
let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
Expand All @@ -707,7 +708,17 @@ fn keysend<E: EntropySource>(
payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
final_value_msat: amt_msat,
};
let status = match channel_manager.send_spontaneous_payment_with_retry(
outbound_payments.payments.insert(
payment_hash,
PaymentInfo {
preimage: None,
secret: None,
status: HTLCStatus::Pending,
amt_msat: MillisatAmount(Some(amt_msat)),
},
);
persister.persist(OUTBOUND_PAYMENTS_FNAME, &*outbound_payments).unwrap();
match channel_manager.send_spontaneous_payment_with_retry(
Some(payment_preimage),
RecipientOnionFields::spontaneous_empty(),
PaymentId(payment_hash.0),
Expand All @@ -717,24 +728,14 @@ fn keysend<E: EntropySource>(
Ok(_payment_hash) => {
println!("EVENT: initiated sending {} msats to {}", amt_msat, payee_pubkey);
print!("> ");
HTLCStatus::Pending
}
Err(e) => {
println!("ERROR: failed to send payment: {:?}", e);
print!("> ");
HTLCStatus::Failed
outbound_payments.payments.get_mut(&payment_hash).unwrap().status = HTLCStatus::Failed;
persister.persist(OUTBOUND_PAYMENTS_FNAME, &*outbound_payments).unwrap();
}
};

outbound_payments.payments.insert(
payment_hash,
PaymentInfo {
preimage: None,
secret: None,
status,
amt_msat: MillisatAmount(Some(amt_msat)),
},
);
}

fn get_invoice(
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
Loading

0 comments on commit c54c387

Please sign in to comment.