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::chainmonitor;
19 use lightning::chain::keysinterface::{InMemorySigner, KeysInterface, KeysManager, Recipient};
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::log_bytes;
28 use lightning::routing::gossip;
29 use lightning::routing::gossip::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;
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 lightning_rapid_gossip_sync::RapidGossipSync;
44 use rand::{thread_rng, Rng};
45 use std::collections::hash_map::Entry;
46 use std::collections::HashMap;
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> = payment::InvoicePayer<
108 Arc<Mutex<ProbabilisticScorer<Arc<NetworkGraph>, Arc<FilesystemLogger>>>>,
109 Arc<FilesystemLogger>,
113 type Router = DefaultRouter<Arc<NetworkGraph>, Arc<FilesystemLogger>>;
115 type GossipSync<P, G, A, L> =
116 lightning_background_processor::GossipSync<P, Arc<RapidGossipSync<G, L>>, G, A, L>;
118 pub(crate) type NetworkGraph = gossip::NetworkGraph<Arc<FilesystemLogger>>;
120 async fn handle_ldk_events(
121 channel_manager: Arc<ChannelManager>, bitcoind_client: Arc<BitcoindClient>,
122 keys_manager: Arc<KeysManager>, inbound_payments: PaymentInfoStorage,
123 outbound_payments: PaymentInfoStorage, network: Network, event: &Event,
126 Event::FundingGenerationReady {
127 temporary_channel_id,
128 counterparty_node_id,
129 channel_value_satoshis,
133 // Construct the raw transaction with one output, that is paid the amount of the
135 let addr = WitnessProgram::from_scriptpubkey(
138 Network::Bitcoin => bitcoin_bech32::constants::Network::Bitcoin,
139 Network::Testnet => bitcoin_bech32::constants::Network::Testnet,
140 Network::Regtest => bitcoin_bech32::constants::Network::Regtest,
141 Network::Signet => bitcoin_bech32::constants::Network::Signet,
144 .expect("Lightning funding tx should always be to a SegWit output")
146 let mut outputs = vec![HashMap::with_capacity(1)];
147 outputs[0].insert(addr, *channel_value_satoshis as f64 / 100_000_000.0);
148 let raw_tx = bitcoind_client.create_raw_transaction(outputs).await;
150 // Have your wallet put the inputs into the transaction such that the output is
152 let funded_tx = bitcoind_client.fund_raw_transaction(raw_tx).await;
154 // Sign the final funding transaction and broadcast it.
155 let signed_tx = bitcoind_client.sign_raw_transaction_with_wallet(funded_tx.hex).await;
156 assert_eq!(signed_tx.complete, true);
157 let final_tx: Transaction =
158 encode::deserialize(&hex_utils::to_vec(&signed_tx.hex).unwrap()).unwrap();
159 // Give the funding transaction back to LDK for opening the channel.
161 .funding_transaction_generated(
162 &temporary_channel_id,
163 counterparty_node_id,
169 "\nERROR: Channel went away before we could fund it. The peer disconnected or refused the channel.");
171 io::stdout().flush().unwrap();
174 Event::PaymentReceived { payment_hash, purpose, amount_msat } => {
176 "\nEVENT: received payment from payment hash {} of {} millisatoshis",
177 hex_utils::hex_str(&payment_hash.0),
181 io::stdout().flush().unwrap();
182 let payment_preimage = match purpose {
183 PaymentPurpose::InvoicePayment { payment_preimage, .. } => *payment_preimage,
184 PaymentPurpose::SpontaneousPayment(preimage) => Some(*preimage),
186 channel_manager.claim_funds(payment_preimage.unwrap());
188 Event::PaymentClaimed { payment_hash, purpose, amount_msat } => {
190 "\nEVENT: claimed payment from payment hash {} of {} millisatoshis",
191 hex_utils::hex_str(&payment_hash.0),
195 io::stdout().flush().unwrap();
196 let (payment_preimage, payment_secret) = match purpose {
197 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
198 (*payment_preimage, Some(*payment_secret))
200 PaymentPurpose::SpontaneousPayment(preimage) => (Some(*preimage), None),
202 let mut payments = inbound_payments.lock().unwrap();
203 match payments.entry(*payment_hash) {
204 Entry::Occupied(mut e) => {
205 let payment = e.get_mut();
206 payment.status = HTLCStatus::Succeeded;
207 payment.preimage = payment_preimage;
208 payment.secret = payment_secret;
210 Entry::Vacant(e) => {
211 e.insert(PaymentInfo {
212 preimage: payment_preimage,
213 secret: payment_secret,
214 status: HTLCStatus::Succeeded,
215 amt_msat: MillisatAmount(Some(*amount_msat)),
220 Event::PaymentSent { payment_preimage, payment_hash, fee_paid_msat, .. } => {
221 let mut payments = outbound_payments.lock().unwrap();
222 for (hash, payment) in payments.iter_mut() {
223 if *hash == *payment_hash {
224 payment.preimage = Some(*payment_preimage);
225 payment.status = HTLCStatus::Succeeded;
227 "\nEVENT: successfully sent payment of {} millisatoshis{} from \
228 payment hash {:?} with preimage {:?}",
230 if let Some(fee) = fee_paid_msat {
231 format!(" (fee {} msat)", fee)
235 hex_utils::hex_str(&payment_hash.0),
236 hex_utils::hex_str(&payment_preimage.0)
239 io::stdout().flush().unwrap();
243 Event::OpenChannelRequest { .. } => {
244 // Unreachable, we don't set manually_accept_inbound_channels
246 Event::PaymentPathSuccessful { .. } => {}
247 Event::PaymentPathFailed { .. } => {}
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 from_channel_str = prev_channel_id
269 .map(|channel_id| format!(" from channel {}", log_bytes!(channel_id)))
270 .unwrap_or_default();
271 let to_channel_str = next_channel_id
272 .map(|channel_id| format!(" to channel {}", log_bytes!(channel_id)))
273 .unwrap_or_default();
274 let from_onchain_str = if *claim_from_onchain_tx {
275 "from onchain downstream claim"
277 "from HTLC fulfill message"
279 if let Some(fee_earned) = fee_earned_msat {
281 "\nEVENT: Forwarded payment{}{}, earning {} msat {}",
282 from_channel_str, to_channel_str, fee_earned, from_onchain_str
286 "\nEVENT: Forwarded payment{}{}, claiming onchain {}",
287 from_channel_str, to_channel_str, from_onchain_str
291 io::stdout().flush().unwrap();
293 Event::PendingHTLCsForwardable { time_forwardable } => {
294 let forwarding_channel_manager = channel_manager.clone();
295 let min = time_forwardable.as_millis() as u64;
296 tokio::spawn(async move {
297 let millis_to_sleep = thread_rng().gen_range(min, min * 5) as u64;
298 tokio::time::sleep(Duration::from_millis(millis_to_sleep)).await;
299 forwarding_channel_manager.process_pending_htlc_forwards();
302 Event::SpendableOutputs { outputs } => {
303 let destination_address = bitcoind_client.get_new_address().await;
304 let output_descriptors = &outputs.iter().map(|a| a).collect::<Vec<_>>();
306 bitcoind_client.get_est_sat_per_1000_weight(ConfirmationTarget::Normal);
307 let spending_tx = keys_manager
308 .spend_spendable_outputs(
311 destination_address.script_pubkey(),
316 bitcoind_client.broadcast_transaction(&spending_tx);
318 Event::ChannelClosed { channel_id, reason, user_channel_id: _ } => {
320 "\nEVENT: Channel {} closed due to: {:?}",
321 hex_utils::hex_str(channel_id),
325 io::stdout().flush().unwrap();
327 Event::DiscardFunding { .. } => {
328 // A "real" node should probably "lock" the UTXOs spent in funding transactions until
329 // the funding transaction either confirms, or this event is generated.
334 async fn start_ldk() {
335 let args = match cli::parse_startup_args() {
336 Ok(user_args) => user_args,
340 // Initialize the LDK data directory if necessary.
341 let ldk_data_dir = format!("{}/.ldk", args.ldk_storage_dir_path);
342 fs::create_dir_all(ldk_data_dir.clone()).unwrap();
344 // Initialize our bitcoind client.
345 let bitcoind_client = match BitcoindClient::new(
346 args.bitcoind_rpc_host.clone(),
347 args.bitcoind_rpc_port,
348 args.bitcoind_rpc_username.clone(),
349 args.bitcoind_rpc_password.clone(),
350 tokio::runtime::Handle::current(),
354 Ok(client) => Arc::new(client),
356 println!("Failed to connect to bitcoind client: {}", e);
361 // Check that the bitcoind we've connected to is running the network we expect
362 let bitcoind_chain = bitcoind_client.get_blockchain_info().await.chain;
364 != match args.network {
365 bitcoin::Network::Bitcoin => "main",
366 bitcoin::Network::Testnet => "test",
367 bitcoin::Network::Regtest => "regtest",
368 bitcoin::Network::Signet => "signet",
371 "Chain argument ({}) didn't match bitcoind chain ({})",
372 args.network, bitcoind_chain
378 // Step 1: Initialize the FeeEstimator
380 // BitcoindClient implements the FeeEstimator trait, so it'll act as our fee estimator.
381 let fee_estimator = bitcoind_client.clone();
383 // Step 2: Initialize the Logger
384 let logger = Arc::new(FilesystemLogger::new(ldk_data_dir.clone()));
386 // Step 3: Initialize the BroadcasterInterface
388 // BitcoindClient implements the BroadcasterInterface trait, so it'll act as our transaction
390 let broadcaster = bitcoind_client.clone();
392 // Step 4: Initialize Persist
393 let persister = Arc::new(FilesystemPersister::new(ldk_data_dir.clone()));
395 // Step 5: Initialize the ChainMonitor
396 let chain_monitor: Arc<ChainMonitor> = Arc::new(chainmonitor::ChainMonitor::new(
400 fee_estimator.clone(),
404 // Step 6: Initialize the KeysManager
406 // The key seed that we use to derive the node privkey (that corresponds to the node pubkey) and
407 // other secret key material.
408 let keys_seed_path = format!("{}/keys_seed", ldk_data_dir.clone());
409 let keys_seed = if let Ok(seed) = fs::read(keys_seed_path.clone()) {
410 assert_eq!(seed.len(), 32);
411 let mut key = [0; 32];
412 key.copy_from_slice(&seed);
415 let mut key = [0; 32];
416 thread_rng().fill_bytes(&mut key);
417 match File::create(keys_seed_path.clone()) {
419 f.write_all(&key).expect("Failed to write node keys seed to disk");
420 f.sync_all().expect("Failed to sync node keys seed to disk");
423 println!("ERROR: Unable to create keys seed file {}: {}", keys_seed_path, e);
429 let cur = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
430 let keys_manager = Arc::new(KeysManager::new(&keys_seed, cur.as_secs(), cur.subsec_nanos()));
432 // Step 7: Read ChannelMonitor state from disk
433 let mut channelmonitors = persister.read_channelmonitors(keys_manager.clone()).unwrap();
435 // Step 8: Initialize the ChannelManager
436 let mut user_config = UserConfig::default();
437 user_config.peer_channel_config_limits.force_announced_channel_preference = false;
438 let mut restarting_node = true;
439 let (channel_manager_blockhash, channel_manager) = {
440 if let Ok(mut f) = fs::File::open(format!("{}/manager", ldk_data_dir.clone())) {
441 let mut channel_monitor_mut_references = Vec::new();
442 for (_, channel_monitor) in channelmonitors.iter_mut() {
443 channel_monitor_mut_references.push(channel_monitor);
445 let read_args = ChannelManagerReadArgs::new(
446 keys_manager.clone(),
447 fee_estimator.clone(),
448 chain_monitor.clone(),
452 channel_monitor_mut_references,
454 <(BlockHash, ChannelManager)>::read(&mut f, read_args).unwrap()
456 // We're starting a fresh node.
457 restarting_node = false;
458 let getinfo_resp = bitcoind_client.get_blockchain_info().await;
460 let chain_params = ChainParameters {
461 network: args.network,
462 best_block: BestBlock::new(
463 getinfo_resp.latest_blockhash,
464 getinfo_resp.latest_height as u32,
467 let fresh_channel_manager = channelmanager::ChannelManager::new(
468 fee_estimator.clone(),
469 chain_monitor.clone(),
472 keys_manager.clone(),
476 (getinfo_resp.latest_blockhash, fresh_channel_manager)
480 // Step 9: Sync ChannelMonitors and ChannelManager to chain tip
481 let mut chain_listener_channel_monitors = Vec::new();
482 let mut cache = UnboundedCache::new();
483 let mut chain_tip: Option<poll::ValidatedBlockHeader> = None;
485 let mut chain_listeners =
486 vec![(channel_manager_blockhash, &channel_manager as &dyn chain::Listen)];
488 for (blockhash, channel_monitor) in channelmonitors.drain(..) {
489 let outpoint = channel_monitor.get_funding_txo().0;
490 chain_listener_channel_monitors.push((
492 (channel_monitor, broadcaster.clone(), fee_estimator.clone(), logger.clone()),
497 for monitor_listener_info in chain_listener_channel_monitors.iter_mut() {
499 .push((monitor_listener_info.0, &monitor_listener_info.1 as &dyn chain::Listen));
502 init::synchronize_listeners(
503 &mut bitcoind_client.deref(),
513 // Step 10: Give ChannelMonitors to ChainMonitor
514 for item in chain_listener_channel_monitors.drain(..) {
515 let channel_monitor = item.1 .0;
516 let funding_outpoint = item.2;
517 chain_monitor.watch_channel(funding_outpoint, channel_monitor).unwrap();
520 // Step 11: Optional: Initialize the P2PGossipSync
521 let genesis = genesis_block(args.network).header.block_hash();
522 let network_graph_path = format!("{}/network_graph", ldk_data_dir.clone());
524 Arc::new(disk::read_network(Path::new(&network_graph_path), genesis, logger.clone()));
525 let gossip_sync = Arc::new(P2PGossipSync::new(
526 Arc::clone(&network_graph),
527 None::<Arc<dyn chain::Access + Send + Sync>>,
531 // Step 12: Initialize the PeerManager
532 let channel_manager: Arc<ChannelManager> = Arc::new(channel_manager);
533 let mut ephemeral_bytes = [0; 32];
534 rand::thread_rng().fill_bytes(&mut ephemeral_bytes);
535 let lightning_msg_handler = MessageHandler {
536 chan_handler: channel_manager.clone(),
537 route_handler: gossip_sync.clone(),
539 let peer_manager: Arc<PeerManager> = Arc::new(PeerManager::new(
540 lightning_msg_handler,
541 keys_manager.get_node_secret(Recipient::Node).unwrap(),
544 Arc::new(IgnoringMessageHandler {}),
548 // Step 13: Initialize networking
550 let peer_manager_connection_handler = peer_manager.clone();
551 let listening_port = args.ldk_peer_listening_port;
552 let stop_listen_connect = Arc::new(AtomicBool::new(false));
553 let stop_listen = Arc::clone(&stop_listen_connect);
554 tokio::spawn(async move {
555 let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", listening_port))
557 .expect("Failed to bind to listen port - is something else already listening on it?");
559 let peer_mgr = peer_manager_connection_handler.clone();
560 let tcp_stream = listener.accept().await.unwrap().0;
561 if stop_listen.load(Ordering::Acquire) {
564 tokio::spawn(async move {
565 lightning_net_tokio::setup_inbound(
567 tcp_stream.into_std().unwrap(),
574 // Step 14: Connect and Disconnect Blocks
575 if chain_tip.is_none() {
577 Some(init::validate_best_block_header(&mut bitcoind_client.deref()).await.unwrap());
579 let channel_manager_listener = channel_manager.clone();
580 let chain_monitor_listener = chain_monitor.clone();
581 let bitcoind_block_source = bitcoind_client.clone();
582 let network = args.network;
583 tokio::spawn(async move {
584 let mut derefed = bitcoind_block_source.deref();
585 let chain_poller = poll::ChainPoller::new(&mut derefed, network);
586 let chain_listener = (chain_monitor_listener, channel_manager_listener);
588 SpvClient::new(chain_tip.unwrap(), chain_poller, &mut cache, &chain_listener);
590 spv_client.poll_best_tip().await.unwrap();
591 tokio::time::sleep(Duration::from_secs(1)).await;
595 // Step 15: Handle LDK Events
596 let channel_manager_event_listener = channel_manager.clone();
597 let keys_manager_listener = keys_manager.clone();
598 // TODO: persist payment info to disk
599 let inbound_payments: PaymentInfoStorage = Arc::new(Mutex::new(HashMap::new()));
600 let outbound_payments: PaymentInfoStorage = Arc::new(Mutex::new(HashMap::new()));
601 let inbound_pmts_for_events = inbound_payments.clone();
602 let outbound_pmts_for_events = outbound_payments.clone();
603 let network = args.network;
604 let bitcoind_rpc = bitcoind_client.clone();
605 let handle = tokio::runtime::Handle::current();
606 let event_handler = move |event: &Event| {
607 handle.block_on(handle_ldk_events(
608 channel_manager_event_listener.clone(),
609 bitcoind_rpc.clone(),
610 keys_manager_listener.clone(),
611 inbound_pmts_for_events.clone(),
612 outbound_pmts_for_events.clone(),
618 // Step 16: Initialize routing ProbabilisticScorer
619 let scorer_path = format!("{}/scorer", ldk_data_dir.clone());
620 let scorer = Arc::new(Mutex::new(disk::read_scorer(
621 Path::new(&scorer_path),
622 Arc::clone(&network_graph),
626 // Step 17: Create InvoicePayer
627 let router = DefaultRouter::new(
628 network_graph.clone(),
630 keys_manager.get_secure_random_bytes(),
632 let invoice_payer = Arc::new(InvoicePayer::new(
633 channel_manager.clone(),
638 payment::Retry::Attempts(5),
641 // Step 18: Persist ChannelManager and NetworkGraph
642 let persister = Arc::new(FilesystemPersister::new(ldk_data_dir.clone()));
644 // Step 19: Background Processing
645 let background_processor = BackgroundProcessor::start(
647 invoice_payer.clone(),
648 chain_monitor.clone(),
649 channel_manager.clone(),
650 GossipSync::P2P(gossip_sync.clone()),
651 peer_manager.clone(),
653 Some(scorer.clone()),
656 // Regularly reconnect to channel peers.
657 let connect_cm = Arc::clone(&channel_manager);
658 let connect_pm = Arc::clone(&peer_manager);
659 let peer_data_path = format!("{}/channel_peer_data", ldk_data_dir.clone());
660 let stop_connect = Arc::clone(&stop_listen_connect);
661 tokio::spawn(async move {
662 let mut interval = tokio::time::interval(Duration::from_secs(1));
664 interval.tick().await;
665 match disk::read_channel_peer_data(Path::new(&peer_data_path)) {
667 let peers = connect_pm.get_peer_node_ids();
668 for node_id in connect_cm
671 .map(|chan| chan.counterparty.node_id)
672 .filter(|id| !peers.contains(id))
674 if stop_connect.load(Ordering::Acquire) {
677 for (pubkey, peer_addr) in info.iter() {
678 if *pubkey == node_id {
679 let _ = cli::do_connect_peer(
682 Arc::clone(&connect_pm),
689 Err(e) => println!("ERROR: errored reading channel peer info from disk: {:?}", e),
694 // Regularly broadcast our node_announcement. This is only required (or possible) if we have
695 // some public channels, and is only useful if we have public listen address(es) to announce.
696 // In a production environment, this should occur only after the announcement of new channels
697 // to avoid churn in the global network graph.
698 let chan_manager = Arc::clone(&channel_manager);
699 let network = args.network;
700 if !args.ldk_announced_listen_addr.is_empty() {
701 tokio::spawn(async move {
702 let mut interval = tokio::time::interval(Duration::from_secs(60));
704 interval.tick().await;
705 chan_manager.broadcast_node_announcement(
707 args.ldk_announced_node_name,
708 args.ldk_announced_listen_addr.clone(),
715 cli::poll_for_user_input(
716 Arc::clone(&invoice_payer),
717 Arc::clone(&peer_manager),
718 Arc::clone(&channel_manager),
719 Arc::clone(&keys_manager),
720 Arc::clone(&network_graph),
723 ldk_data_dir.clone(),
728 // Disconnect our peers and stop accepting new connections. This ensures we don't continue
729 // updating our channel data after we've stopped the background processor.
730 stop_listen_connect.store(true, Ordering::Release);
731 peer_manager.disconnect_all_peers();
733 // Stop the background processor.
734 background_processor.stop().unwrap();
738 pub async fn main() {