]> git.bitcoin.ninja Git - ldk-sample/blob - src/main.rs
Update for LDK release 0.0.113
[ldk-sample] / src / main.rs
1 mod args;
2 pub mod bitcoind_client;
3 mod cli;
4 mod convert;
5 mod disk;
6 mod hex_utils;
7
8 use crate::bitcoind_client::BitcoindClient;
9 use crate::disk::FilesystemLogger;
10 use bitcoin::blockdata::constants::genesis_block;
11 use bitcoin::blockdata::transaction::Transaction;
12 use bitcoin::consensus::encode;
13 use bitcoin::network::constants::Network;
14 use bitcoin::secp256k1::Secp256k1;
15 use bitcoin::BlockHash;
16 use bitcoin_bech32::WitnessProgram;
17 use lightning::chain;
18 use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
19 use lightning::chain::keysinterface::{InMemorySigner, KeysInterface, KeysManager, Recipient};
20 use lightning::chain::{chainmonitor, ChannelMonitorUpdateStatus};
21 use lightning::chain::{Filter, Watch};
22 use lightning::ln::channelmanager;
23 use lightning::ln::channelmanager::{
24         ChainParameters, ChannelManagerReadArgs, SimpleArcChannelManager,
25 };
26 use lightning::ln::peer_handler::{IgnoringMessageHandler, MessageHandler, SimpleArcPeerManager};
27 use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
28 use lightning::onion_message::SimpleArcOnionMessenger;
29 use lightning::routing::gossip;
30 use lightning::routing::gossip::{NodeId, P2PGossipSync};
31 use lightning::routing::router::DefaultRouter;
32 use lightning::routing::scoring::ProbabilisticScorer;
33 use lightning::util::config::UserConfig;
34 use lightning::util::events::{Event, PaymentPurpose};
35 use lightning::util::ser::ReadableArgs;
36 use lightning_background_processor::{BackgroundProcessor, GossipSync};
37 use lightning_block_sync::init;
38 use lightning_block_sync::poll;
39 use lightning_block_sync::SpvClient;
40 use lightning_block_sync::UnboundedCache;
41 use lightning_invoice::payment;
42 use lightning_net_tokio::SocketDescriptor;
43 use lightning_persister::FilesystemPersister;
44 use rand::{thread_rng, Rng};
45 use std::collections::hash_map::Entry;
46 use std::collections::HashMap;
47 use std::convert::TryInto;
48 use std::fmt;
49 use std::fs;
50 use std::fs::File;
51 use std::io;
52 use std::io::Write;
53 use std::path::Path;
54 use std::sync::atomic::{AtomicBool, Ordering};
55 use std::sync::{Arc, Mutex};
56 use std::time::{Duration, SystemTime};
57
58 pub(crate) enum HTLCStatus {
59         Pending,
60         Succeeded,
61         Failed,
62 }
63
64 pub(crate) struct MillisatAmount(Option<u64>);
65
66 impl fmt::Display for MillisatAmount {
67         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
68                 match self.0 {
69                         Some(amt) => write!(f, "{}", amt),
70                         None => write!(f, "unknown"),
71                 }
72         }
73 }
74
75 pub(crate) struct PaymentInfo {
76         preimage: Option<PaymentPreimage>,
77         secret: Option<PaymentSecret>,
78         status: HTLCStatus,
79         amt_msat: MillisatAmount,
80 }
81
82 pub(crate) type PaymentInfoStorage = Arc<Mutex<HashMap<PaymentHash, PaymentInfo>>>;
83
84 type ChainMonitor = chainmonitor::ChainMonitor<
85         InMemorySigner,
86         Arc<dyn Filter + Send + Sync>,
87         Arc<BitcoindClient>,
88         Arc<BitcoindClient>,
89         Arc<FilesystemLogger>,
90         Arc<FilesystemPersister>,
91 >;
92
93 pub(crate) type PeerManager = SimpleArcPeerManager<
94         SocketDescriptor,
95         ChainMonitor,
96         BitcoindClient,
97         BitcoindClient,
98         dyn chain::Access + Send + Sync,
99         FilesystemLogger,
100 >;
101
102 pub(crate) type ChannelManager =
103         SimpleArcChannelManager<ChainMonitor, BitcoindClient, BitcoindClient, FilesystemLogger>;
104
105 pub(crate) type InvoicePayer<E> =
106         payment::InvoicePayer<Arc<ChannelManager>, Router, Arc<FilesystemLogger>, E>;
107
108 type Router = DefaultRouter<
109         Arc<NetworkGraph>,
110         Arc<FilesystemLogger>,
111         Arc<Mutex<ProbabilisticScorer<Arc<NetworkGraph>, Arc<FilesystemLogger>>>>,
112 >;
113
114 pub(crate) type NetworkGraph = gossip::NetworkGraph<Arc<FilesystemLogger>>;
115
116 type OnionMessenger = SimpleArcOnionMessenger<FilesystemLogger>;
117
118 async fn handle_ldk_events(
119         channel_manager: &Arc<ChannelManager>, bitcoind_client: &BitcoindClient,
120         network_graph: &NetworkGraph, keys_manager: &KeysManager,
121         inbound_payments: &PaymentInfoStorage, outbound_payments: &PaymentInfoStorage,
122         network: Network, event: &Event,
123 ) {
124         match event {
125                 Event::FundingGenerationReady {
126                         temporary_channel_id,
127                         counterparty_node_id,
128                         channel_value_satoshis,
129                         output_script,
130                         ..
131                 } => {
132                         // Construct the raw transaction with one output, that is paid the amount of the
133                         // channel.
134                         let addr = WitnessProgram::from_scriptpubkey(
135                                 &output_script[..],
136                                 match network {
137                                         Network::Bitcoin => bitcoin_bech32::constants::Network::Bitcoin,
138                                         Network::Testnet => bitcoin_bech32::constants::Network::Testnet,
139                                         Network::Regtest => bitcoin_bech32::constants::Network::Regtest,
140                                         Network::Signet => bitcoin_bech32::constants::Network::Signet,
141                                 },
142                         )
143                         .expect("Lightning funding tx should always be to a SegWit output")
144                         .to_address();
145                         let mut outputs = vec![HashMap::with_capacity(1)];
146                         outputs[0].insert(addr, *channel_value_satoshis as f64 / 100_000_000.0);
147                         let raw_tx = bitcoind_client.create_raw_transaction(outputs).await;
148
149                         // Have your wallet put the inputs into the transaction such that the output is
150                         // satisfied.
151                         let funded_tx = bitcoind_client.fund_raw_transaction(raw_tx).await;
152
153                         // Sign the final funding transaction and broadcast it.
154                         let signed_tx = bitcoind_client.sign_raw_transaction_with_wallet(funded_tx.hex).await;
155                         assert_eq!(signed_tx.complete, true);
156                         let final_tx: Transaction =
157                                 encode::deserialize(&hex_utils::to_vec(&signed_tx.hex).unwrap()).unwrap();
158                         // Give the funding transaction back to LDK for opening the channel.
159                         if channel_manager
160                                 .funding_transaction_generated(
161                                         &temporary_channel_id,
162                                         counterparty_node_id,
163                                         final_tx,
164                                 )
165                                 .is_err()
166                         {
167                                 println!(
168                                         "\nERROR: Channel went away before we could fund it. The peer disconnected or refused the channel.");
169                                 print!("> ");
170                                 io::stdout().flush().unwrap();
171                         }
172                 }
173                 Event::PaymentClaimable {
174                         payment_hash,
175                         purpose,
176                         amount_msat,
177                         receiver_node_id: _,
178                         via_channel_id: _,
179                         via_user_channel_id: _,
180                 } => {
181                         println!(
182                                 "\nEVENT: received payment from payment hash {} of {} millisatoshis",
183                                 hex_utils::hex_str(&payment_hash.0),
184                                 amount_msat,
185                         );
186                         print!("> ");
187                         io::stdout().flush().unwrap();
188                         let payment_preimage = match purpose {
189                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => *payment_preimage,
190                                 PaymentPurpose::SpontaneousPayment(preimage) => Some(*preimage),
191                         };
192                         channel_manager.claim_funds(payment_preimage.unwrap());
193                 }
194                 Event::PaymentClaimed { payment_hash, purpose, amount_msat, receiver_node_id: _ } => {
195                         println!(
196                                 "\nEVENT: claimed payment from payment hash {} of {} millisatoshis",
197                                 hex_utils::hex_str(&payment_hash.0),
198                                 amount_msat,
199                         );
200                         print!("> ");
201                         io::stdout().flush().unwrap();
202                         let (payment_preimage, payment_secret) = match purpose {
203                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
204                                         (*payment_preimage, Some(*payment_secret))
205                                 }
206                                 PaymentPurpose::SpontaneousPayment(preimage) => (Some(*preimage), None),
207                         };
208                         let mut payments = inbound_payments.lock().unwrap();
209                         match payments.entry(*payment_hash) {
210                                 Entry::Occupied(mut e) => {
211                                         let payment = e.get_mut();
212                                         payment.status = HTLCStatus::Succeeded;
213                                         payment.preimage = payment_preimage;
214                                         payment.secret = payment_secret;
215                                 }
216                                 Entry::Vacant(e) => {
217                                         e.insert(PaymentInfo {
218                                                 preimage: payment_preimage,
219                                                 secret: payment_secret,
220                                                 status: HTLCStatus::Succeeded,
221                                                 amt_msat: MillisatAmount(Some(*amount_msat)),
222                                         });
223                                 }
224                         }
225                 }
226                 Event::PaymentSent { payment_preimage, payment_hash, fee_paid_msat, .. } => {
227                         let mut payments = outbound_payments.lock().unwrap();
228                         for (hash, payment) in payments.iter_mut() {
229                                 if *hash == *payment_hash {
230                                         payment.preimage = Some(*payment_preimage);
231                                         payment.status = HTLCStatus::Succeeded;
232                                         println!(
233                                                 "\nEVENT: successfully sent payment of {} millisatoshis{} from \
234                                                                  payment hash {:?} with preimage {:?}",
235                                                 payment.amt_msat,
236                                                 if let Some(fee) = fee_paid_msat {
237                                                         format!(" (fee {} msat)", fee)
238                                                 } else {
239                                                         "".to_string()
240                                                 },
241                                                 hex_utils::hex_str(&payment_hash.0),
242                                                 hex_utils::hex_str(&payment_preimage.0)
243                                         );
244                                         print!("> ");
245                                         io::stdout().flush().unwrap();
246                                 }
247                         }
248                 }
249                 Event::OpenChannelRequest { .. } => {
250                         // Unreachable, we don't set manually_accept_inbound_channels
251                 }
252                 Event::PaymentPathSuccessful { .. } => {}
253                 Event::PaymentPathFailed { .. } => {}
254                 Event::ProbeSuccessful { .. } => {}
255                 Event::ProbeFailed { .. } => {}
256                 Event::PaymentFailed { payment_hash, .. } => {
257                         print!(
258                                 "\nEVENT: Failed to send payment to payment hash {:?}: exhausted payment retry attempts",
259                                 hex_utils::hex_str(&payment_hash.0)
260                         );
261                         print!("> ");
262                         io::stdout().flush().unwrap();
263
264                         let mut payments = outbound_payments.lock().unwrap();
265                         if payments.contains_key(&payment_hash) {
266                                 let payment = payments.get_mut(&payment_hash).unwrap();
267                                 payment.status = HTLCStatus::Failed;
268                         }
269                 }
270                 Event::PaymentForwarded {
271                         prev_channel_id,
272                         next_channel_id,
273                         fee_earned_msat,
274                         claim_from_onchain_tx,
275                 } => {
276                         let read_only_network_graph = network_graph.read_only();
277                         let nodes = read_only_network_graph.nodes();
278                         let channels = channel_manager.list_channels();
279
280                         let node_str = |channel_id: &Option<[u8; 32]>| match channel_id {
281                                 None => String::new(),
282                                 Some(channel_id) => match channels.iter().find(|c| c.channel_id == *channel_id) {
283                                         None => String::new(),
284                                         Some(channel) => {
285                                                 match nodes.get(&NodeId::from_pubkey(&channel.counterparty.node_id)) {
286                                                         None => "private node".to_string(),
287                                                         Some(node) => match &node.announcement_info {
288                                                                 None => "unnamed node".to_string(),
289                                                                 Some(announcement) => {
290                                                                         format!("node {}", announcement.alias)
291                                                                 }
292                                                         },
293                                                 }
294                                         }
295                                 },
296                         };
297                         let channel_str = |channel_id: &Option<[u8; 32]>| {
298                                 channel_id
299                                         .map(|channel_id| format!(" with channel {}", hex_utils::hex_str(&channel_id)))
300                                         .unwrap_or_default()
301                         };
302                         let from_prev_str =
303                                 format!(" from {}{}", node_str(prev_channel_id), channel_str(prev_channel_id));
304                         let to_next_str =
305                                 format!(" to {}{}", node_str(next_channel_id), channel_str(next_channel_id));
306
307                         let from_onchain_str = if *claim_from_onchain_tx {
308                                 "from onchain downstream claim"
309                         } else {
310                                 "from HTLC fulfill message"
311                         };
312                         if let Some(fee_earned) = fee_earned_msat {
313                                 println!(
314                                         "\nEVENT: Forwarded payment{}{}, earning {} msat {}",
315                                         from_prev_str, to_next_str, fee_earned, from_onchain_str
316                                 );
317                         } else {
318                                 println!(
319                                         "\nEVENT: Forwarded payment{}{}, claiming onchain {}",
320                                         from_prev_str, to_next_str, from_onchain_str
321                                 );
322                         }
323                         print!("> ");
324                         io::stdout().flush().unwrap();
325                 }
326                 Event::HTLCHandlingFailed { .. } => {}
327                 Event::PendingHTLCsForwardable { time_forwardable } => {
328                         let forwarding_channel_manager = channel_manager.clone();
329                         let min = time_forwardable.as_millis() as u64;
330                         tokio::spawn(async move {
331                                 let millis_to_sleep = thread_rng().gen_range(min, min * 5) as u64;
332                                 tokio::time::sleep(Duration::from_millis(millis_to_sleep)).await;
333                                 forwarding_channel_manager.process_pending_htlc_forwards();
334                         });
335                 }
336                 Event::SpendableOutputs { outputs } => {
337                         let destination_address = bitcoind_client.get_new_address().await;
338                         let output_descriptors = &outputs.iter().map(|a| a).collect::<Vec<_>>();
339                         let tx_feerate =
340                                 bitcoind_client.get_est_sat_per_1000_weight(ConfirmationTarget::Normal);
341                         let spending_tx = keys_manager
342                                 .spend_spendable_outputs(
343                                         output_descriptors,
344                                         Vec::new(),
345                                         destination_address.script_pubkey(),
346                                         tx_feerate,
347                                         &Secp256k1::new(),
348                                 )
349                                 .unwrap();
350                         bitcoind_client.broadcast_transaction(&spending_tx);
351                 }
352                 Event::ChannelReady {
353                         ref channel_id,
354                         user_channel_id: _,
355                         ref counterparty_node_id,
356                         channel_type: _,
357                 } => {
358                         println!(
359                                 "\nEVENT: Channel {} with peer {} is ready to be used!",
360                                 hex_utils::hex_str(channel_id),
361                                 hex_utils::hex_str(&counterparty_node_id.serialize()),
362                         );
363                         print!("> ");
364                         io::stdout().flush().unwrap();
365                 }
366                 Event::ChannelClosed { channel_id, reason, user_channel_id: _ } => {
367                         println!(
368                                 "\nEVENT: Channel {} closed due to: {:?}",
369                                 hex_utils::hex_str(channel_id),
370                                 reason
371                         );
372                         print!("> ");
373                         io::stdout().flush().unwrap();
374                 }
375                 Event::DiscardFunding { .. } => {
376                         // A "real" node should probably "lock" the UTXOs spent in funding transactions until
377                         // the funding transaction either confirms, or this event is generated.
378                 }
379                 Event::HTLCIntercepted { .. } => {}
380         }
381 }
382
383 async fn start_ldk() {
384         let args = match args::parse_startup_args() {
385                 Ok(user_args) => user_args,
386                 Err(()) => return,
387         };
388
389         // Initialize the LDK data directory if necessary.
390         let ldk_data_dir = format!("{}/.ldk", args.ldk_storage_dir_path);
391         fs::create_dir_all(ldk_data_dir.clone()).unwrap();
392
393         // Initialize our bitcoind client.
394         let bitcoind_client = match BitcoindClient::new(
395                 args.bitcoind_rpc_host.clone(),
396                 args.bitcoind_rpc_port,
397                 args.bitcoind_rpc_username.clone(),
398                 args.bitcoind_rpc_password.clone(),
399                 tokio::runtime::Handle::current(),
400         )
401         .await
402         {
403                 Ok(client) => Arc::new(client),
404                 Err(e) => {
405                         println!("Failed to connect to bitcoind client: {}", e);
406                         return;
407                 }
408         };
409
410         // Check that the bitcoind we've connected to is running the network we expect
411         let bitcoind_chain = bitcoind_client.get_blockchain_info().await.chain;
412         if bitcoind_chain
413                 != match args.network {
414                         bitcoin::Network::Bitcoin => "main",
415                         bitcoin::Network::Testnet => "test",
416                         bitcoin::Network::Regtest => "regtest",
417                         bitcoin::Network::Signet => "signet",
418                 } {
419                 println!(
420                         "Chain argument ({}) didn't match bitcoind chain ({})",
421                         args.network, bitcoind_chain
422                 );
423                 return;
424         }
425
426         // ## Setup
427         // Step 1: Initialize the FeeEstimator
428
429         // BitcoindClient implements the FeeEstimator trait, so it'll act as our fee estimator.
430         let fee_estimator = bitcoind_client.clone();
431
432         // Step 2: Initialize the Logger
433         let logger = Arc::new(FilesystemLogger::new(ldk_data_dir.clone()));
434
435         // Step 3: Initialize the BroadcasterInterface
436
437         // BitcoindClient implements the BroadcasterInterface trait, so it'll act as our transaction
438         // broadcaster.
439         let broadcaster = bitcoind_client.clone();
440
441         // Step 4: Initialize Persist
442         let persister = Arc::new(FilesystemPersister::new(ldk_data_dir.clone()));
443
444         // Step 5: Initialize the ChainMonitor
445         let chain_monitor: Arc<ChainMonitor> = Arc::new(chainmonitor::ChainMonitor::new(
446                 None,
447                 broadcaster.clone(),
448                 logger.clone(),
449                 fee_estimator.clone(),
450                 persister.clone(),
451         ));
452
453         // Step 6: Initialize the KeysManager
454
455         // The key seed that we use to derive the node privkey (that corresponds to the node pubkey) and
456         // other secret key material.
457         let keys_seed_path = format!("{}/keys_seed", ldk_data_dir.clone());
458         let keys_seed = if let Ok(seed) = fs::read(keys_seed_path.clone()) {
459                 assert_eq!(seed.len(), 32);
460                 let mut key = [0; 32];
461                 key.copy_from_slice(&seed);
462                 key
463         } else {
464                 let mut key = [0; 32];
465                 thread_rng().fill_bytes(&mut key);
466                 match File::create(keys_seed_path.clone()) {
467                         Ok(mut f) => {
468                                 f.write_all(&key).expect("Failed to write node keys seed to disk");
469                                 f.sync_all().expect("Failed to sync node keys seed to disk");
470                         }
471                         Err(e) => {
472                                 println!("ERROR: Unable to create keys seed file {}: {}", keys_seed_path, e);
473                                 return;
474                         }
475                 }
476                 key
477         };
478         let cur = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
479         let keys_manager = Arc::new(KeysManager::new(&keys_seed, cur.as_secs(), cur.subsec_nanos()));
480
481         // Step 7: Read ChannelMonitor state from disk
482         let mut channelmonitors = persister.read_channelmonitors(keys_manager.clone()).unwrap();
483
484         // Step 8: Poll for the best chain tip, which may be used by the channel manager & spv client
485         let polled_chain_tip = init::validate_best_block_header(bitcoind_client.as_ref())
486                 .await
487                 .expect("Failed to fetch best block header and best block");
488
489         // Step 9: Initialize the ChannelManager
490         let mut user_config = UserConfig::default();
491         user_config.channel_handshake_limits.force_announced_channel_preference = false;
492         let mut restarting_node = true;
493         let (channel_manager_blockhash, channel_manager) = {
494                 if let Ok(mut f) = fs::File::open(format!("{}/manager", ldk_data_dir.clone())) {
495                         let mut channel_monitor_mut_references = Vec::new();
496                         for (_, channel_monitor) in channelmonitors.iter_mut() {
497                                 channel_monitor_mut_references.push(channel_monitor);
498                         }
499                         let read_args = ChannelManagerReadArgs::new(
500                                 keys_manager.clone(),
501                                 fee_estimator.clone(),
502                                 chain_monitor.clone(),
503                                 broadcaster.clone(),
504                                 logger.clone(),
505                                 user_config,
506                                 channel_monitor_mut_references,
507                         );
508                         <(BlockHash, ChannelManager)>::read(&mut f, read_args).unwrap()
509                 } else {
510                         // We're starting a fresh node.
511                         restarting_node = false;
512
513                         let polled_best_block = polled_chain_tip.to_best_block();
514                         let polled_best_block_hash = polled_best_block.block_hash();
515                         let chain_params =
516                                 ChainParameters { network: args.network, best_block: polled_best_block };
517                         let fresh_channel_manager = channelmanager::ChannelManager::new(
518                                 fee_estimator.clone(),
519                                 chain_monitor.clone(),
520                                 broadcaster.clone(),
521                                 logger.clone(),
522                                 keys_manager.clone(),
523                                 user_config,
524                                 chain_params,
525                         );
526                         (polled_best_block_hash, fresh_channel_manager)
527                 }
528         };
529
530         // Step 10: Sync ChannelMonitors and ChannelManager to chain tip
531         let mut chain_listener_channel_monitors = Vec::new();
532         let mut cache = UnboundedCache::new();
533         let chain_tip = if restarting_node {
534                 let mut chain_listeners = vec![(
535                         channel_manager_blockhash,
536                         &channel_manager as &(dyn chain::Listen + Send + Sync),
537                 )];
538
539                 for (blockhash, channel_monitor) in channelmonitors.drain(..) {
540                         let outpoint = channel_monitor.get_funding_txo().0;
541                         chain_listener_channel_monitors.push((
542                                 blockhash,
543                                 (channel_monitor, broadcaster.clone(), fee_estimator.clone(), logger.clone()),
544                                 outpoint,
545                         ));
546                 }
547
548                 for monitor_listener_info in chain_listener_channel_monitors.iter_mut() {
549                         chain_listeners.push((
550                                 monitor_listener_info.0,
551                                 &monitor_listener_info.1 as &(dyn chain::Listen + Send + Sync),
552                         ));
553                 }
554
555                 init::synchronize_listeners(
556                         bitcoind_client.as_ref(),
557                         args.network,
558                         &mut cache,
559                         chain_listeners,
560                 )
561                 .await
562                 .unwrap()
563         } else {
564                 polled_chain_tip
565         };
566
567         // Step 11: Give ChannelMonitors to ChainMonitor
568         for item in chain_listener_channel_monitors.drain(..) {
569                 let channel_monitor = item.1 .0;
570                 let funding_outpoint = item.2;
571                 assert_eq!(
572                         chain_monitor.watch_channel(funding_outpoint, channel_monitor),
573                         ChannelMonitorUpdateStatus::Completed
574                 );
575         }
576
577         // Step 12: Optional: Initialize the P2PGossipSync
578         let genesis = genesis_block(args.network).header.block_hash();
579         let network_graph_path = format!("{}/network_graph", ldk_data_dir.clone());
580         let network_graph =
581                 Arc::new(disk::read_network(Path::new(&network_graph_path), genesis, logger.clone()));
582         let gossip_sync = Arc::new(P2PGossipSync::new(
583                 Arc::clone(&network_graph),
584                 None::<Arc<dyn chain::Access + Send + Sync>>,
585                 logger.clone(),
586         ));
587
588         // Step 13: Initialize the PeerManager
589         let channel_manager: Arc<ChannelManager> = Arc::new(channel_manager);
590         let onion_messenger: Arc<OnionMessenger> = Arc::new(OnionMessenger::new(
591                 Arc::clone(&keys_manager),
592                 Arc::clone(&logger),
593                 IgnoringMessageHandler {},
594         ));
595         let mut ephemeral_bytes = [0; 32];
596         let current_time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
597         rand::thread_rng().fill_bytes(&mut ephemeral_bytes);
598         let lightning_msg_handler = MessageHandler {
599                 chan_handler: channel_manager.clone(),
600                 route_handler: gossip_sync.clone(),
601                 onion_message_handler: onion_messenger.clone(),
602         };
603         let peer_manager: Arc<PeerManager> = Arc::new(PeerManager::new(
604                 lightning_msg_handler,
605                 keys_manager.get_node_secret(Recipient::Node).unwrap(),
606                 current_time.try_into().unwrap(),
607                 &ephemeral_bytes,
608                 logger.clone(),
609                 IgnoringMessageHandler {},
610         ));
611
612         // ## Running LDK
613         // Step 14: Initialize networking
614
615         let peer_manager_connection_handler = peer_manager.clone();
616         let listening_port = args.ldk_peer_listening_port;
617         let stop_listen_connect = Arc::new(AtomicBool::new(false));
618         let stop_listen = Arc::clone(&stop_listen_connect);
619         tokio::spawn(async move {
620                 let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", listening_port))
621                         .await
622                         .expect("Failed to bind to listen port - is something else already listening on it?");
623                 loop {
624                         let peer_mgr = peer_manager_connection_handler.clone();
625                         let tcp_stream = listener.accept().await.unwrap().0;
626                         if stop_listen.load(Ordering::Acquire) {
627                                 return;
628                         }
629                         tokio::spawn(async move {
630                                 lightning_net_tokio::setup_inbound(
631                                         peer_mgr.clone(),
632                                         tcp_stream.into_std().unwrap(),
633                                 )
634                                 .await;
635                         });
636                 }
637         });
638
639         // Step 15: Connect and Disconnect Blocks
640         let channel_manager_listener = channel_manager.clone();
641         let chain_monitor_listener = chain_monitor.clone();
642         let bitcoind_block_source = bitcoind_client.clone();
643         let network = args.network;
644         tokio::spawn(async move {
645                 let chain_poller = poll::ChainPoller::new(bitcoind_block_source.as_ref(), network);
646                 let chain_listener = (chain_monitor_listener, channel_manager_listener);
647                 let mut spv_client = SpvClient::new(chain_tip, chain_poller, &mut cache, &chain_listener);
648                 loop {
649                         spv_client.poll_best_tip().await.unwrap();
650                         tokio::time::sleep(Duration::from_secs(1)).await;
651                 }
652         });
653
654         // Step 16: Handle LDK Events
655         let channel_manager_event_listener = channel_manager.clone();
656         let keys_manager_listener = keys_manager.clone();
657         // TODO: persist payment info to disk
658         let inbound_payments: PaymentInfoStorage = Arc::new(Mutex::new(HashMap::new()));
659         let outbound_payments: PaymentInfoStorage = Arc::new(Mutex::new(HashMap::new()));
660         let inbound_pmts_for_events = inbound_payments.clone();
661         let outbound_pmts_for_events = outbound_payments.clone();
662         let network = args.network;
663         let bitcoind_rpc = bitcoind_client.clone();
664         let network_graph_events = network_graph.clone();
665         let handle = tokio::runtime::Handle::current();
666         let event_handler = move |event: Event| {
667                 handle.block_on(handle_ldk_events(
668                         &channel_manager_event_listener,
669                         &bitcoind_rpc,
670                         &network_graph_events,
671                         &keys_manager_listener,
672                         &inbound_pmts_for_events,
673                         &outbound_pmts_for_events,
674                         network,
675                         &event,
676                 ));
677         };
678
679         // Step 17: Initialize routing ProbabilisticScorer
680         let scorer_path = format!("{}/scorer", ldk_data_dir.clone());
681         let scorer = Arc::new(Mutex::new(disk::read_scorer(
682                 Path::new(&scorer_path),
683                 Arc::clone(&network_graph),
684                 Arc::clone(&logger),
685         )));
686
687         // Step 18: Create InvoicePayer
688         let router = DefaultRouter::new(
689                 network_graph.clone(),
690                 logger.clone(),
691                 keys_manager.get_secure_random_bytes(),
692                 scorer.clone(),
693         );
694         let invoice_payer = Arc::new(InvoicePayer::new(
695                 channel_manager.clone(),
696                 router,
697                 logger.clone(),
698                 event_handler,
699                 payment::Retry::Timeout(Duration::from_secs(10)),
700         ));
701
702         // Step 19: Persist ChannelManager and NetworkGraph
703         let persister = Arc::new(FilesystemPersister::new(ldk_data_dir.clone()));
704
705         // Step 20: Background Processing
706         let background_processor = BackgroundProcessor::start(
707                 persister,
708                 invoice_payer.clone(),
709                 chain_monitor.clone(),
710                 channel_manager.clone(),
711                 GossipSync::p2p(gossip_sync.clone()),
712                 peer_manager.clone(),
713                 logger.clone(),
714                 Some(scorer.clone()),
715         );
716
717         // Regularly reconnect to channel peers.
718         let connect_cm = Arc::clone(&channel_manager);
719         let connect_pm = Arc::clone(&peer_manager);
720         let peer_data_path = format!("{}/channel_peer_data", ldk_data_dir.clone());
721         let stop_connect = Arc::clone(&stop_listen_connect);
722         tokio::spawn(async move {
723                 let mut interval = tokio::time::interval(Duration::from_secs(1));
724                 loop {
725                         interval.tick().await;
726                         match disk::read_channel_peer_data(Path::new(&peer_data_path)) {
727                                 Ok(info) => {
728                                         let peers = connect_pm.get_peer_node_ids();
729                                         for node_id in connect_cm
730                                                 .list_channels()
731                                                 .iter()
732                                                 .map(|chan| chan.counterparty.node_id)
733                                                 .filter(|id| !peers.contains(id))
734                                         {
735                                                 if stop_connect.load(Ordering::Acquire) {
736                                                         return;
737                                                 }
738                                                 for (pubkey, peer_addr) in info.iter() {
739                                                         if *pubkey == node_id {
740                                                                 let _ = cli::do_connect_peer(
741                                                                         *pubkey,
742                                                                         peer_addr.clone(),
743                                                                         Arc::clone(&connect_pm),
744                                                                 )
745                                                                 .await;
746                                                         }
747                                                 }
748                                         }
749                                 }
750                                 Err(e) => println!("ERROR: errored reading channel peer info from disk: {:?}", e),
751                         }
752                 }
753         });
754
755         // Regularly broadcast our node_announcement. This is only required (or possible) if we have
756         // some public channels, and is only useful if we have public listen address(es) to announce.
757         // In a production environment, this should occur only after the announcement of new channels
758         // to avoid churn in the global network graph.
759         let peer_man = Arc::clone(&peer_manager);
760         let network = args.network;
761         if !args.ldk_announced_listen_addr.is_empty() {
762                 tokio::spawn(async move {
763                         let mut interval = tokio::time::interval(Duration::from_secs(60));
764                         loop {
765                                 interval.tick().await;
766                                 peer_man.broadcast_node_announcement(
767                                         [0; 3],
768                                         args.ldk_announced_node_name,
769                                         args.ldk_announced_listen_addr.clone(),
770                                 );
771                         }
772                 });
773         }
774
775         // Start the CLI.
776         cli::poll_for_user_input(
777                 Arc::clone(&invoice_payer),
778                 Arc::clone(&peer_manager),
779                 Arc::clone(&channel_manager),
780                 Arc::clone(&keys_manager),
781                 Arc::clone(&network_graph),
782                 Arc::clone(&onion_messenger),
783                 inbound_payments,
784                 outbound_payments,
785                 ldk_data_dir.clone(),
786                 network,
787                 Arc::clone(&logger),
788         )
789         .await;
790
791         // Disconnect our peers and stop accepting new connections. This ensures we don't continue
792         // updating our channel data after we've stopped the background processor.
793         stop_listen_connect.store(true, Ordering::Release);
794         peer_manager.disconnect_all_peers();
795
796         // Stop the background processor.
797         background_processor.stop().unwrap();
798 }
799
800 #[tokio::main]
801 pub async fn main() {
802         #[cfg(not(target_os = "windows"))]
803         {
804                 // Catch Ctrl-C with a dummy signal handler.
805                 unsafe {
806                         let mut new_action: libc::sigaction = core::mem::zeroed();
807                         let mut old_action: libc::sigaction = core::mem::zeroed();
808
809                         extern "C" fn dummy_handler(
810                                 _: libc::c_int, _: *const libc::siginfo_t, _: *const libc::c_void,
811                         ) {
812                         }
813
814                         new_action.sa_sigaction = dummy_handler as libc::sighandler_t;
815                         new_action.sa_flags = libc::SA_SIGINFO;
816
817                         libc::sigaction(
818                                 libc::SIGINT,
819                                 &new_action as *const libc::sigaction,
820                                 &mut old_action as *mut libc::sigaction,
821                         );
822                 }
823         }
824
825         start_ldk().await;
826 }