2 pub mod bitcoind_client;
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;
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,
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;
51 use std::sync::atomic::{AtomicBool, Ordering};
52 use std::sync::{Arc, Mutex};
53 use std::time::{Duration, SystemTime};
55 pub(crate) enum HTLCStatus {
61 pub(crate) struct MillisatAmount(Option<u64>);
63 impl fmt::Display for MillisatAmount {
64 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
66 Some(amt) => write!(f, "{}", amt),
67 None => write!(f, "unknown"),
72 pub(crate) struct PaymentInfo {
73 preimage: Option<PaymentPreimage>,
74 secret: Option<PaymentSecret>,
76 amt_msat: MillisatAmount,
79 pub(crate) type PaymentInfoStorage = Arc<Mutex<HashMap<PaymentHash, PaymentInfo>>>;
81 type ChainMonitor = chainmonitor::ChainMonitor<
83 Arc<dyn Filter + Send + Sync>,
86 Arc<FilesystemLogger>,
87 Arc<FilesystemPersister>,
90 pub(crate) type PeerManager = SimpleArcPeerManager<
99 pub(crate) type ChannelManager =
100 SimpleArcChannelManager<ChainMonitor, BitcoindClient, BitcoindClient, FilesystemLogger>;
102 pub(crate) type NetworkGraph = gossip::NetworkGraph<Arc<FilesystemLogger>>;
104 type OnionMessenger = SimpleArcOnionMessenger<FilesystemLogger>;
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,
113 Event::FundingGenerationReady {
114 temporary_channel_id,
115 counterparty_node_id,
116 channel_value_satoshis,
120 // Construct the raw transaction with one output, that is paid the amount of the
122 let addr = WitnessProgram::from_scriptpubkey(
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,
131 .expect("Lightning funding tx should always be to a SegWit output")
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;
137 // Have your wallet put the inputs into the transaction such that the output is
139 let funded_tx = bitcoind_client.fund_raw_transaction(raw_tx).await;
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.
148 .funding_transaction_generated(
149 &temporary_channel_id,
150 counterparty_node_id,
156 "\nERROR: Channel went away before we could fund it. The peer disconnected or refused the channel.");
158 io::stdout().flush().unwrap();
161 Event::PaymentClaimable {
167 via_user_channel_id: _,
170 "\nEVENT: received payment from payment hash {} of {} millisatoshis",
171 hex_utils::hex_str(&payment_hash.0),
175 io::stdout().flush().unwrap();
176 let payment_preimage = match purpose {
177 PaymentPurpose::InvoicePayment { payment_preimage, .. } => *payment_preimage,
178 PaymentPurpose::SpontaneousPayment(preimage) => Some(*preimage),
180 channel_manager.claim_funds(payment_preimage.unwrap());
182 Event::PaymentClaimed { payment_hash, purpose, amount_msat, receiver_node_id: _ } => {
184 "\nEVENT: claimed payment from payment hash {} of {} millisatoshis",
185 hex_utils::hex_str(&payment_hash.0),
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))
194 PaymentPurpose::SpontaneousPayment(preimage) => (Some(*preimage), None),
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;
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)),
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;
221 "\nEVENT: successfully sent payment of {} millisatoshis{} from \
222 payment hash {:?} with preimage {:?}",
224 if let Some(fee) = fee_paid_msat {
225 format!(" (fee {} msat)", fee)
229 hex_utils::hex_str(&payment_hash.0),
230 hex_utils::hex_str(&payment_preimage.0)
233 io::stdout().flush().unwrap();
237 Event::OpenChannelRequest { .. } => {
238 // Unreachable, we don't set manually_accept_inbound_channels
240 Event::PaymentPathSuccessful { .. } => {}
241 Event::PaymentPathFailed { .. } => {}
242 Event::ProbeSuccessful { .. } => {}
243 Event::ProbeFailed { .. } => {}
244 Event::PaymentFailed { payment_hash, .. } => {
246 "\nEVENT: Failed to send payment to payment hash {:?}: exhausted payment retry attempts",
247 hex_utils::hex_str(&payment_hash.0)
250 io::stdout().flush().unwrap();
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;
258 Event::PaymentForwarded {
262 claim_from_onchain_tx,
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();
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(),
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)
285 let channel_str = |channel_id: &Option<[u8; 32]>| {
287 .map(|channel_id| format!(" with channel {}", hex_utils::hex_str(&channel_id)))
291 format!(" from {}{}", node_str(prev_channel_id), channel_str(prev_channel_id));
293 format!(" to {}{}", node_str(next_channel_id), channel_str(next_channel_id));
295 let from_onchain_str = if *claim_from_onchain_tx {
296 "from onchain downstream claim"
298 "from HTLC fulfill message"
300 if let Some(fee_earned) = fee_earned_msat {
302 "\nEVENT: Forwarded payment{}{}, earning {} msat {}",
303 from_prev_str, to_next_str, fee_earned, from_onchain_str
307 "\nEVENT: Forwarded payment{}{}, claiming onchain {}",
308 from_prev_str, to_next_str, from_onchain_str
312 io::stdout().flush().unwrap();
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();
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<_>>();
328 bitcoind_client.get_est_sat_per_1000_weight(ConfirmationTarget::Normal);
329 let spending_tx = keys_manager
330 .spend_spendable_outputs(
333 destination_address.script_pubkey(),
338 bitcoind_client.broadcast_transaction(&spending_tx);
340 Event::ChannelReady {
343 ref counterparty_node_id,
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()),
352 io::stdout().flush().unwrap();
354 Event::ChannelClosed { channel_id, reason, user_channel_id: _ } => {
356 "\nEVENT: Channel {} closed due to: {:?}",
357 hex_utils::hex_str(channel_id),
361 io::stdout().flush().unwrap();
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.
367 Event::HTLCIntercepted { .. } => {}
371 async fn start_ldk() {
372 let args = match args::parse_startup_args() {
373 Ok(user_args) => user_args,
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();
382 // Step 1: Initialize the Logger
383 let logger = Arc::new(FilesystemLogger::new(ldk_data_dir.clone()));
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(),
396 Ok(client) => Arc::new(client),
398 println!("Failed to connect to bitcoind client: {}", e);
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;
406 != match args.network {
407 bitcoin::Network::Bitcoin => "main",
408 bitcoin::Network::Testnet => "test",
409 bitcoin::Network::Regtest => "regtest",
410 bitcoin::Network::Signet => "signet",
413 "Chain argument ({}) didn't match bitcoind chain ({})",
414 args.network, bitcoind_chain
419 // Step 2: Initialize the FeeEstimator
421 // BitcoindClient implements the FeeEstimator trait, so it'll act as our fee estimator.
422 let fee_estimator = bitcoind_client.clone();
424 // Step 3: Initialize the BroadcasterInterface
426 // BitcoindClient implements the BroadcasterInterface trait, so it'll act as our transaction
428 let broadcaster = bitcoind_client.clone();
430 // Step 4: Initialize Persist
431 let persister = Arc::new(FilesystemPersister::new(ldk_data_dir.clone()));
433 // Step 5: Initialize the ChainMonitor
434 let chain_monitor: Arc<ChainMonitor> = Arc::new(chainmonitor::ChainMonitor::new(
438 fee_estimator.clone(),
442 // Step 6: Initialize the KeysManager
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);
453 let mut key = [0; 32];
454 thread_rng().fill_bytes(&mut key);
455 match File::create(keys_seed_path.clone()) {
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");
461 println!("ERROR: Unable to create keys seed file {}: {}", keys_seed_path, e);
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()));
470 // Step 7: Read ChannelMonitor state from disk
471 let mut channelmonitors =
472 persister.read_channelmonitors(keys_manager.clone(), keys_manager.clone()).unwrap();
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())
477 .expect("Failed to fetch best block header and best block");
479 // Step 9: Initialize routing ProbabilisticScorer
480 let network_graph_path = format!("{}/network_graph", ldk_data_dir.clone());
482 Arc::new(disk::read_network(Path::new(&network_graph_path), args.network, logger.clone()));
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),
491 // Step 10: Create Router
492 let router = Arc::new(DefaultRouter::new(
493 network_graph.clone(),
495 keys_manager.get_secure_random_bytes(),
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);
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(),
519 channel_monitor_mut_references,
521 <(BlockHash, ChannelManager)>::read(&mut f, read_args).unwrap()
523 // We're starting a fresh node.
524 restarting_node = false;
526 let polled_best_block = polled_chain_tip.to_best_block();
527 let polled_best_block_hash = polled_best_block.block_hash();
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(),
536 keys_manager.clone(),
537 keys_manager.clone(),
538 keys_manager.clone(),
542 (polled_best_block_hash, fresh_channel_manager)
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),
555 for (blockhash, channel_monitor) in channelmonitors.drain(..) {
556 let outpoint = channel_monitor.get_funding_txo().0;
557 chain_listener_channel_monitors.push((
559 (channel_monitor, broadcaster.clone(), fee_estimator.clone(), logger.clone()),
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),
571 init::synchronize_listeners(
572 bitcoind_client.as_ref(),
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;
588 chain_monitor.watch_channel(funding_outpoint, channel_monitor),
589 ChannelMonitorUpdateStatus::Completed
593 // Step 14: Optional: Initialize the P2PGossipSync
594 let gossip_sync = Arc::new(P2PGossipSync::new(
595 Arc::clone(&network_graph),
596 None::<Arc<BitcoindClient>>,
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),
606 IgnoringMessageHandler {},
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(),
616 let peer_manager: Arc<PeerManager> = Arc::new(PeerManager::new(
617 lightning_msg_handler,
618 current_time.try_into().unwrap(),
621 IgnoringMessageHandler {},
622 Arc::clone(&keys_manager),
626 // Step 16: Initialize networking
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))
635 .expect("Failed to bind to listen port - is something else already listening on it?");
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) {
642 tokio::spawn(async move {
643 lightning_net_tokio::setup_inbound(
645 tcp_stream.into_std().unwrap(),
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);
662 spv_client.poll_best_tip().await.unwrap();
663 tokio::time::sleep(Duration::from_secs(1)).await;
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,
683 &network_graph_events,
684 &keys_manager_listener,
685 &inbound_pmts_for_events,
686 &outbound_pmts_for_events,
692 // Step 19: Persist ChannelManager and NetworkGraph
693 let persister = Arc::new(FilesystemPersister::new(ldk_data_dir.clone()));
695 // Step 20: Background Processing
696 let background_processor = BackgroundProcessor::start(
699 chain_monitor.clone(),
700 channel_manager.clone(),
701 GossipSync::p2p(gossip_sync.clone()),
702 peer_manager.clone(),
704 Some(scorer.clone()),
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));
715 interval.tick().await;
716 match disk::read_channel_peer_data(Path::new(&peer_data_path)) {
718 let peers = connect_pm.get_peer_node_ids();
719 for node_id in connect_cm
722 .map(|chan| chan.counterparty.node_id)
723 .filter(|id| !peers.iter().any(|(pk, _)| id == pk))
725 if stop_connect.load(Ordering::Acquire) {
728 for (pubkey, peer_addr) in info.iter() {
729 if *pubkey == node_id {
730 let _ = cli::do_connect_peer(
733 Arc::clone(&connect_pm),
740 Err(e) => println!("ERROR: errored reading channel peer info from disk: {:?}", e),
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));
755 interval.tick().await;
756 peer_man.broadcast_node_announcement(
758 args.ldk_announced_node_name,
759 args.ldk_announced_listen_addr.clone(),
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),
774 ldk_data_dir.clone(),
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();
785 // Stop the background processor.
786 background_processor.stop().unwrap();
790 pub async fn main() {
791 #[cfg(not(target_os = "windows"))]
793 // Catch Ctrl-C with a dummy signal handler.
795 let mut new_action: libc::sigaction = core::mem::zeroed();
796 let mut old_action: libc::sigaction = core::mem::zeroed();
798 extern "C" fn dummy_handler(
799 _: libc::c_int, _: *const libc::siginfo_t, _: *const libc::c_void,
803 new_action.sa_sigaction = dummy_handler as libc::sighandler_t;
804 new_action.sa_flags = libc::SA_SIGINFO;
808 &new_action as *const libc::sigaction,
809 &mut old_action as *mut libc::sigaction,