Update to LDK 0.0.121
[ldk-sample] / src / main.rs
index 50edb22ed54449d47d1f168c252ab05ff0ff7a6a..73a6ddf3356e7d2aabfa9c32ea9debfbef379250 100644 (file)
@@ -20,12 +20,12 @@ use lightning::events::bump_transaction::{BumpTransactionEventHandler, Wallet};
 use lightning::events::{Event, PaymentFailureReason, PaymentPurpose};
 use lightning::ln::channelmanager::{self, RecentPaymentDetails};
 use lightning::ln::channelmanager::{
-       ChainParameters, ChannelManagerReadArgs, SimpleArcChannelManager,
+       ChainParameters, ChannelManagerReadArgs, PaymentId, SimpleArcChannelManager,
 };
 use lightning::ln::msgs::DecodeError;
 use lightning::ln::peer_handler::{IgnoringMessageHandler, MessageHandler, SimpleArcPeerManager};
 use lightning::ln::{ChannelId, PaymentHash, PaymentPreimage, PaymentSecret};
-use lightning::onion_message::{DefaultMessageRouter, SimpleArcOnionMessenger};
+use lightning::onion_message::messenger::{DefaultMessageRouter, SimpleArcOnionMessenger};
 use lightning::routing::gossip;
 use lightning::routing::gossip::{NodeId, P2PGossipSync};
 use lightning::routing::router::DefaultRouter;
@@ -109,11 +109,19 @@ impl_writeable_tlv_based!(PaymentInfo, {
        (6, amt_msat, required),
 });
 
