2 pub mod bitcoind_client;
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;
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,
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;
54 use std::sync::atomic::{AtomicBool, Ordering};
55 use std::sync::{Arc, Mutex};
56 use std::time::{Duration, SystemTime};
58 pub(crate) enum HTLCStatus {
64 pub(crate) struct MillisatAmount(Option<u64>);
66 impl fmt::Display for MillisatAmount {
67 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
69 Some(amt) => write!(f, "{}", amt),
70 None => write!(f, "unknown"),
75 pub(crate) struct PaymentInfo {
76 preimage: Option<PaymentPreimage>,
77 secret: Option<PaymentSecret>,
79 amt_msat: MillisatAmount,
82 pub(crate) type PaymentInfoStorage = Arc<Mutex<HashMap<PaymentHash, PaymentInfo>>>;
84 type ChainMonitor = chainmonitor::ChainMonitor<
86 Arc<dyn Filter + Send + Sync>,
89 Arc<FilesystemLogger>,
90 Arc<FilesystemPersister>,
93 pub(crate) type PeerManager = SimpleArcPeerManager<
98 dyn chain::Access + Send + Sync,
102 pub(crate) type ChannelManager =
103 SimpleArcChannelManager<ChainMonitor, BitcoindClient, BitcoindClient, FilesystemLogger>;
105 pub(crate) type InvoicePayer<E> =
106 payment::InvoicePayer<Arc<ChannelManager>, Router, Arc<FilesystemLogger>, E>;
108 type Router = DefaultRouter<
110 Arc<FilesystemLogger>,
111 Arc<Mutex<ProbabilisticScorer<Arc<NetworkGraph>, Arc<FilesystemLogger>>>>,
114 pub(crate) type NetworkGraph = gossip::NetworkGraph<Arc<FilesystemLogger>>;
116 type OnionMessenger = SimpleArcOnionMessenger<FilesystemLogger>;
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,
125 Event::FundingGenerationReady {
126 temporary_channel_id,
127 counterparty_node_id,
128 channel_value_satoshis,
132 // Construct the raw transaction with one output, that is paid the amount of the
134 let addr = WitnessProgram::from_scriptpubkey(
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,
143 .expect("Lightning funding tx should always be to a SegWit output")
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;
149 // Have your wallet put the inputs into the transaction such that the output is
151 let funded_tx = bitcoind_client.fund_raw_transaction(raw_tx).await;
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.
160 .funding_transaction_generated(
161 &temporary_channel_id,
162 counterparty_node_id,
168 "\nERROR: Channel went away before we could fund it. The peer disconnected or refused the channel.");
170 io::stdout().flush().unwrap();
173 Event::PaymentClaimable {
179 via_user_channel_id: _,
182 "\nEVENT: received payment from payment hash {} of {} millisatoshis",
183 hex_utils::hex_str(&payment_hash.0),
187 io::stdout().flush().unwrap();
188 let payment_preimage = match purpose {
189 PaymentPurpose::InvoicePayment { payment_preimage, .. } => *payment_preimage,
190 PaymentPurpose::SpontaneousPayment(preimage) => Some(*preimage),
192 channel_manager.claim_funds(payment_preimage.unwrap());
194 Event::PaymentClaimed { payment_hash, purpose, amount_msat, receiver_node_id: _ } => {
196 "\nEVENT: claimed payment from payment hash {} of {} millisatoshis",
197 hex_utils::hex_str(&payment_hash.0),
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))
206 PaymentPurpose::SpontaneousPayment(preimage) => (Some(*preimage), None),
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;
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)),
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;
233 "\nEVENT: successfully sent payment of {} millisatoshis{} from \
234 payment hash {:?} with preimage {:?}",
236 if let Some(fee) = fee_paid_msat {
237 format!(" (fee {} msat)", fee)
241 hex_utils::hex_str(&payment_hash.0),
242 hex_utils::hex_str(&payment_preimage.0)
245 io::stdout().flush().unwrap();
249 Event::OpenChannelRequest { .. } => {
250 // Unreachable, we don't set manually_accept_inbound_channels
252 Event::PaymentPathSuccessful { .. } => {}
253 Event::PaymentPathFailed { .. } => {}
254 Event::ProbeSuccessful { .. } => {}
255 Event::ProbeFailed { .. } => {}
256 Event::PaymentFailed { payment_hash, .. } => {
258 "\nEVENT: Failed to send payment to payment hash {:?}: exhausted payment retry attempts",
259 hex_utils::hex_str(&payment_hash.0)
262 io::stdout().flush().unwrap();
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;
270 Event::PaymentForwarded {
274 claim_from_onchain_tx,
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();
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(),
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)
297 let channel_str = |channel_id: &Option<[u8; 32]>| {
299 .map(|channel_id| format!(" with channel {}", hex_utils::hex_str(&channel_id)))
303 format!(" from {}{}", node_str(prev_channel_id), channel_str(prev_channel_id));
305 format!(" to {}{}", node_str(next_channel_id), channel_str(next_channel_id));
307 let from_onchain_str = if *claim_from_onchain_tx {
308 "from onchain downstream claim"
310 "from HTLC fulfill message"
312 if let Some(fee_earned) = fee_earned_msat {
314 "\nEVENT: Forwarded payment{}{}, earning {} msat {}",
315 from_prev_str, to_next_str, fee_earned, from_onchain_str
319 "\nEVENT: Forwarded payment{}{}, claiming onchain {}",
320 from_prev_str, to_next_str, from_onchain_str
324 io::stdout().flush().unwrap();
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();
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<_>>();
340 bitcoind_client.get_est_sat_per_1000_weight(ConfirmationTarget::Normal);
341 let spending_tx = keys_manager
342 .spend_spendable_outputs(
345 destination_address.script_pubkey(),
350 bitcoind_client.broadcast_transaction(&spending_tx);
352 Event::ChannelReady {
355 ref counterparty_node_id,
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()),
364 io::stdout().flush().unwrap();
366 Event::ChannelClosed { channel_id, reason, user_channel_id: _ } => {
368 "\nEVENT: Channel {} closed due to: {:?}",
369 hex_utils::hex_str(channel_id),
373 io::stdout().flush().unwrap();
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.
379 Event::HTLCIntercepted { .. } => {}
383 async fn start_ldk() {
384 let args = match args::parse_startup_args() {
385 Ok(user_args) => user_args,
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();
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(),
403 Ok(client) => Arc::new(client),
405 println!("Failed to connect to bitcoind client: {}", e);
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;
413 != match args.network {
414 bitcoin::Network::Bitcoin => "main",
415 bitcoin::Network::Testnet => "test",
416 bitcoin::Network::Regtest => "regtest",
417 bitcoin::Network::Signet => "signet",
420 "Chain argument ({}) didn't match bitcoind chain ({})",
421 args.network, bitcoind_chain
427 // Step 1: Initialize the FeeEstimator
429 // BitcoindClient implements the FeeEstimator trait, so it'll act as our fee estimator.
430 let fee_estimator = bitcoind_client.clone();
432 // Step 2: Initialize the Logger
433 let logger = Arc::new(FilesystemLogger::new(ldk_data_dir.clone()));
435 // Step 3: Initialize the BroadcasterInterface
437 // BitcoindClient implements the BroadcasterInterface trait, so it'll act as our transaction
439 let broadcaster = bitcoind_client.clone();
441 // Step 4: Initialize Persist
442 let persister = Arc::new(FilesystemPersister::new(ldk_data_dir.clone()));
444 // Step 5: Initialize the ChainMonitor
445 let chain_monitor: Arc<ChainMonitor> = Arc::new(chainmonitor::ChainMonitor::new(
449 fee_estimator.clone(),
453 // Step 6: Initialize the KeysManager
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);
464 let mut key = [0; 32];
465 thread_rng().fill_bytes(&mut key);
466 match File::create(keys_seed_path.clone()) {
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");
472 println!("ERROR: Unable to create keys seed file {}: {}", keys_seed_path, e);
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()));
481 // Step 7: Read ChannelMonitor state from disk
482 let mut channelmonitors = persister.read_channelmonitors(keys_manager.clone()).unwrap();
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())
487 .expect("Failed to fetch best block header and best block");
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);
499 let read_args = ChannelManagerReadArgs::new(
500 keys_manager.clone(),
501 fee_estimator.clone(),
502 chain_monitor.clone(),
506 channel_monitor_mut_references,
508 <(BlockHash, ChannelManager)>::read(&mut f, read_args).unwrap()
510 // We're starting a fresh node.
511 restarting_node = false;
513 let polled_best_block = polled_chain_tip.to_best_block();
514 let polled_best_block_hash = polled_best_block.block_hash();
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(),
522 keys_manager.clone(),
526 (polled_best_block_hash, fresh_channel_manager)
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),
539 for (blockhash, channel_monitor) in channelmonitors.drain(..) {
540 let outpoint = channel_monitor.get_funding_txo().0;
541 chain_listener_channel_monitors.push((
543 (channel_monitor, broadcaster.clone(), fee_estimator.clone(), logger.clone()),
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),
555 init::synchronize_listeners(
556 bitcoind_client.as_ref(),
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;
572 chain_monitor.watch_channel(funding_outpoint, channel_monitor),
573 ChannelMonitorUpdateStatus::Completed
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());
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>>,
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),
593 IgnoringMessageHandler {},
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(),
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(),
609 IgnoringMessageHandler {},
613 // Step 14: Initialize networking
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))
622 .expect("Failed to bind to listen port - is something else already listening on it?");
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) {
629 tokio::spawn(async move {
630 lightning_net_tokio::setup_inbound(
632 tcp_stream.into_std().unwrap(),
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);
649 spv_client.poll_best_tip().await.unwrap();
650 tokio::time::sleep(Duration::from_secs(1)).await;
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,
670 &network_graph_events,
671 &keys_manager_listener,
672 &inbound_pmts_for_events,
673 &outbound_pmts_for_events,
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),
687 // Step 18: Create InvoicePayer
688 let router = DefaultRouter::new(
689 network_graph.clone(),
691 keys_manager.get_secure_random_bytes(),
694 let invoice_payer = Arc::new(InvoicePayer::new(
695 channel_manager.clone(),
699 payment::Retry::Timeout(Duration::from_secs(10)),
702 // Step 19: Persist ChannelManager and NetworkGraph
703 let persister = Arc::new(FilesystemPersister::new(ldk_data_dir.clone()));
705 // Step 20: Background Processing
706 let background_processor = BackgroundProcessor::start(
708 invoice_payer.clone(),
709 chain_monitor.clone(),
710 channel_manager.clone(),
711 GossipSync::p2p(gossip_sync.clone()),
712 peer_manager.clone(),
714 Some(scorer.clone()),
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));
725 interval.tick().await;
726 match disk::read_channel_peer_data(Path::new(&peer_data_path)) {
728 let peers = connect_pm.get_peer_node_ids();
729 for node_id in connect_cm
732 .map(|chan| chan.counterparty.node_id)
733 .filter(|id| !peers.contains(id))
735 if stop_connect.load(Ordering::Acquire) {
738 for (pubkey, peer_addr) in info.iter() {
739 if *pubkey == node_id {
740 let _ = cli::do_connect_peer(
743 Arc::clone(&connect_pm),
750 Err(e) => println!("ERROR: errored reading channel peer info from disk: {:?}", e),
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));
765 interval.tick().await;
766 peer_man.broadcast_node_announcement(
768 args.ldk_announced_node_name,
769 args.ldk_announced_listen_addr.clone(),
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),
785 ldk_data_dir.clone(),
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();
796 // Stop the background processor.
797 background_processor.stop().unwrap();
801 pub async fn main() {
802 #[cfg(not(target_os = "windows"))]
804 // Catch Ctrl-C with a dummy signal handler.
806 let mut new_action: libc::sigaction = core::mem::zeroed();
807 let mut old_action: libc::sigaction = core::mem::zeroed();
809 extern "C" fn dummy_handler(
810 _: libc::c_int, _: *const libc::siginfo_t, _: *const libc::c_void,
814 new_action.sa_sigaction = dummy_handler as libc::sighandler_t;
815 new_action.sa_flags = libc::SA_SIGINFO;
819 &new_action as *const libc::sigaction,
820 &mut old_action as *mut libc::sigaction,