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::hashes::sha256::Hash as Sha256;
13 use bitcoin::hashes::Hash;
14 use bitcoin::network::constants::Network;
15 use bitcoin::secp256k1::Secp256k1;
16 use bitcoin::BlockHash;
17 use bitcoin_bech32::WitnessProgram;
19 use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
20 use lightning::chain::chainmonitor;
21 use lightning::chain::keysinterface::{InMemorySigner, KeysInterface, KeysManager};
22 use lightning::chain::{BestBlock, Filter, Watch};
23 use lightning::ln::channelmanager;
24 use lightning::ln::channelmanager::{
25 ChainParameters, ChannelManagerReadArgs, SimpleArcChannelManager,
27 use lightning::ln::peer_handler::{IgnoringMessageHandler, MessageHandler, SimpleArcPeerManager};
28 use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
29 use lightning::routing::network_graph::NetGraphMsgHandler;
30 use lightning::util::config::UserConfig;
31 use lightning::util::events::{Event, PaymentPurpose};
32 use lightning::util::ser::ReadableArgs;
33 use lightning_background_processor::BackgroundProcessor;
34 use lightning_block_sync::init;
35 use lightning_block_sync::poll;
36 use lightning_block_sync::SpvClient;
37 use lightning_block_sync::UnboundedCache;
38 use lightning_net_tokio::SocketDescriptor;
39 use lightning_persister::FilesystemPersister;
40 use rand::{thread_rng, Rng};
41 use std::collections::hash_map::Entry;
42 use std::collections::HashMap;
50 use std::sync::{Arc, Mutex};
51 use std::time::{Duration, SystemTime};
53 pub(crate) enum HTLCStatus {
59 pub(crate) struct MillisatAmount(Option<u64>);
61 impl fmt::Display for MillisatAmount {
62 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64 Some(amt) => write!(f, "{}", amt),
65 None => write!(f, "unknown"),
70 pub(crate) struct PaymentInfo {
71 preimage: Option<PaymentPreimage>,
72 secret: Option<PaymentSecret>,
74 amt_msat: MillisatAmount,
77 pub(crate) type PaymentInfoStorage = Arc<Mutex<HashMap<PaymentHash, PaymentInfo>>>;
79 type ChainMonitor = chainmonitor::ChainMonitor<
81 Arc<dyn Filter + Send + Sync>,
84 Arc<FilesystemLogger>,
85 Arc<FilesystemPersister>,
88 pub(crate) type PeerManager = SimpleArcPeerManager<
93 dyn chain::Access + Send + Sync,
97 pub(crate) type ChannelManager =
98 SimpleArcChannelManager<ChainMonitor, BitcoindClient, BitcoindClient, FilesystemLogger>;
100 async fn handle_ldk_events(
101 channel_manager: Arc<ChannelManager>, bitcoind_client: Arc<BitcoindClient>,
102 keys_manager: Arc<KeysManager>, inbound_payments: PaymentInfoStorage,
103 outbound_payments: PaymentInfoStorage, network: Network, event: &Event,
106 Event::FundingGenerationReady {
107 temporary_channel_id,
108 channel_value_satoshis,
112 // Construct the raw transaction with one output, that is paid the amount of the
114 let addr = WitnessProgram::from_scriptpubkey(
117 Network::Bitcoin => bitcoin_bech32::constants::Network::Bitcoin,
118 Network::Testnet => bitcoin_bech32::constants::Network::Testnet,
119 Network::Regtest => bitcoin_bech32::constants::Network::Regtest,
120 Network::Signet => panic!("Signet unsupported"),
123 .expect("Lightning funding tx should always be to a SegWit output")
125 let mut outputs = vec![HashMap::with_capacity(1)];
126 outputs[0].insert(addr, *channel_value_satoshis as f64 / 100_000_000.0);
127 let raw_tx = bitcoind_client.create_raw_transaction(outputs).await;
129 // Have your wallet put the inputs into the transaction such that the output is
131 let funded_tx = bitcoind_client.fund_raw_transaction(raw_tx).await;
133 // Sign the final funding transaction and broadcast it.
134 let signed_tx = bitcoind_client.sign_raw_transaction_with_wallet(funded_tx.hex).await;
135 assert_eq!(signed_tx.complete, true);
136 let final_tx: Transaction =
137 encode::deserialize(&hex_utils::to_vec(&signed_tx.hex).unwrap()).unwrap();
138 // Give the funding transaction back to LDK for opening the channel.
140 .funding_transaction_generated(&temporary_channel_id, final_tx)
144 "\nERROR: Channel went away before we could fund it. The peer disconnected or refused the channel.");
146 io::stdout().flush().unwrap();
149 Event::PaymentReceived { payment_hash, purpose, amt, .. } => {
150 let mut payments = inbound_payments.lock().unwrap();
151 let (payment_preimage, payment_secret) = match purpose {
152 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
153 (*payment_preimage, Some(*payment_secret))
155 PaymentPurpose::SpontaneousPayment(preimage) => (Some(*preimage), None),
157 let status = match channel_manager.claim_funds(payment_preimage.unwrap()) {
160 "\nEVENT: received payment from payment hash {} of {} millisatoshis",
161 hex_utils::hex_str(&payment_hash.0),
165 io::stdout().flush().unwrap();
166 HTLCStatus::Succeeded
168 _ => HTLCStatus::Failed,
170 match payments.entry(*payment_hash) {
171 Entry::Occupied(mut e) => {
172 let payment = e.get_mut();
173 payment.status = status;
174 payment.preimage = payment_preimage;
175 payment.secret = payment_secret;
177 Entry::Vacant(e) => {
178 e.insert(PaymentInfo {
179 preimage: payment_preimage,
180 secret: payment_secret,
182 amt_msat: MillisatAmount(Some(*amt)),
187 Event::PaymentSent { payment_preimage } => {
188 let hashed = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
189 let mut payments = outbound_payments.lock().unwrap();
190 for (payment_hash, payment) in payments.iter_mut() {
191 if *payment_hash == hashed {
192 payment.preimage = Some(*payment_preimage);
193 payment.status = HTLCStatus::Succeeded;
195 "\nEVENT: successfully sent payment of {} millisatoshis from \
196 payment hash {:?} with preimage {:?}",
198 hex_utils::hex_str(&payment_hash.0),
199 hex_utils::hex_str(&payment_preimage.0)
202 io::stdout().flush().unwrap();
206 Event::PaymentPathFailed {
214 "\nEVENT: Failed to send payment{} to payment hash {:?}: ",
215 if *all_paths_failed { "" } else { " along MPP path" },
216 hex_utils::hex_str(&payment_hash.0)
218 if *rejected_by_dest {
219 println!("re-attempting the payment will not succeed");
221 println!("payment may be retried");
224 io::stdout().flush().unwrap();
226 let mut payments = outbound_payments.lock().unwrap();
227 if payments.contains_key(&payment_hash) {
228 let payment = payments.get_mut(&payment_hash).unwrap();
229 payment.status = HTLCStatus::Failed;
232 Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
233 let from_onchain_str = if *claim_from_onchain_tx {
234 "from onchain downstream claim"
236 "from HTLC fulfill message"
238 if let Some(fee_earned) = fee_earned_msat {
240 "\nEVENT: Forwarded payment, earning {} msat {}",
241 fee_earned, from_onchain_str
244 println!("\nEVENT: Forwarded payment, claiming onchain {}", from_onchain_str);
247 io::stdout().flush().unwrap();
249 Event::PendingHTLCsForwardable { time_forwardable } => {
250 let forwarding_channel_manager = channel_manager.clone();
251 let min = time_forwardable.as_millis() as u64;
252 tokio::spawn(async move {
253 let millis_to_sleep = thread_rng().gen_range(min, min * 5) as u64;
254 tokio::time::sleep(Duration::from_millis(millis_to_sleep)).await;
255 forwarding_channel_manager.process_pending_htlc_forwards();
258 Event::SpendableOutputs { outputs } => {
259 let destination_address = bitcoind_client.get_new_address().await;
260 let output_descriptors = &outputs.iter().map(|a| a).collect::<Vec<_>>();
262 bitcoind_client.get_est_sat_per_1000_weight(ConfirmationTarget::Normal);
263 let spending_tx = keys_manager
264 .spend_spendable_outputs(
267 destination_address.script_pubkey(),
272 bitcoind_client.broadcast_transaction(&spending_tx);
274 Event::ChannelClosed { channel_id, reason } => {
276 "\nEVENT: Channel {} closed due to: {:?}",
277 hex_utils::hex_str(channel_id),
281 io::stdout().flush().unwrap();
286 async fn start_ldk() {
287 let args = match cli::parse_startup_args() {
288 Ok(user_args) => user_args,
292 // Initialize the LDK data directory if necessary.
293 let ldk_data_dir = format!("{}/.ldk", args.ldk_storage_dir_path);
294 fs::create_dir_all(ldk_data_dir.clone()).unwrap();
296 // Initialize our bitcoind client.
297 let bitcoind_client = match BitcoindClient::new(
298 args.bitcoind_rpc_host.clone(),
299 args.bitcoind_rpc_port,
300 args.bitcoind_rpc_username.clone(),
301 args.bitcoind_rpc_password.clone(),
302 tokio::runtime::Handle::current(),
306 Ok(client) => Arc::new(client),
308 println!("Failed to connect to bitcoind client: {}", e);
313 // Check that the bitcoind we've connected to is running the network we expect
314 let bitcoind_chain = bitcoind_client.get_blockchain_info().await.chain;
316 != match args.network {
317 bitcoin::Network::Bitcoin => "main",
318 bitcoin::Network::Testnet => "test",
319 bitcoin::Network::Regtest => "regtest",
320 bitcoin::Network::Signet => "signet",
323 "Chain argument ({}) didn't match bitcoind chain ({})",
324 args.network, bitcoind_chain
330 // Step 1: Initialize the FeeEstimator
332 // BitcoindClient implements the FeeEstimator trait, so it'll act as our fee estimator.
333 let fee_estimator = bitcoind_client.clone();
335 // Step 2: Initialize the Logger
336 let logger = Arc::new(FilesystemLogger::new(ldk_data_dir.clone()));
338 // Step 3: Initialize the BroadcasterInterface
340 // BitcoindClient implements the BroadcasterInterface trait, so it'll act as our transaction
342 let broadcaster = bitcoind_client.clone();
344 // Step 4: Initialize Persist
345 let persister = Arc::new(FilesystemPersister::new(ldk_data_dir.clone()));
347 // Step 5: Initialize the ChainMonitor
348 let chain_monitor: Arc<ChainMonitor> = Arc::new(chainmonitor::ChainMonitor::new(
352 fee_estimator.clone(),
356 // Step 6: Initialize the KeysManager
358 // The key seed that we use to derive the node privkey (that corresponds to the node pubkey) and
359 // other secret key material.
360 let keys_seed_path = format!("{}/keys_seed", ldk_data_dir.clone());
361 let keys_seed = if let Ok(seed) = fs::read(keys_seed_path.clone()) {
362 assert_eq!(seed.len(), 32);
363 let mut key = [0; 32];
364 key.copy_from_slice(&seed);
367 let mut key = [0; 32];
368 thread_rng().fill_bytes(&mut key);
369 match File::create(keys_seed_path.clone()) {
371 f.write_all(&key).expect("Failed to write node keys seed to disk");
372 f.sync_all().expect("Failed to sync node keys seed to disk");
375 println!("ERROR: Unable to create keys seed file {}: {}", keys_seed_path, e);
381 let cur = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
382 let keys_manager = Arc::new(KeysManager::new(&keys_seed, cur.as_secs(), cur.subsec_nanos()));
384 // Step 7: Read ChannelMonitor state from disk
385 let mut channelmonitors = persister.read_channelmonitors(keys_manager.clone()).unwrap();
387 // Step 8: Initialize the ChannelManager
388 let mut user_config = UserConfig::default();
389 user_config.peer_channel_config_limits.force_announced_channel_preference = false;
390 let mut restarting_node = true;
391 let (channel_manager_blockhash, mut channel_manager) = {
392 if let Ok(mut f) = fs::File::open(format!("{}/manager", ldk_data_dir.clone())) {
393 let mut channel_monitor_mut_references = Vec::new();
394 for (_, channel_monitor) in channelmonitors.iter_mut() {
395 channel_monitor_mut_references.push(channel_monitor);
397 let read_args = ChannelManagerReadArgs::new(
398 keys_manager.clone(),
399 fee_estimator.clone(),
400 chain_monitor.clone(),
404 channel_monitor_mut_references,
406 <(BlockHash, ChannelManager)>::read(&mut f, read_args).unwrap()
408 // We're starting a fresh node.
409 restarting_node = false;
410 let getinfo_resp = bitcoind_client.get_blockchain_info().await;
412 let chain_params = ChainParameters {
413 network: args.network,
414 best_block: BestBlock::new(
415 getinfo_resp.latest_blockhash,
416 getinfo_resp.latest_height as u32,
419 let fresh_channel_manager = channelmanager::ChannelManager::new(
420 fee_estimator.clone(),
421 chain_monitor.clone(),
424 keys_manager.clone(),
428 (getinfo_resp.latest_blockhash, fresh_channel_manager)
432 // Step 9: Sync ChannelMonitors and ChannelManager to chain tip
433 let mut chain_listener_channel_monitors = Vec::new();
434 let mut cache = UnboundedCache::new();
435 let mut chain_tip: Option<poll::ValidatedBlockHeader> = None;
437 let mut chain_listeners =
438 vec![(channel_manager_blockhash, &mut channel_manager as &mut dyn chain::Listen)];
440 for (blockhash, channel_monitor) in channelmonitors.drain(..) {
441 let outpoint = channel_monitor.get_funding_txo().0;
442 chain_listener_channel_monitors.push((
444 (channel_monitor, broadcaster.clone(), fee_estimator.clone(), logger.clone()),
449 for monitor_listener_info in chain_listener_channel_monitors.iter_mut() {
450 chain_listeners.push((
451 monitor_listener_info.0,
452 &mut monitor_listener_info.1 as &mut dyn chain::Listen,
456 init::synchronize_listeners(
457 &mut bitcoind_client.deref(),
467 // Step 10: Give ChannelMonitors to ChainMonitor
468 for item in chain_listener_channel_monitors.drain(..) {
469 let channel_monitor = item.1 .0;
470 let funding_outpoint = item.2;
471 chain_monitor.watch_channel(funding_outpoint, channel_monitor).unwrap();
474 // Step 11: Optional: Initialize the NetGraphMsgHandler
475 let genesis = genesis_block(args.network).header.block_hash();
476 let network_graph_path = format!("{}/network_graph", ldk_data_dir.clone());
477 let network_graph = disk::read_network(Path::new(&network_graph_path), genesis);
478 let router = Arc::new(NetGraphMsgHandler::new(
480 None::<Arc<dyn chain::Access + Send + Sync>>,
483 let router_persist = Arc::clone(&router);
484 tokio::spawn(async move {
485 let mut interval = tokio::time::interval(Duration::from_secs(600));
487 interval.tick().await;
488 if disk::persist_network(Path::new(&network_graph_path), &router_persist.network_graph)
491 // Persistence errors here are non-fatal as we can just fetch the routing graph
492 // again later, but they may indicate a disk error which could be fatal elsewhere.
494 "Warning: Failed to persist network graph, check your disk and permissions"
500 // Step 12: Initialize the PeerManager
501 let channel_manager: Arc<ChannelManager> = Arc::new(channel_manager);
502 let mut ephemeral_bytes = [0; 32];
503 rand::thread_rng().fill_bytes(&mut ephemeral_bytes);
504 let lightning_msg_handler =
505 MessageHandler { chan_handler: channel_manager.clone(), route_handler: router.clone() };
506 let peer_manager: Arc<PeerManager> = Arc::new(PeerManager::new(
507 lightning_msg_handler,
508 keys_manager.get_node_secret(),
511 Arc::new(IgnoringMessageHandler {}),
515 // Step 13: Initialize networking
517 let peer_manager_connection_handler = peer_manager.clone();
518 let listening_port = args.ldk_peer_listening_port;
519 tokio::spawn(async move {
520 let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", listening_port))
522 .expect("Failed to bind to listen port - is something else already listening on it?");
524 let peer_mgr = peer_manager_connection_handler.clone();
525 let tcp_stream = listener.accept().await.unwrap().0;
526 tokio::spawn(async move {
527 lightning_net_tokio::setup_inbound(
529 tcp_stream.into_std().unwrap(),
536 // Step 14: Connect and Disconnect Blocks
537 if chain_tip.is_none() {
539 Some(init::validate_best_block_header(&mut bitcoind_client.deref()).await.unwrap());
541 let channel_manager_listener = channel_manager.clone();
542 let chain_monitor_listener = chain_monitor.clone();
543 let bitcoind_block_source = bitcoind_client.clone();
544 let network = args.network;
545 tokio::spawn(async move {
546 let mut derefed = bitcoind_block_source.deref();
547 let chain_poller = poll::ChainPoller::new(&mut derefed, network);
548 let chain_listener = (chain_monitor_listener, channel_manager_listener);
550 SpvClient::new(chain_tip.unwrap(), chain_poller, &mut cache, &chain_listener);
552 spv_client.poll_best_tip().await.unwrap();
553 tokio::time::sleep(Duration::from_secs(1)).await;
557 // Step 15: Handle LDK Events
558 let channel_manager_event_listener = channel_manager.clone();
559 let keys_manager_listener = keys_manager.clone();
560 // TODO: persist payment info to disk
561 let inbound_payments: PaymentInfoStorage = Arc::new(Mutex::new(HashMap::new()));
562 let outbound_payments: PaymentInfoStorage = Arc::new(Mutex::new(HashMap::new()));
563 let inbound_pmts_for_events = inbound_payments.clone();
564 let outbound_pmts_for_events = outbound_payments.clone();
565 let network = args.network;
566 let bitcoind_rpc = bitcoind_client.clone();
567 let handle = tokio::runtime::Handle::current();
568 let event_handler = move |event: &Event| {
569 handle.block_on(handle_ldk_events(
570 channel_manager_event_listener.clone(),
571 bitcoind_rpc.clone(),
572 keys_manager_listener.clone(),
573 inbound_pmts_for_events.clone(),
574 outbound_pmts_for_events.clone(),
579 // Step 16: Persist ChannelManager
580 let data_dir = ldk_data_dir.clone();
581 let persist_channel_manager_callback =
582 move |node: &ChannelManager| FilesystemPersister::persist_manager(data_dir.clone(), &*node);
583 // Step 17: Background Processing
584 let background_processor = BackgroundProcessor::start(
585 persist_channel_manager_callback,
587 chain_monitor.clone(),
588 channel_manager.clone(),
589 Some(router.clone()),
590 peer_manager.clone(),
594 // Reconnect to channel peers if possible.
595 let peer_data_path = format!("{}/channel_peer_data", ldk_data_dir.clone());
596 match disk::read_channel_peer_data(Path::new(&peer_data_path)) {
598 for (pubkey, peer_addr) in info.drain() {
599 for chan_info in channel_manager.list_channels() {
600 if pubkey == chan_info.counterparty.node_id {
602 cli::connect_peer_if_necessary(pubkey, peer_addr, peer_manager.clone())
608 Err(e) => println!("ERROR: errored reading channel peer info from disk: {:?}", e),
611 // Regularly broadcast our node_announcement. This is only required (or possible) if we have
612 // some public channels, and is only useful if we have public listen address(es) to announce.
613 // In a production environment, this should occur only after the announcement of new channels
614 // to avoid churn in the global network graph.
615 let chan_manager = Arc::clone(&channel_manager);
616 let network = args.network;
617 if !args.ldk_announced_listen_addr.is_empty() {
618 tokio::spawn(async move {
619 let mut interval = tokio::time::interval(Duration::from_secs(60));
621 interval.tick().await;
622 chan_manager.broadcast_node_announcement(
624 args.ldk_announced_node_name,
625 args.ldk_announced_listen_addr.clone(),
632 cli::poll_for_user_input(
633 peer_manager.clone(),
634 channel_manager.clone(),
635 keys_manager.clone(),
639 ldk_data_dir.clone(),
645 // Stop the background processor.
646 background_processor.stop().unwrap();
650 pub async fn main() {