1 pub mod bitcoind_client;
7 use crate::bitcoind_client::BitcoindClient;
8 use crate::disk::FilesystemLogger;
9 use bitcoin::blockdata::constants::genesis_block;
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::{InMemorySigner, KeysInterface, KeysManager, Recipient};
19 use lightning::chain::{chainmonitor, ChannelMonitorUpdateStatus};
20 use lightning::chain::{BestBlock, 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::scoring::ProbabilisticScorer;
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_invoice::payment;
40 use lightning_invoice::utils::DefaultRouter;
41 use lightning_net_tokio::SocketDescriptor;
42 use lightning_persister::FilesystemPersister;
43 use rand::{thread_rng, Rng};
44 use std::collections::hash_map::Entry;
45 use std::collections::HashMap;
46 use std::convert::TryInto;
53 use std::sync::atomic::{AtomicBool, Ordering};
54 use std::sync::{Arc, Mutex};
55 use std::time::{Duration, SystemTime};
57 pub(crate) enum HTLCStatus {
63 pub(crate) struct MillisatAmount(Option<u64>);
65 impl fmt::Display for MillisatAmount {
66 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
68 Some(amt) => write!(f, "{}", amt),
69 None => write!(f, "unknown"),
74 pub(crate) struct PaymentInfo {
75 preimage: Option<PaymentPreimage>,
76 secret: Option<PaymentSecret>,
78 amt_msat: MillisatAmount,
81 pub(crate) type PaymentInfoStorage = Arc<Mutex<HashMap<PaymentHash, PaymentInfo>>>;
83 type ChainMonitor = chainmonitor::ChainMonitor<
85 Arc<dyn Filter + Send + Sync>,
88 Arc<FilesystemLogger>,
89 Arc<FilesystemPersister>,
92 pub(crate) type PeerManager = SimpleArcPeerManager<
97 dyn chain::Access + Send + Sync,
101 pub(crate) type ChannelManager =
102 SimpleArcChannelManager<ChainMonitor, BitcoindClient, BitcoindClient, FilesystemLogger>;
104 pub(crate) type InvoicePayer<E> =
105 payment::InvoicePayer<Arc<ChannelManager>, Router, Arc<FilesystemLogger>, E>;
107 type Router = DefaultRouter<
109 Arc<FilesystemLogger>,
110 Arc<Mutex<ProbabilisticScorer<Arc<NetworkGraph>, Arc<FilesystemLogger>>>>,
113 pub(crate) type NetworkGraph = gossip::NetworkGraph<Arc<FilesystemLogger>>;
115 type OnionMessenger = SimpleArcOnionMessenger<FilesystemLogger>;
117 async fn handle_ldk_events(
118 channel_manager: &Arc<ChannelManager>, bitcoind_client: &BitcoindClient,
119 network_graph: &NetworkGraph, keys_manager: &KeysManager,
120 inbound_payments: &PaymentInfoStorage, outbound_payments: &PaymentInfoStorage,
121 network: Network, event: &Event,
124 Event::FundingGenerationReady {
125 temporary_channel_id,
126 counterparty_node_id,
127 channel_value_satoshis,
131 // Construct the raw transaction with one output, that is paid the amount of the
133 let addr = WitnessProgram::from_scriptpubkey(
136 Network::Bitcoin => bitcoin_bech32::constants::Network::Bitcoin,
137 Network::Testnet => bitcoin_bech32::constants::Network::Testnet,
138 Network::Regtest => bitcoin_bech32::constants::Network::Regtest,
139 Network::Signet => bitcoin_bech32::constants::Network::Signet,
142 .expect("Lightning funding tx should always be to a SegWit output")
144 let mut outputs = vec![HashMap::with_capacity(1)];
145 outputs[0].insert(addr, *channel_value_satoshis as f64 / 100_000_000.0);
146 let raw_tx = bitcoind_client.create_raw_transaction(outputs).await;
148 // Have your wallet put the inputs into the transaction such that the output is
150 let funded_tx = bitcoind_client.fund_raw_transaction(raw_tx).await;
152 // Sign the final funding transaction and broadcast it.
153 let signed_tx = bitcoind_client.sign_raw_transaction_with_wallet(funded_tx.hex).await;
154 assert_eq!(signed_tx.complete, true);
155 let final_tx: Transaction =
156 encode::deserialize(&hex_utils::to_vec(&signed_tx.hex).unwrap()).unwrap();
157 // Give the funding transaction back to LDK for opening the channel.
159 .funding_transaction_generated(
160 &temporary_channel_id,
161 counterparty_node_id,
167 "\nERROR: Channel went away before we could fund it. The peer disconnected or refused the channel.");
169 io::stdout().flush().unwrap();
172 Event::PaymentReceived { payment_hash, purpose, amount_msat } => {
174 "\nEVENT: received payment from payment hash {} of {} millisatoshis",
175 hex_utils::hex_str(&payment_hash.0),
179 io::stdout().flush().unwrap();
180 let payment_preimage = match purpose {
181 PaymentPurpose::InvoicePayment { payment_preimage, .. } => *payment_preimage,
182 PaymentPurpose::SpontaneousPayment(preimage) => Some(*preimage),
184 channel_manager.claim_funds(payment_preimage.unwrap());
186 Event::PaymentClaimed { payment_hash, purpose, amount_msat } => {
188 "\nEVENT: claimed payment from payment hash {} of {} millisatoshis",
189 hex_utils::hex_str(&payment_hash.0),
193 io::stdout().flush().unwrap();
194 let (payment_preimage, payment_secret) = match purpose {
195 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
196 (*payment_preimage, Some(*payment_secret))
198 PaymentPurpose::SpontaneousPayment(preimage) => (Some(*preimage), None),
200 let mut payments = inbound_payments.lock().unwrap();
201 match payments.entry(*payment_hash) {
202 Entry::Occupied(mut e) => {
203 let payment = e.get_mut();
204 payment.status = HTLCStatus::Succeeded;
205 payment.preimage = payment_preimage;
206 payment.secret = payment_secret;
208 Entry::Vacant(e) => {
209 e.insert(PaymentInfo {
210 preimage: payment_preimage,
211 secret: payment_secret,
212 status: HTLCStatus::Succeeded,
213 amt_msat: MillisatAmount(Some(*amount_msat)),
218 Event::PaymentSent { payment_preimage, payment_hash, fee_paid_msat, .. } => {
219 let mut payments = outbound_payments.lock().unwrap();
220 for (hash, payment) in payments.iter_mut() {
221 if *hash == *payment_hash {
222 payment.preimage = Some(*payment_preimage);
223 payment.status = HTLCStatus::Succeeded;
225 "\nEVENT: successfully sent payment of {} millisatoshis{} from \
226 payment hash {:?} with preimage {:?}",
228 if let Some(fee) = fee_paid_msat {
229 format!(" (fee {} msat)", fee)
233 hex_utils::hex_str(&payment_hash.0),
234 hex_utils::hex_str(&payment_preimage.0)
237 io::stdout().flush().unwrap();
241 Event::OpenChannelRequest { .. } => {
242 // Unreachable, we don't set manually_accept_inbound_channels
244 Event::PaymentPathSuccessful { .. } => {}
245 Event::PaymentPathFailed { .. } => {}
246 Event::ProbeSuccessful { .. } => {}
247 Event::ProbeFailed { .. } => {}
248 Event::PaymentFailed { payment_hash, .. } => {
250 "\nEVENT: Failed to send payment to payment hash {:?}: exhausted payment retry attempts",
251 hex_utils::hex_str(&payment_hash.0)
254 io::stdout().flush().unwrap();
256 let mut payments = outbound_payments.lock().unwrap();
257 if payments.contains_key(&payment_hash) {
258 let payment = payments.get_mut(&payment_hash).unwrap();
259 payment.status = HTLCStatus::Failed;
262 Event::PaymentForwarded {
266 claim_from_onchain_tx,
268 let read_only_network_graph = network_graph.read_only();
269 let nodes = read_only_network_graph.nodes();
270 let channels = channel_manager.list_channels();
272 let node_str = |channel_id: &Option<[u8; 32]>| match channel_id {
273 None => String::new(),
274 Some(channel_id) => match channels.iter().find(|c| c.channel_id == *channel_id) {
275 None => String::new(),
277 match nodes.get(&NodeId::from_pubkey(&channel.counterparty.node_id)) {
278 None => "private node".to_string(),
279 Some(node) => match &node.announcement_info {
280 None => "unnamed node".to_string(),
281 Some(announcement) => {
282 format!("node {}", announcement.alias)
289 let channel_str = |channel_id: &Option<[u8; 32]>| {
291 .map(|channel_id| format!(" with channel {}", hex_utils::hex_str(&channel_id)))
295 format!(" from {}{}", node_str(prev_channel_id), channel_str(prev_channel_id));
297 format!(" to {}{}", node_str(next_channel_id), channel_str(next_channel_id));
299 let from_onchain_str = if *claim_from_onchain_tx {
300 "from onchain downstream claim"
302 "from HTLC fulfill message"
304 if let Some(fee_earned) = fee_earned_msat {
306 "\nEVENT: Forwarded payment{}{}, earning {} msat {}",
307 from_prev_str, to_next_str, fee_earned, from_onchain_str
311 "\nEVENT: Forwarded payment{}{}, claiming onchain {}",
312 from_prev_str, to_next_str, from_onchain_str
316 io::stdout().flush().unwrap();
318 Event::HTLCHandlingFailed { .. } => {}
319 Event::PendingHTLCsForwardable { time_forwardable } => {
320 let forwarding_channel_manager = channel_manager.clone();
321 let min = time_forwardable.as_millis() as u64;
322 tokio::spawn(async move {
323 let millis_to_sleep = thread_rng().gen_range(min, min * 5) as u64;
324 tokio::time::sleep(Duration::from_millis(millis_to_sleep)).await;
325 forwarding_channel_manager.process_pending_htlc_forwards();
328 Event::SpendableOutputs { outputs } => {
329 let destination_address = bitcoind_client.get_new_address().await;
330 let output_descriptors = &outputs.iter().map(|a| a).collect::<Vec<_>>();
332 bitcoind_client.get_est_sat_per_1000_weight(ConfirmationTarget::Normal);
333 let spending_tx = keys_manager
334 .spend_spendable_outputs(
337 destination_address.script_pubkey(),
342 bitcoind_client.broadcast_transaction(&spending_tx);
344 Event::ChannelClosed { channel_id, reason, user_channel_id: _ } => {
346 "\nEVENT: Channel {} closed due to: {:?}",
347 hex_utils::hex_str(channel_id),
351 io::stdout().flush().unwrap();
353 Event::DiscardFunding { .. } => {
354 // A "real" node should probably "lock" the UTXOs spent in funding transactions until
355 // the funding transaction either confirms, or this event is generated.
360 async fn start_ldk() {
361 let args = match cli::parse_startup_args() {
362 Ok(user_args) => user_args,
366 // Initialize the LDK data directory if necessary.
367 let ldk_data_dir = format!("{}/.ldk", args.ldk_storage_dir_path);
368 fs::create_dir_all(ldk_data_dir.clone()).unwrap();
370 // Initialize our bitcoind client.
371 let bitcoind_client = match BitcoindClient::new(
372 args.bitcoind_rpc_host.clone(),
373 args.bitcoind_rpc_port,
374 args.bitcoind_rpc_username.clone(),
375 args.bitcoind_rpc_password.clone(),
376 tokio::runtime::Handle::current(),
380 Ok(client) => Arc::new(client),
382 println!("Failed to connect to bitcoind client: {}", e);
387 // Check that the bitcoind we've connected to is running the network we expect
388 let bitcoind_chain = bitcoind_client.get_blockchain_info().await.chain;
390 != match args.network {
391 bitcoin::Network::Bitcoin => "main",
392 bitcoin::Network::Testnet => "test",
393 bitcoin::Network::Regtest => "regtest",
394 bitcoin::Network::Signet => "signet",
397 "Chain argument ({}) didn't match bitcoind chain ({})",
398 args.network, bitcoind_chain
404 // Step 1: Initialize the FeeEstimator
406 // BitcoindClient implements the FeeEstimator trait, so it'll act as our fee estimator.
407 let fee_estimator = bitcoind_client.clone();
409 // Step 2: Initialize the Logger
410 let logger = Arc::new(FilesystemLogger::new(ldk_data_dir.clone()));
412 // Step 3: Initialize the BroadcasterInterface
414 // BitcoindClient implements the BroadcasterInterface trait, so it'll act as our transaction
416 let broadcaster = bitcoind_client.clone();
418 // Step 4: Initialize Persist
419 let persister = Arc::new(FilesystemPersister::new(ldk_data_dir.clone()));
421 // Step 5: Initialize the ChainMonitor
422 let chain_monitor: Arc<ChainMonitor> = Arc::new(chainmonitor::ChainMonitor::new(
426 fee_estimator.clone(),
430 // Step 6: Initialize the KeysManager
432 // The key seed that we use to derive the node privkey (that corresponds to the node pubkey) and
433 // other secret key material.
434 let keys_seed_path = format!("{}/keys_seed", ldk_data_dir.clone());
435 let keys_seed = if let Ok(seed) = fs::read(keys_seed_path.clone()) {
436 assert_eq!(seed.len(), 32);
437 let mut key = [0; 32];
438 key.copy_from_slice(&seed);
441 let mut key = [0; 32];
442 thread_rng().fill_bytes(&mut key);
443 match File::create(keys_seed_path.clone()) {
445 f.write_all(&key).expect("Failed to write node keys seed to disk");
446 f.sync_all().expect("Failed to sync node keys seed to disk");
449 println!("ERROR: Unable to create keys seed file {}: {}", keys_seed_path, e);
455 let cur = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
456 let keys_manager = Arc::new(KeysManager::new(&keys_seed, cur.as_secs(), cur.subsec_nanos()));
458 // Step 7: Read ChannelMonitor state from disk
459 let mut channelmonitors = persister.read_channelmonitors(keys_manager.clone()).unwrap();
461 // Step 8: Initialize the ChannelManager
462 let mut user_config = UserConfig::default();
463 user_config.channel_handshake_limits.force_announced_channel_preference = false;
464 let mut restarting_node = true;
465 let (channel_manager_blockhash, channel_manager) = {
466 if let Ok(mut f) = fs::File::open(format!("{}/manager", ldk_data_dir.clone())) {
467 let mut channel_monitor_mut_references = Vec::new();
468 for (_, channel_monitor) in channelmonitors.iter_mut() {
469 channel_monitor_mut_references.push(channel_monitor);
471 let read_args = ChannelManagerReadArgs::new(
472 keys_manager.clone(),
473 fee_estimator.clone(),
474 chain_monitor.clone(),
478 channel_monitor_mut_references,
480 <(BlockHash, ChannelManager)>::read(&mut f, read_args).unwrap()
482 // We're starting a fresh node.
483 restarting_node = false;
484 let getinfo_resp = bitcoind_client.get_blockchain_info().await;
486 let chain_params = ChainParameters {
487 network: args.network,
488 best_block: BestBlock::new(
489 getinfo_resp.latest_blockhash,
490 getinfo_resp.latest_height as u32,
493 let fresh_channel_manager = channelmanager::ChannelManager::new(
494 fee_estimator.clone(),
495 chain_monitor.clone(),
498 keys_manager.clone(),
502 (getinfo_resp.latest_blockhash, fresh_channel_manager)
506 // Step 9: Sync ChannelMonitors and ChannelManager to chain tip
507 let mut chain_listener_channel_monitors = Vec::new();
508 let mut cache = UnboundedCache::new();
509 let mut chain_tip: Option<poll::ValidatedBlockHeader> = None;
511 let mut chain_listeners = vec![(
512 channel_manager_blockhash,
513 &channel_manager as &(dyn chain::Listen + Send + Sync),
516 for (blockhash, channel_monitor) in channelmonitors.drain(..) {
517 let outpoint = channel_monitor.get_funding_txo().0;
518 chain_listener_channel_monitors.push((
520 (channel_monitor, broadcaster.clone(), fee_estimator.clone(), logger.clone()),
525 for monitor_listener_info in chain_listener_channel_monitors.iter_mut() {
526 chain_listeners.push((
527 monitor_listener_info.0,
528 &monitor_listener_info.1 as &(dyn chain::Listen + Send + Sync),
532 init::synchronize_listeners(
533 bitcoind_client.as_ref(),
543 // Step 10: Give ChannelMonitors to ChainMonitor
544 for item in chain_listener_channel_monitors.drain(..) {
545 let channel_monitor = item.1 .0;
546 let funding_outpoint = item.2;
548 chain_monitor.watch_channel(funding_outpoint, channel_monitor),
549 ChannelMonitorUpdateStatus::Completed
553 // Step 11: Optional: Initialize the P2PGossipSync
554 let genesis = genesis_block(args.network).header.block_hash();
555 let network_graph_path = format!("{}/network_graph", ldk_data_dir.clone());
557 Arc::new(disk::read_network(Path::new(&network_graph_path), genesis, logger.clone()));
558 let gossip_sync = Arc::new(P2PGossipSync::new(
559 Arc::clone(&network_graph),
560 None::<Arc<dyn chain::Access + Send + Sync>>,
564 // Step 12: Initialize the PeerManager
565 let channel_manager: Arc<ChannelManager> = Arc::new(channel_manager);
566 let onion_messenger: Arc<OnionMessenger> = Arc::new(OnionMessenger::new(
567 Arc::clone(&keys_manager),
569 IgnoringMessageHandler {},
571 let mut ephemeral_bytes = [0; 32];
572 let current_time = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
573 rand::thread_rng().fill_bytes(&mut ephemeral_bytes);
574 let lightning_msg_handler = MessageHandler {
575 chan_handler: channel_manager.clone(),
576 route_handler: gossip_sync.clone(),
577 onion_message_handler: onion_messenger.clone(),
579 let peer_manager: Arc<PeerManager> = Arc::new(PeerManager::new(
580 lightning_msg_handler,
581 keys_manager.get_node_secret(Recipient::Node).unwrap(),
582 current_time.try_into().unwrap(),
585 IgnoringMessageHandler {},
589 // Step 13: Initialize networking
591 let peer_manager_connection_handler = peer_manager.clone();
592 let listening_port = args.ldk_peer_listening_port;
593 let stop_listen_connect = Arc::new(AtomicBool::new(false));
594 let stop_listen = Arc::clone(&stop_listen_connect);
595 tokio::spawn(async move {
596 let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", listening_port))
598 .expect("Failed to bind to listen port - is something else already listening on it?");
600 let peer_mgr = peer_manager_connection_handler.clone();
601 let tcp_stream = listener.accept().await.unwrap().0;
602 if stop_listen.load(Ordering::Acquire) {
605 tokio::spawn(async move {
606 lightning_net_tokio::setup_inbound(
608 tcp_stream.into_std().unwrap(),
615 // Step 14: Connect and Disconnect Blocks
616 if chain_tip.is_none() {
617 chain_tip = Some(init::validate_best_block_header(bitcoind_client.as_ref()).await.unwrap());
619 let channel_manager_listener = channel_manager.clone();
620 let chain_monitor_listener = chain_monitor.clone();
621 let bitcoind_block_source = bitcoind_client.clone();
622 let network = args.network;
623 tokio::spawn(async move {
624 let chain_poller = poll::ChainPoller::new(bitcoind_block_source.as_ref(), network);
625 let chain_listener = (chain_monitor_listener, channel_manager_listener);
627 SpvClient::new(chain_tip.unwrap(), chain_poller, &mut cache, &chain_listener);
629 spv_client.poll_best_tip().await.unwrap();
630 tokio::time::sleep(Duration::from_secs(1)).await;
634 // Step 15: Handle LDK Events
635 let channel_manager_event_listener = channel_manager.clone();
636 let keys_manager_listener = keys_manager.clone();
637 // TODO: persist payment info to disk
638 let inbound_payments: PaymentInfoStorage = Arc::new(Mutex::new(HashMap::new()));
639 let outbound_payments: PaymentInfoStorage = Arc::new(Mutex::new(HashMap::new()));
640 let inbound_pmts_for_events = inbound_payments.clone();
641 let outbound_pmts_for_events = outbound_payments.clone();
642 let network = args.network;
643 let bitcoind_rpc = bitcoind_client.clone();
644 let network_graph_events = network_graph.clone();
645 let handle = tokio::runtime::Handle::current();
646 let event_handler = move |event: &Event| {
647 handle.block_on(handle_ldk_events(
648 &channel_manager_event_listener,
650 &network_graph_events,
651 &keys_manager_listener,
652 &inbound_pmts_for_events,
653 &outbound_pmts_for_events,
659 // Step 16: Initialize routing ProbabilisticScorer
660 let scorer_path = format!("{}/scorer", ldk_data_dir.clone());
661 let scorer = Arc::new(Mutex::new(disk::read_scorer(
662 Path::new(&scorer_path),
663 Arc::clone(&network_graph),
667 // Step 17: Create InvoicePayer
668 let router = DefaultRouter::new(
669 network_graph.clone(),
671 keys_manager.get_secure_random_bytes(),
674 let invoice_payer = Arc::new(InvoicePayer::new(
675 channel_manager.clone(),
679 payment::Retry::Timeout(Duration::from_secs(10)),
682 // Step 18: Persist ChannelManager and NetworkGraph
683 let persister = Arc::new(FilesystemPersister::new(ldk_data_dir.clone()));
685 // Step 19: Background Processing
686 let background_processor = BackgroundProcessor::start(
688 invoice_payer.clone(),
689 chain_monitor.clone(),
690 channel_manager.clone(),
691 GossipSync::p2p(gossip_sync.clone()),
692 peer_manager.clone(),
694 Some(scorer.clone()),
697 // Regularly reconnect to channel peers.
698 let connect_cm = Arc::clone(&channel_manager);
699 let connect_pm = Arc::clone(&peer_manager);
700 let peer_data_path = format!("{}/channel_peer_data", ldk_data_dir.clone());
701 let stop_connect = Arc::clone(&stop_listen_connect);
702 tokio::spawn(async move {
703 let mut interval = tokio::time::interval(Duration::from_secs(1));
705 interval.tick().await;
706 match disk::read_channel_peer_data(Path::new(&peer_data_path)) {
708 let peers = connect_pm.get_peer_node_ids();
709 for node_id in connect_cm
712 .map(|chan| chan.counterparty.node_id)
713 .filter(|id| !peers.contains(id))
715 if stop_connect.load(Ordering::Acquire) {
718 for (pubkey, peer_addr) in info.iter() {
719 if *pubkey == node_id {
720 let _ = cli::do_connect_peer(
723 Arc::clone(&connect_pm),
730 Err(e) => println!("ERROR: errored reading channel peer info from disk: {:?}", e),
735 // Regularly broadcast our node_announcement. This is only required (or possible) if we have
736 // some public channels, and is only useful if we have public listen address(es) to announce.
737 // In a production environment, this should occur only after the announcement of new channels
738 // to avoid churn in the global network graph.
739 let peer_man = Arc::clone(&peer_manager);
740 let network = args.network;
741 if !args.ldk_announced_listen_addr.is_empty() {
742 tokio::spawn(async move {
743 let mut interval = tokio::time::interval(Duration::from_secs(60));
745 interval.tick().await;
746 peer_man.broadcast_node_announcement(
748 args.ldk_announced_node_name,
749 args.ldk_announced_listen_addr.clone(),
756 cli::poll_for_user_input(
757 Arc::clone(&invoice_payer),
758 Arc::clone(&peer_manager),
759 Arc::clone(&channel_manager),
760 Arc::clone(&keys_manager),
761 Arc::clone(&network_graph),
762 Arc::clone(&onion_messenger),
765 ldk_data_dir.clone(),
771 // Disconnect our peers and stop accepting new connections. This ensures we don't continue
772 // updating our channel data after we've stopped the background processor.
773 stop_listen_connect.store(true, Ordering::Release);
774 peer_manager.disconnect_all_peers();
776 // Stop the background processor.
777 background_processor.stop().unwrap();
781 pub async fn main() {
782 #[cfg(not(target_os = "windows"))]
784 // Catch Ctrl-C with a dummy signal handler.
786 let mut new_action: libc::sigaction = core::mem::zeroed();
787 let mut old_action: libc::sigaction = core::mem::zeroed();
789 extern "C" fn dummy_handler(
790 _: libc::c_int, _: *const libc::siginfo_t, _: *const libc::c_void,
794 new_action.sa_sigaction = dummy_handler as libc::sighandler_t;
795 new_action.sa_flags = libc::SA_SIGINFO;
799 &new_action as *const libc::sigaction,
800 &mut old_action as *mut libc::sigaction,