-pub(crate) struct PaymentInfoStorage {
+pub(crate) struct InboundPaymentInfoStorage {
        payments: HashMap<PaymentHash, PaymentInfo>,
 }
 
-impl_writeable_tlv_based!(PaymentInfoStorage, {
+impl_writeable_tlv_based!(InboundPaymentInfoStorage, {
+       (0, payments, required),
+});
+
+pub(crate) struct OutboundPaymentInfoStorage {
+       payments: HashMap<PaymentId, PaymentInfo>,
+}
+
+impl_writeable_tlv_based!(OutboundPaymentInfoStorage, {
        (0, payments, required),
 });
 
@@ -137,11 +145,6 @@ pub(crate) type GossipVerifier = lightning_block_sync::gossip::GossipVerifier<
        lightning_block_sync::gossip::TokioSpawner,
        Arc<lightning_block_sync::rpc::RpcClient>,
        Arc<FilesystemLogger>,
-       SocketDescriptor,
-       Arc<ChannelManager>,
-       Arc<SimpleArcOnionMessenger<FilesystemLogger>>,
-       IgnoringMessageHandler,
-       Arc<KeysManager>,
 >;
 
 pub(crate) type PeerManager = SimpleArcPeerManager<
@@ -158,7 +161,8 @@ pub(crate) type ChannelManager =
 
 pub(crate) type NetworkGraph = gossip::NetworkGraph<Arc<FilesystemLogger>>;
 
-type OnionMessenger = SimpleArcOnionMessenger<FilesystemLogger>;
+type OnionMessenger =
+       SimpleArcOnionMessenger<ChainMonitor, BitcoindClient, BitcoindClient, FilesystemLogger>;
 
 pub(crate) type BumpTxEventHandler = BumpTransactionEventHandler<
        Arc<BitcoindClient>,
@@ -170,8 +174,9 @@ pub(crate) type BumpTxEventHandler = BumpTransactionEventHandler<
 async fn handle_ldk_events(
        channel_manager: &Arc<ChannelManager>, bitcoind_client: &BitcoindClient,
        network_graph: &NetworkGraph, keys_manager: &KeysManager,
-       bump_tx_event_handler: &BumpTxEventHandler, inbound_payments: Arc<Mutex<PaymentInfoStorage>>,
-       outbound_payments: Arc<Mutex<PaymentInfoStorage>>, fs_store: &Arc<FilesystemStore>,
+       bump_tx_event_handler: &BumpTxEventHandler,
+       inbound_payments: Arc<Mutex<InboundPaymentInfoStorage>>,
+       outbound_payments: Arc<Mutex<OutboundPaymentInfoStorage>>, fs_store: &Arc<FilesystemStore>,
        network: Network, event: Event,
 ) {
        match event {
@@ -185,12 +190,12 @@ async fn handle_ldk_events(
                        // Construct the raw transaction with one output, that is paid the amount of the
                        // channel.
                        let addr = WitnessProgram::from_scriptpubkey(
-                               &output_script[..],
+                               &output_script.as_bytes(),
                                match network {
                                        Network::Bitcoin => bitcoin_bech32::constants::Network::Bitcoin,
-                                       Network::Testnet => bitcoin_bech32::constants::Network::Testnet,
                                        Network::Regtest => bitcoin_bech32::constants::Network::Regtest,
                                        Network::Signet => bitcoin_bech32::constants::Network::Signet,
+                                       Network::Testnet | _ => bitcoin_bech32::constants::Network::Testnet,
                                },
                        )
                        .expect("Lightning funding tx should always be to a SegWit output")
@@ -203,7 +208,7 @@ async fn handle_ldk_events(
                        // satisfied.
                        let funded_tx = bitcoind_client.fund_raw_transaction(raw_tx).await;
 
-                       // Sign the final funding transaction and broadcast it.
+                       // Sign the final funding transaction and give it to LDK, who will eventually broadcast it.
                        let signed_tx = bitcoind_client.sign_raw_transaction_with_wallet(funded_tx.hex).await;
                        assert_eq!(signed_tx.complete, true);
                        let final_tx: Transaction =
@@ -285,10 +290,12 @@ async fn handle_ldk_events(
                        }
                        fs_store.write("", "", INBOUND_PAYMENTS_FNAME, &inbound.encode()).unwrap();
                }
-               Event::PaymentSent { payment_preimage, payment_hash, fee_paid_msat, .. } => {
+               Event::PaymentSent {
+                       payment_preimage, payment_hash, fee_paid_msat, payment_id, ..
+               } => {
                        let mut outbound = outbound_payments.lock().unwrap();
-                       for (hash, payment) in outbound.payments.iter_mut() {
-                               if *hash == payment_hash {
+                       for (id, payment) in outbound.payments.iter_mut() {
+                               if *id == payment_id.unwrap() {
                                        payment.preimage = Some(payment_preimage);
                                        payment.status = HTLCStatus::Succeeded;
                                        println!(
@@ -342,7 +349,7 @@ async fn handle_ldk_events(
                Event::PaymentPathFailed { .. } => {}
                Event::ProbeSuccessful { .. } => {}
                Event::ProbeFailed { .. } => {}
-               Event::PaymentFailed { payment_hash, reason, .. } => {
+               Event::PaymentFailed { payment_hash, reason, payment_id, .. } => {
                        print!(
                                "\nEVENT: Failed to send payment to payment hash {}: {:?}",
                                payment_hash,
@@ -352,8 +359,20 @@ async fn handle_ldk_events(
                        io::stdout().flush().unwrap();
 
                        let mut outbound = outbound_payments.lock().unwrap();
-                       if outbound.payments.contains_key(&payment_hash) {
-                               let payment = outbound.payments.get_mut(&payment_hash).unwrap();
+                       if outbound.payments.contains_key(&payment_id) {
+                               let payment = outbound.payments.get_mut(&payment_id).unwrap();
+                               payment.status = HTLCStatus::Failed;
+                       }
+                       fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound.encode()).unwrap();
+               }
+               Event::InvoiceRequestFailed { payment_id } => {
+                       print!("\nEVENT: Failed to request invoice to send payment with id {}", payment_id);
+                       print!("> ");
+                       io::stdout().flush().unwrap();
+
+                       let mut outbound = outbound_payments.lock().unwrap();
+                       if outbound.payments.contains_key(&payment_id) {
+                               let payment = outbound.payments.get_mut(&payment_id).unwrap();
                                payment.status = HTLCStatus::Failed;
                        }
                        fs_store.write("", "", OUTBOUND_PAYMENTS_FNAME, &outbound.encode()).unwrap();
@@ -476,6 +495,7 @@ async fn handle_ldk_events(
                        user_channel_id: _,
                        counterparty_node_id,
                        channel_capacity_sats: _,
+                       channel_funding_txo: _,
                } => {
                        println!(
                                "\nEVENT: Channel {} with counterparty {} closed due to: {:?}",
@@ -492,6 +512,7 @@ async fn handle_ldk_events(
                }
                Event::HTLCIntercepted { .. } => {}
                Event::BumpTransaction(event) => bump_tx_event_handler.handle_event(&event),
+               Event::ConnectionNeeded { .. } => {}
        }
 }
 
@@ -515,6 +536,7 @@ async fn start_ldk() {
                args.bitcoind_rpc_port,
                args.bitcoind_rpc_username.clone(),
                args.bitcoind_rpc_password.clone(),
+               args.network,
                tokio::runtime::Handle::current(),
                Arc::clone(&logger),
        )
@@ -532,9 +554,9 @@ async fn start_ldk() {
        if bitcoind_chain
                != match args.network {
                        bitcoin::Network::Bitcoin => "main",
-                       bitcoin::Network::Testnet => "test",
                        bitcoin::Network::Regtest => "regtest",
                        bitcoin::Network::Signet => "signet",
+                       bitcoin::Network::Testnet | _ => "test",
                } {
                println!(
                        "Chain argument ({}) didn't match bitcoind chain ({})",
@@ -753,8 +775,8 @@ async fn start_ldk() {
                Arc::clone(&keys_manager),
                Arc::clone(&keys_manager),
                Arc::clone(&logger),
-               Arc::new(DefaultMessageRouter {}),
-               IgnoringMessageHandler {},
+               Arc::new(DefaultMessageRouter::new(Arc::clone(&network_graph))),
+               Arc::clone(&channel_manager),
                IgnoringMessageHandler {},
        ));
        let mut ephemeral_bytes = [0; 32];
@@ -825,32 +847,30 @@ async fn start_ldk() {
                }
        });
 
-       let inbound_payments = Arc::new(Mutex::new(disk::read_payment_info(Path::new(&format!(
-               "{}/{}",
-               ldk_data_dir, INBOUND_PAYMENTS_FNAME
-       )))));
-       let outbound_payments = Arc::new(Mutex::new(disk::read_payment_info(Path::new(&format!(
-               "{}/{}",
-               ldk_data_dir, OUTBOUND_PAYMENTS_FNAME
-       )))));
-       let recent_payments_payment_hashes = channel_manager
+       let inbound_payments = Arc::new(Mutex::new(disk::read_inbound_payment_info(Path::new(
+               &format!("{}/{}", ldk_data_dir, INBOUND_PAYMENTS_FNAME),
+       ))));
+       let outbound_payments = Arc::new(Mutex::new(disk::read_outbound_payment_info(Path::new(
+               &format!("{}/{}", ldk_data_dir, OUTBOUND_PAYMENTS_FNAME),
+       ))));
+       let recent_payments_payment_ids = channel_manager
                .list_recent_payments()
                .into_iter()
                .filter_map(|p| match p {
-                       RecentPaymentDetails::Pending { payment_hash, .. } => Some(payment_hash),
-                       RecentPaymentDetails::Fulfilled { payment_hash, .. } => payment_hash,
-                       RecentPaymentDetails::Abandoned { payment_hash, .. } => Some(payment_hash),
-                       RecentPaymentDetails::AwaitingInvoice { payment_id: _ } => todo!(),
+                       RecentPaymentDetails::Pending { payment_id, .. } => Some(payment_id),
+                       RecentPaymentDetails::Fulfilled { payment_id, .. } => Some(payment_id),
+                       RecentPaymentDetails::Abandoned { payment_id, .. } => Some(payment_id),
+                       RecentPaymentDetails::AwaitingInvoice { payment_id } => Some(payment_id),
                })
-               .collect::<Vec<PaymentHash>>();
-       for (payment_hash, payment_info) in outbound_payments
+               .collect::<Vec<PaymentId>>();
+       for (payment_id, payment_info) in outbound_payments
                .lock()
                .unwrap()
                .payments
                .iter_mut()
                .filter(|(_, i)| matches!(i.status, HTLCStatus::Pending))
        {
-               if !recent_payments_payment_hashes.contains(payment_hash) {
+               if !recent_payments_payment_ids.contains(payment_id) {
                        payment_info.status = HTLCStatus::Failed;
                }
        }
@@ -917,6 +937,7 @@ async fn start_ldk() {
                        })
                },
                false,
+               || Some(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap()),
        ));
 
        // Regularly reconnect to channel peers.