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::scoring::ProbabilisticScorer;
32 use lightning::util::config::UserConfig;
33 use lightning::util::events::{Event, PaymentPurpose};
34 use lightning::util::ser::ReadableArgs;
35 use lightning_background_processor::{BackgroundProcessor, GossipSync};
36 use lightning_block_sync::init;
37 use lightning_block_sync::poll;
38 use lightning_block_sync::SpvClient;
39 use lightning_block_sync::UnboundedCache;
40 use lightning_invoice::payment;
41 use lightning_invoice::utils::DefaultRouter;
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::PaymentReceived { payment_hash, purpose, amount_msat } => {
175 "\nEVENT: received payment from payment hash {} of {} millisatoshis",
176 hex_utils::hex_str(&payment_hash.0),
180 io::stdout().flush().unwrap();
181 let payment_preimage = match purpose {
182 PaymentPurpose::InvoicePayment { payment_preimage, .. } => *payment_preimage,
183 PaymentPurpose::SpontaneousPayment(preimage) => Some(*preimage),
185 channel_manager.claim_funds(payment_preimage.unwrap());
187 Event::PaymentClaimed { payment_hash, purpose, amount_msat } => {
189 "\nEVENT: claimed payment from payment hash {} of {} millisatoshis",
190 hex_utils::hex_str(&payment_hash.0),
194 io::stdout().flush().unwrap();
195 let (payment_preimage, payment_secret) = match purpose {
196 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
197 (*payment_preimage, Some(*payment_secret))
199 PaymentPurpose::SpontaneousPayment(preimage) => (Some(*preimage), None),
201 let mut payments = inbound_payments.lock().unwrap();
202 match payments.entry(*payment_hash) {
203 Entry::Occupied(mut e) => {
204 let payment = e.get_mut();
205 payment.status = HTLCStatus::Succeeded;
206 payment.preimage = payment_preimage;
207 payment.secret = payment_secret;
209 Entry::Vacant(e) => {
210 e.insert(PaymentInfo {
211 preimage: payment_preimage,
212 secret: payment_secret,
213 status: HTLCStatus::Succeeded,
214 amt_msat: MillisatAmount(Some(*amount_msat)),
219 Event::PaymentSent { payment_preimage, payment_hash, fee_paid_msat, .. } => {
220 let mut payments = outbound_payments.lock().unwrap();
221 for (hash, payment) in payments.iter_mut() {
222 if *hash == *payment_hash {
223 payment.preimage = Some(*payment_preimage);
224 payment.status = HTLCStatus::Succeeded;
226 "\nEVENT: successfully sent payment of {} millisatoshis{} from \
227 payment hash {:?} with preimage {:?}",
229 if let Some(fee) = fee_paid_msat {
230 format!(" (fee {} msat)", fee)
234 hex_utils::hex_str(&payment_hash.0),
235 hex_utils::hex_str(&payment_preimage.0)
238 io::stdout().flush().unwrap();
242 Event::OpenChannelRequest { .. } => {
243 // Unreachable, we don't set manually_accept_inbound_channels
245 Event::PaymentPathSuccessful { .. } => {}
246 Event::PaymentPathFailed { .. } => {}
247 Event::ProbeSuccessful { .. } => {}
248 Event::ProbeFailed { .. } => {}
249 Event::PaymentFailed { payment_hash, .. } => {
251 "\nEVENT: Failed to send payment to payment hash {:?}: exhausted payment retry attempts",
252 hex_utils::hex_str(&payment_hash.0)
255 io::stdout().flush().unwrap();
257 let mut payments = outbound_payments.lock().unwrap();
258 if payments.contains_key(&payment_hash) {
259 let payment = payments.get_mut(&payment_hash).unwrap();
260 payment.status = HTLCStatus::Failed;
263 Event::PaymentForwarded {
267 claim_from_onchain_tx,
269 let read_only_network_graph = network_graph.read_only();
270 let nodes = read_only_network_graph.nodes();
271 let channels = channel_manager.list_channels();
273 let node_str = |channel_id: &Option<[u8; 32]>| match channel_id {
274 None => String::new(),
275 Some(channel_id) => match channels.iter().find(|c| c.channel_id == *channel_id) {
276 None => String::new(),
278 match nodes.get(&NodeId::from_pubkey(&channel.counterparty.node_id)) {
279 None => "private node".to_string(),
280 Some(node) => match &node.announcement_info {
281 None => "unnamed node".to_string(),
282 Some(announcement) => {
283 format!("node {}", announcement.alias)
290 let channel_str = |channel_id: &Option<[u8; 32]>| {
292 .map(|channel_id| format!(" with channel {}", hex_utils::hex_str(&channel_id)))
296 format!(" from {}{}", node_str(prev_channel_id), channel_str(prev_channel_id));
298 format!(" to {}{}", node_str(next_channel_id), channel_str(next_channel_id));
300 let from_onchain_str = if *claim_from_onchain_tx {
301 "from onchain downstream claim"
303 "from HTLC fulfill message"
305 if let Some(fee_earned) = fee_earned_msat {
307 "\nEVENT: Forwarded payment{}{}, earning {} msat {}",
308 from_prev_str, to_next_str, fee_earned, from_onchain_str
312 "\nEVENT: Forwarded payment{}{}, claiming onchain {}",
313 from_prev_str, to_next_str, from_onchain_str
317 io::stdout().flush().unwrap();
319 Event::HTLCHandlingFailed { .. } => {}
320 Event::PendingHTLCsForwardable { time_forwardable } => {
321 let forwarding_channel_manager = channel_manager.clone();
322 let min = time_forwardable.as_millis() as u64;
323 tokio::spawn(async move {
324 let millis_to_sleep = thread_rng().gen_range(min, min * 5) as u64;
325 tokio::time::sleep(Duration::from_millis(millis_to_sleep)).await;
326 forwarding_channel_manager.process_pending_htlc_forwards();
329 Event::SpendableOutputs { outputs } => {
330 let destination_address = bitcoind_client.get_new_address().await;
331 let output_descriptors = &outputs.iter().map(|a| a).collect::<Vec<_>>();
333 bitcoind_client.get_est_sat_per_1000_weight(ConfirmationTarget::Normal);
334 let spending_tx = keys_manager
335 .spend_spendable_outputs(
338 destination_address.script_pubkey(),
343 bitcoind_client.broadcast_transaction(&spending_tx);
345 Event::ChannelClosed { channel_id, reason, user_channel_id: _ } => {
347 "\nEVENT: Channel {} closed due to: {:?}",
348 hex_utils::hex_str(channel_id),
352 io::stdout().flush().unwrap();
354 Event::DiscardFunding { .. } => {
355 // A "real" node should probably "lock" the UTXOs spent in funding transactions until
356 // the funding transaction either confirms, or this event is generated.
361 async fn start_ldk() {
362 let args = match args::parse_startup_args() {
363 Ok(user_args) => user_args,
367 // Initialize the LDK data directory if necessary.
368 let ldk_data_dir = format!("{}/.ldk", args.ldk_storage_dir_path);
369 fs::create_dir_all(ldk_data_dir.clone()).unwrap();
371 // Initialize our bitcoind client.
372 let bitcoind_client = match BitcoindClient::new(
373 args.bitcoind_rpc_host.clone(),
374 args.bitcoind_rpc_port,
375 args.bitcoind_rpc_username.clone(),
376 args.bitcoind_rpc_password.clone(),
377 tokio::runtime::Handle::current(),
381 Ok(client) => Arc::new(client),
383 println!("Failed to connect to bitcoind client: {}", e);
388 // Check that the bitcoind we've connected to is running the network we expect
389 let bitcoind_chain = bitcoind_client.get_blockchain_info().await.chain;
391 != match args.network {
392 bitcoin::Network::Bitcoin => "main",
393 bitcoin::Network::Testnet => "test",
394 bitcoin::Network::Regtest => "regtest",
395 bitcoin::Network::Signet => "signet",
398 "Chain argument ({}) didn't match bitcoind chain ({})",
399 args.network, bitcoind_chain
405 // Step 1: Initialize the FeeEstimator
407 // BitcoindClient implements the FeeEstimator trait, so it'll act as our fee estimator.
408 let fee_estimator = bitcoind_client.clone();
410 // Step 2: Initialize the Logger
411 let logger = Arc::new(FilesystemLogger::new(ldk_data_dir.clone()));
413 // Step 3: Initialize the BroadcasterInterface
415 // BitcoindClient implements the BroadcasterInterface trait, so it'll act as our transaction
417 let broadcaster = bitcoind_client.clone();
419 // Step 4: Initialize Persist
420 let persister = Arc::new(FilesystemPersister::new(ldk_data_dir.clone()));
422 // Step 5: Initialize the ChainMonitor
423 let chain_monitor: Arc<ChainMonitor> = Arc::new(chainmonitor::ChainMonitor::new(
427 fee_estimator.clone(),
431 // Step 6: Initialize the KeysManager
433 // The key seed that we use to derive the node privkey (that corresponds to the node pubkey) and
434 // other secret key material.
435 let keys_seed_path = format!("{}/keys_seed", ldk_data_dir.clone());
436 let keys_seed = if let Ok(seed) = fs::read(keys_seed_path.clone()) {
437 assert_eq!(seed.len(), 32);
438 let mut key = [0; 32];
439 key.copy_from_slice(&seed);
442 let mut key = [0; 32];
443 thread_rng().fill_bytes(&mut key);
444 match File::create(keys_seed_path.clone()) {
446 f.write_all(&key).expect("Failed to write node keys seed to disk");
447 f.sync_all().expect("Failed to sync node keys seed to disk");
450 println!("ERROR: Unable to create keys seed file {}: {}", keys_seed_path, e);
456 let cur = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
457 let keys_manager = Arc::new(KeysManager::new(&keys_seed, cur.as_secs(), cur.subsec_nanos()));
459 // Step 7: Read ChannelMonitor state from disk
460 let mut channelmonitors = persister.read_channelmonitors(keys_manager.clone()).unwrap();
462 // Step 8: Poll for the best chain tip, which may be used by the channel manager & spv client
463 let polled_chain_tip = init::validate_best_block_header(bitcoind_client.as_ref())
465 .expect("Failed to fetch best block header and best block");
467 // Step 9: Initialize the ChannelManager
468 let mut user_config = UserConfig::default();
469 user_config.channel_handshake_limits.force_announced_channel_preference = false;
470 let mut restarting_node = true;
471 let (channel_manager_blockhash, channel_manager) = {
472 if let Ok(mut f) = fs::File::open(format!("{}/manager", ldk_data_dir.clone())) {
473 let mut channel_monitor_mut_references = Vec::new();
474 for (_, channel_monitor) in channelmonitors.iter_mut() {
475 channel_monitor_mut_references.push(channel_monitor);
477 let read_args = ChannelManagerReadArgs::new(
478 keys_manager.clone(),
479 fee_estimator.clone(),
480 chain_monitor.clone(),
484 channel_monitor_mut_references,
486 <(BlockHash, ChannelManager)>::read(&mut f, read_args).unwrap()
488 // We're starting a fresh node.
489 restarting_node = false;
491 let polled_best_block = polled_chain_tip.to_best_block();
492 let polled_best_block_hash = polled_best_block.block_hash();
494 ChainParameters { network: args.network, best_block: polled_best_block };
495 let fresh_channel_manager = channelmanager::ChannelManager::new(
496 fee_estimator.clone(),
497 chain_monitor.clone(),
500 keys_manager.clone(),
504 (polled_best_block_hash, fresh_channel_manager)
508 // Step 10: Sync ChannelMonitors and ChannelManager to chain tip
509 let mut chain_listener_channel_monitors = Vec::new();
510 let mut cache = UnboundedCache::new();
511 let chain_tip = if restarting_node {
512 let mut chain_listeners = vec![(
513 channel_manager_blockhash,
514 &channel_manager as &(dyn chain::Listen + Send + Sync),
517 for (blockhash, channel_monitor) in channelmonitors.drain(..) {
518 let outpoint = channel_monitor.get_funding_txo().0;
519 chain_listener_channel_monitors.push((
521 (channel_monitor, broadcaster.clone(), fee_estimator.clone(), logger.clone()),
526 for monitor_listener_info in chain_listener_channel_monitors.iter_mut() {
527 chain_listeners.push((
528 monitor_listener_info.0,
529 &monitor_listener_info.1 as &(dyn chain::Listen + Send + Sync),
533 init::synchronize_listeners(
534 bitcoind_client.as_ref(),
545 // Step 11: Give ChannelMonitors to ChainMonitor
546 for item in chain_listener_channel_monitors.drain(..) {
547 let channel_monitor = item.1 .0;
548 let funding_outpoint = item.2;
550 chain_monitor.watch_channel(funding_outpoint, channel_monitor),
551 ChannelMonitorUpdateStatus::Completed
555 // Step 12: Optional: Initialize the P2PGossipSync
556 let genesis = genesis_block(args.network).header.block_hash();
557 let network_graph_path = format!("{}/network_graph", ldk_data_dir.clone());
559 Arc::new(disk::read_network(Path::new(&network_graph_path), genesis, logger.clone()));
560 let gossip_sync = Arc::new(P2PGossipSync::new(
561 Arc::clone(&network_graph),
562 None::<Arc<dyn chain::Access + Send + Sync>>,
566 // Step 13: Initialize the PeerManager
567 let channel_manager: Arc<ChannelManager> = Arc::new(channel_manager);
568 let onion_messenger: Arc<OnionMessenger> = Arc::new(OnionMessenger::new(
569 Arc::clone(&keys_manager),
571 IgnoringMessageHandler {},
573 let mut ephemeral_bytes = [0; 32];
574 let current_time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
575 rand::thread_rng().fill_bytes(&mut ephemeral_bytes);
576 let lightning_msg_handler = MessageHandler {
577 chan_handler: channel_manager.clone(),
578 route_handler: gossip_sync.clone(),
579 onion_message_handler: onion_messenger.clone(),
581 let peer_manager: Arc<PeerManager> = Arc::new(PeerManager::new(
582 lightning_msg_handler,
583 keys_manager.get_node_secret(Recipient::Node).unwrap(),
584 current_time.try_into().unwrap(),
587 IgnoringMessageHandler {},
591 // Step 14: Initialize networking
593 let peer_manager_connection_handler = peer_manager.clone();
594 let listening_port = args.ldk_peer_listening_port;
595 let stop_listen_connect = Arc::new(AtomicBool::new(false));
596 let stop_listen = Arc::clone(&stop_listen_connect);
597 tokio::spawn(async move {
598 let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", listening_port))
600 .expect("Failed to bind to listen port - is something else already listening on it?");
602 let peer_mgr = peer_manager_connection_handler.clone();
603 let tcp_stream = listener.accept().await.unwrap().0;
604 if stop_listen.load(Ordering::Acquire) {
607 tokio::spawn(async move {
608 lightning_net_tokio::setup_inbound(
610 tcp_stream.into_std().unwrap(),
617 // Step 15: Connect and Disconnect Blocks
618 let channel_manager_listener = channel_manager.clone();
619 let chain_monitor_listener = chain_monitor.clone();
620 let bitcoind_block_source = bitcoind_client.clone();
621 let network = args.network;
622 tokio::spawn(async move {
623 let chain_poller = poll::ChainPoller::new(bitcoind_block_source.as_ref(), network);
624 let chain_listener = (chain_monitor_listener, channel_manager_listener);
625 let mut spv_client = SpvClient::new(chain_tip, chain_poller, &mut cache, &chain_listener);
627 spv_client.poll_best_tip().await.unwrap();
628 tokio::time::sleep(Duration::from_secs(1)).await;
632 // Step 16: Handle LDK Events
633 let channel_manager_event_listener = channel_manager.clone();
634 let keys_manager_listener = keys_manager.clone();
635 // TODO: persist payment info to disk
636 let inbound_payments: PaymentInfoStorage = Arc::new(Mutex::new(HashMap::new()));
637 let outbound_payments: PaymentInfoStorage = Arc::new(Mutex::new(HashMap::new()));
638 let inbound_pmts_for_events = inbound_payments.clone();
639 let outbound_pmts_for_events = outbound_payments.clone();
640 let network = args.network;
641 let bitcoind_rpc = bitcoind_client.clone();
642 let network_graph_events = network_graph.clone();
643 let handle = tokio::runtime::Handle::current();
644 let event_handler = move |event: &Event| {
645 handle.block_on(handle_ldk_events(
646 &channel_manager_event_listener,
648 &network_graph_events,
649 &keys_manager_listener,
650 &inbound_pmts_for_events,
651 &outbound_pmts_for_events,
657 // Step 17: Initialize routing ProbabilisticScorer
658 let scorer_path = format!("{}/scorer", ldk_data_dir.clone());
659 let scorer = Arc::new(Mutex::new(disk::read_scorer(
660 Path::new(&scorer_path),
661 Arc::clone(&network_graph),
665 // Step 18: Create InvoicePayer
666 let router = DefaultRouter::new(
667 network_graph.clone(),
669 keys_manager.get_secure_random_bytes(),
672 let invoice_payer = Arc::new(InvoicePayer::new(
673 channel_manager.clone(),
677 payment::Retry::Timeout(Duration::from_secs(10)),
680 // Step 19: Persist ChannelManager and NetworkGraph
681 let persister = Arc::new(FilesystemPersister::new(ldk_data_dir.clone()));
683 // Step 20: Background Processing
684 let background_processor = BackgroundProcessor::start(
686 invoice_payer.clone(),
687 chain_monitor.clone(),
688 channel_manager.clone(),
689 GossipSync::p2p(gossip_sync.clone()),
690 peer_manager.clone(),
692 Some(scorer.clone()),
695 // Regularly reconnect to channel peers.
696 let connect_cm = Arc::clone(&channel_manager);
697 let connect_pm = Arc::clone(&peer_manager);
698 let peer_data_path = format!("{}/channel_peer_data", ldk_data_dir.clone());
699 let stop_connect = Arc::clone(&stop_listen_connect);
700 tokio::spawn(async move {
701 let mut interval = tokio::time::interval(Duration::from_secs(1));
703 interval.tick().await;
704 match disk::read_channel_peer_data(Path::new(&peer_data_path)) {
706 let peers = connect_pm.get_peer_node_ids();
707 for node_id in connect_cm
710 .map(|chan| chan.counterparty.node_id)
711 .filter(|id| !peers.contains(id))
713 if stop_connect.load(Ordering::Acquire) {
716 for (pubkey, peer_addr) in info.iter() {
717 if *pubkey == node_id {
718 let _ = cli::do_connect_peer(
721 Arc::clone(&connect_pm),
728 Err(e) => println!("ERROR: errored reading channel peer info from disk: {:?}", e),
733 // Regularly broadcast our node_announcement. This is only required (or possible) if we have
734 // some public channels, and is only useful if we have public listen address(es) to announce.
735 // In a production environment, this should occur only after the announcement of new channels
736 // to avoid churn in the global network graph.
737 let peer_man = Arc::clone(&peer_manager);
738 let network = args.network;
739 if !args.ldk_announced_listen_addr.is_empty() {
740 tokio::spawn(async move {
741 let mut interval = tokio::time::interval(Duration::from_secs(60));
743 interval.tick().await;
744 peer_man.broadcast_node_announcement(
746 args.ldk_announced_node_name,
747 args.ldk_announced_listen_addr.clone(),
754 cli::poll_for_user_input(
755 Arc::clone(&invoice_payer),
756 Arc::clone(&peer_manager),
757 Arc::clone(&channel_manager),
758 Arc::clone(&keys_manager),
759 Arc::clone(&network_graph),
760 Arc::clone(&onion_messenger),
763 ldk_data_dir.clone(),
769 // Disconnect our peers and stop accepting new connections. This ensures we don't continue
770 // updating our channel data after we've stopped the background processor.
771 stop_listen_connect.store(true, Ordering::Release);
772 peer_manager.disconnect_all_peers();
774 // Stop the background processor.
775 background_processor.stop().unwrap();
779 pub async fn main() {
780 #[cfg(not(target_os = "windows"))]
782 // Catch Ctrl-C with a dummy signal handler.
784 let mut new_action: libc::sigaction = core::mem::zeroed();
785 let mut old_action: libc::sigaction = core::mem::zeroed();
787 extern "C" fn dummy_handler(
788 _: libc::c_int, _: *const libc::siginfo_t, _: *const libc::c_void,
792 new_action.sa_sigaction = dummy_handler as libc::sighandler_t;
793 new_action.sa_flags = libc::SA_SIGINFO;
797 &new_action as *const libc::sigaction,
798 &mut old_action as *mut libc::sigaction,