]> git.bitcoin.ninja Git - ldk-sample/commitdiff
SatoshiAmount -> MillisatAmount and PaymentInfo struct
authorValentine Wallace <vwallace@protonmail.com>
Wed, 14 Apr 2021 02:35:26 +0000 (22:35 -0400)
committerValentine Wallace <vwallace@protonmail.com>
Mon, 3 May 2021 22:31:02 +0000 (18:31 -0400)
src/cli.rs
src/main.rs

index 0144c001022662d7da6890cda460b24b30edc243..e2f4a6379235c0d6da53a0a5d7464993983189b1 100644 (file)
@@ -1,8 +1,8 @@
 use crate::disk;
 use crate::hex_utils;
 use crate::{
-       ChannelManager, FilesystemLogger, HTLCDirection, HTLCStatus, PaymentInfoStorage, PeerManager,
-       SatoshiAmount,
+       ChannelManager, FilesystemLogger, HTLCDirection, HTLCStatus, MillisatAmount, PaymentInfo,
+       PaymentInfoStorage, PeerManager,
 };
 use bitcoin::hashes::sha256::Hash as Sha256Hash;
 use bitcoin::hashes::Hash;
@@ -285,21 +285,21 @@ pub(crate) async fn poll_for_user_input(
                                "getinvoice" => {
                                        let amt_str = words.next();
                                        if amt_str.is_none() {
-                                               println!("ERROR: getinvoice requires an amount in satoshis");
+                                               println!("ERROR: getinvoice requires an amount in millisatoshis");
                                                print!("> ");
                                                io::stdout().flush().unwrap();
                                                continue;
                                        }
 
-                                       let amt_sat: Result<u64, _> = amt_str.unwrap().parse();
-                                       if amt_sat.is_err() {
+                                       let amt_msat: Result<u64, _> = amt_str.unwrap().parse();
+                                       if amt_msat.is_err() {
                                                println!("ERROR: getinvoice provided payment amount was not a number");
                                                print!("> ");
                                                io::stdout().flush().unwrap();
                                                continue;
                                        }
                                        get_invoice(
-                                               amt_sat.unwrap(),
+                                               amt_msat.unwrap(),
                                                payment_storage.clone(),
                                                node_privkey.clone(),
                                                channel_manager.clone(),
@@ -386,7 +386,7 @@ pub(crate) async fn poll_for_user_input(
 fn help() {
        println!("openchannel pubkey@host:port <channel_amt_satoshis>");
        println!("sendpayment <invoice>");
-       println!("getinvoice <amt_in_satoshis>");
+       println!("getinvoice <amt_in_millisatoshis>");
        println!("connectpeer pubkey@host:port");
        println!("listchannels");
        println!("listpayments");
@@ -423,18 +423,18 @@ fn list_payments(payment_storage: PaymentInfoStorage) {
        let payments = payment_storage.lock().unwrap();
        print!("[");
        for (payment_hash, payment_info) in payments.deref() {
-               let direction_str = match payment_info.1 {
+               let direction_str = match payment_info.direction {
                        HTLCDirection::Inbound => "inbound",
                        HTLCDirection::Outbound => "outbound",
                };
                println!("");
                println!("\t{{");
-               println!("\t\tamount_satoshis: {},", payment_info.3);
+               println!("\t\tamount_millisatoshis: {},", payment_info.amt_msat);
                println!("\t\tpayment_hash: {},", hex_utils::hex_str(&payment_hash.0));
                println!("\t\thtlc_direction: {},", direction_str);
                println!(
                        "\t\thtlc_status: {},",
-                       match payment_info.2 {
+                       match payment_info.status {
                                HTLCStatus::Pending => "pending",
                                HTLCStatus::Succeeded => "succeeded",
                                HTLCStatus::Failed => "failed",
@@ -558,12 +558,18 @@ fn send_payment(
        let mut payments = payment_storage.lock().unwrap();
        payments.insert(
                payment_hash,
-               (None, HTLCDirection::Outbound, status, SatoshiAmount(Some(amt_msat / 1000))),
+               PaymentInfo {
+                       preimage: None,
+                       secret: payment_secret,
+                       direction: HTLCDirection::Outbound,
+                       status,
+                       amt_msat: MillisatAmount(Some(amt_msat)),
+               },
        );
 }
 
 fn get_invoice(
-       amt_sat: u64, payment_storage: PaymentInfoStorage, our_node_privkey: SecretKey,
+       amt_msat: u64, payment_storage: PaymentInfoStorage, our_node_privkey: SecretKey,
        channel_manager: Arc<ChannelManager>, network: Network,
 ) {
        let mut payments = payment_storage.lock().unwrap();
@@ -582,7 +588,7 @@ fn get_invoice(
        })
        .payment_hash(payment_hash)
        .description("rust-lightning-bitcoinrpc invoice".to_string())
-       .amount_pico_btc(amt_sat * 10_000)
+       .amount_pico_btc(amt_msat * 10)
        .current_timestamp()
        .payee_pub_key(our_node_pubkey);
 
@@ -622,12 +628,16 @@ fn get_invoice(
 
        payments.insert(
                PaymentHash(payment_hash.into_inner()),
-               (
-                       Some(PaymentPreimage(preimage)),
-                       HTLCDirection::Inbound,
-                       HTLCStatus::Pending,
-                       SatoshiAmount(Some(amt_sat)),
-               ),
+               PaymentInfo {
+                       preimage: Some(PaymentPreimage(preimage)),
+                       // We can't add payment secrets to invoices until we support features in invoices.
+                       // Otherwise lnd errors with "destination hop doesn't understand payment addresses"
+                       // (for context, lnd calls payment secrets "payment addresses").
+                       secret: None,
+                       direction: HTLCDirection::Inbound,
+                       status: HTLCStatus::Pending,
+                       amt_msat: MillisatAmount(Some(amt_msat)),
+               },
        );
 }
 
index 5f213fca40b2dffac9a72c3ed0897c58b84e4bf3..87ad4e9a718997f48c58af19aa32688c1944791d 100644 (file)
@@ -23,7 +23,8 @@ use lightning::chain::Filter;
 use lightning::chain::Watch;
 use lightning::ln::channelmanager;
 use lightning::ln::channelmanager::{
-       ChainParameters, ChannelManagerReadArgs, PaymentHash, PaymentPreimage, SimpleArcChannelManager,
+       ChainParameters, ChannelManagerReadArgs, PaymentHash, PaymentPreimage, PaymentSecret,
+       SimpleArcChannelManager,
 };
 use lightning::ln::peer_handler::{MessageHandler, SimpleArcPeerManager};
 use lightning::routing::network_graph::NetGraphMsgHandler;
@@ -62,9 +63,9 @@ pub(crate) enum HTLCStatus {
        Failed,
 }
 
-pub(crate) struct SatoshiAmount(Option<u64>);
+pub(crate) struct MillisatAmount(Option<u64>);
 
-impl fmt::Display for SatoshiAmount {
+impl fmt::Display for MillisatAmount {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                match self.0 {
                        Some(amt) => write!(f, "{}", amt),
@@ -73,11 +74,15 @@ impl fmt::Display for SatoshiAmount {
        }
 }
 
-pub(crate) type PaymentInfoStorage = Arc<
-       Mutex<
-               HashMap<PaymentHash, (Option<PaymentPreimage>, HTLCDirection, HTLCStatus, SatoshiAmount)>,
-       >,
->;
+pub(crate) struct PaymentInfo {
+       preimage: Option<PaymentPreimage>,
+       secret: Option<PaymentSecret>,
+       direction: HTLCDirection,
+       status: HTLCStatus,
+       amt_msat: MillisatAmount,
+}
+
+pub(crate) type PaymentInfoStorage = Arc<Mutex<HashMap<PaymentHash, PaymentInfo>>>;
 
 type ChainMonitor = chainmonitor::ChainMonitor<
        InMemorySigner,
@@ -151,47 +156,50 @@ async fn handle_ldk_events(
                                                .funding_transaction_generated(&temporary_channel_id, final_tx)
                                                .unwrap();
                                }
-                               Event::FundingBroadcastSafe { funding_txo, .. } => {
-                               Event::PaymentReceived { payment_hash, payment_secret, amt: amt_msat } => {
+                               Event::PaymentReceived { payment_hash, .. } => {
                                        let mut payments = payment_storage.lock().unwrap();
-                                       if let Some((Some(preimage), _, _, _)) = payments.get(&payment_hash) {
+                                       if let Some(payment) = payments.get_mut(&payment_hash) {
                                                assert!(loop_channel_manager.claim_funds(
-                                                       preimage.clone(),
-                                                       &payment_secret,
-                                                       amt_msat
+                                                       payment.preimage.unwrap().clone(),
+                                                       &payment.secret,
+                                                       payment.amt_msat.0.unwrap(),
                                                ));
                                                println!(
-                                                       "\nEVENT: received payment from payment_hash {} of {} satoshis",
+                                                       "\nEVENT: received payment from payment_hash {} of {} millisatoshis",
                                                        hex_utils::hex_str(&payment_hash.0),
-                                                       amt_msat / 1000
+                                                       payment.amt_msat
                                                );
                                                print!("> ");
                                                io::stdout().flush().unwrap();
-                                               let (_, _, ref mut status, _) = payments.get_mut(&payment_hash).unwrap();
-                                               *status = HTLCStatus::Succeeded;
+                                               payment.status = HTLCStatus::Succeeded;
                                        } else {
                                                println!("\nERROR: we received a payment but didn't know the preimage");
                                                print!("> ");
                                                io::stdout().flush().unwrap();
-                                               loop_channel_manager.fail_htlc_backwards(&payment_hash, &payment_secret);
+                                               loop_channel_manager.fail_htlc_backwards(&payment_hash, &None);
                                                payments.insert(
                                                        payment_hash,
-                                                       (None, HTLCDirection::Inbound, HTLCStatus::Failed, SatoshiAmount(None)),
+                                                       PaymentInfo {
+                                                               preimage: None,
+                                                               secret: None,
+                                                               direction: HTLCDirection::Inbound,
+                                                               status: HTLCStatus::Failed,
+                                                               amt_msat: MillisatAmount(None),
+                                                       },
                                                );
                                        }
                                }
                                Event::PaymentSent { payment_preimage } => {
                                        let hashed = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
                                        let mut payments = payment_storage.lock().unwrap();
-                                       for (payment_hash, (preimage_option, _, status, amt_sat)) in payments.iter_mut()
-                                       {
+                                       for (payment_hash, payment) in payments.iter_mut() {
                                                if *payment_hash == hashed {
-                                                       *preimage_option = Some(payment_preimage);
-                                                       *status = HTLCStatus::Succeeded;
+                                                       payment.preimage = Some(payment_preimage);
+                                                       payment.status = HTLCStatus::Succeeded;
                                                        println!(
-                                                               "\nEVENT: successfully sent payment of {} satoshis from \
+                                                               "\nEVENT: successfully sent payment of {} millisatoshis from \
                                          payment hash {:?} with preimage {:?}",
-                                                               amt_sat,
+                                                               payment.amt_msat,
                                                                hex_utils::hex_str(&payment_hash.0),
                                                                hex_utils::hex_str(&payment_preimage.0)
                                                        );
@@ -215,8 +223,8 @@ async fn handle_ldk_events(
 
                                        let mut payments = payment_storage.lock().unwrap();
                                        if payments.contains_key(&payment_hash) {
-                                               let (_, _, ref mut status, _) = payments.get_mut(&payment_hash).unwrap();
-                                               *status = HTLCStatus::Failed;
+                                               let payment = payments.get_mut(&payment_hash).unwrap();
+                                               payment.status = HTLCStatus::Failed;
                                        }
                                }
                                Event::PendingHTLCsForwardable { time_forwardable } => {
@@ -492,18 +500,11 @@ async fn start_ldk() {
                logger.clone(),
        );
 
-       let peer_manager_processor = peer_manager.clone();
-       tokio::spawn(async move {
-               loop {
-                       peer_manager_processor.timer_tick_occurred();
-                       tokio::time::sleep(Duration::from_secs(60)).await;
-               }
-       });
-
        // Step 15: Initialize LDK Event Handling
        let channel_manager_event_listener = channel_manager.clone();
        let chain_monitor_event_listener = chain_monitor.clone();
        let keys_manager_listener = keys_manager.clone();
+       // TODO: persist payment info to disk
        let payment_info: PaymentInfoStorage = Arc::new(Mutex::new(HashMap::new()));
        let payment_info_for_events = payment_info.clone();
        let network = args.network;