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