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::{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;
132 let change_output_position = funded_tx.changepos;
133 assert!(change_output_position == 0 || change_output_position == 1);
135 // Sign the final funding transaction and broadcast it.
136 let signed_tx = bitcoind_client.sign_raw_transaction_with_wallet(funded_tx.hex).await;
137 assert_eq!(signed_tx.complete, true);
138 let final_tx: Transaction =
139 encode::deserialize(&hex_utils::to_vec(&signed_tx.hex).unwrap()).unwrap();
140 // Give the funding transaction back to LDK for opening the channel.
142 .funding_transaction_generated(&temporary_channel_id, final_tx)
146 "\nERROR: Channel went away before we could fund it. The peer disconnected or refused the channel.");
148 io::stdout().flush().unwrap();
151 Event::PaymentReceived { payment_hash, purpose, amt, .. } => {
152 let mut payments = inbound_payments.lock().unwrap();
153 let (payment_preimage, payment_secret) = match purpose {
154 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
155 (payment_preimage, Some(payment_secret))
157 PaymentPurpose::SpontaneousPayment(preimage) => (Some(preimage), None),
159 let status = match channel_manager.claim_funds(payment_preimage.unwrap()) {
162 "\nEVENT: received payment from payment hash {} of {} millisatoshis",
163 hex_utils::hex_str(&payment_hash.0),
167 io::stdout().flush().unwrap();
168 HTLCStatus::Succeeded
170 _ => HTLCStatus::Failed,
172 match payments.entry(payment_hash) {
173 Entry::Occupied(mut e) => {
174 let payment = e.get_mut();
175 payment.status = status;
176 payment.preimage = payment_preimage;
177 payment.secret = payment_secret;
179 Entry::Vacant(e) => {
180 e.insert(PaymentInfo {
181 preimage: payment_preimage,
182 secret: payment_secret,
184 amt_msat: MillisatAmount(Some(amt)),
189 Event::PaymentSent { payment_preimage } => {
190 let hashed = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
191 let mut payments = outbound_payments.lock().unwrap();
192 for (payment_hash, payment) in payments.iter_mut() {
193 if *payment_hash == hashed {
194 payment.preimage = Some(payment_preimage);
195 payment.status = HTLCStatus::Succeeded;
197 "\nEVENT: successfully sent payment of {} millisatoshis from \
198 payment hash {:?} with preimage {:?}",
200 hex_utils::hex_str(&payment_hash.0),
201 hex_utils::hex_str(&payment_preimage.0)
204 io::stdout().flush().unwrap();
208 Event::PaymentFailed { payment_hash, rejected_by_dest } => {
210 "\nEVENT: Failed to send payment to payment hash {:?}: ",
211 hex_utils::hex_str(&payment_hash.0)
213 if rejected_by_dest {
214 println!("re-attempting the payment will not succeed");
216 println!("payment may be retried");
219 io::stdout().flush().unwrap();
221 let mut payments = outbound_payments.lock().unwrap();
222 if payments.contains_key(&payment_hash) {
223 let payment = payments.get_mut(&payment_hash).unwrap();
224 payment.status = HTLCStatus::Failed;
227 Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
228 let from_onchain_str = if claim_from_onchain_tx {
229 "from onchain downstream claim"
231 "from HTLC fulfill message"
233 if let Some(fee_earned) = fee_earned_msat {
235 "\nEVENT: Forwarded payment, earning {} msat {}",
236 fee_earned, from_onchain_str
239 println!("\nEVENT: Forwarded payment, claiming onchain {}", from_onchain_str);
242 io::stdout().flush().unwrap();
244 Event::PendingHTLCsForwardable { time_forwardable } => {
245 let forwarding_channel_manager = channel_manager.clone();
246 tokio::spawn(async move {
247 let min = time_forwardable.as_millis() as u64;
248 let millis_to_sleep = thread_rng().gen_range(min, min * 5) as u64;
249 tokio::time::sleep(Duration::from_millis(millis_to_sleep)).await;
250 forwarding_channel_manager.process_pending_htlc_forwards();
253 Event::SpendableOutputs { outputs } => {
254 let destination_address = bitcoind_client.get_new_address().await;
255 let output_descriptors = &outputs.iter().map(|a| a).collect::<Vec<_>>();
257 bitcoind_client.get_est_sat_per_1000_weight(ConfirmationTarget::Normal);
258 let spending_tx = keys_manager
259 .spend_spendable_outputs(
262 destination_address.script_pubkey(),
267 bitcoind_client.broadcast_transaction(&spending_tx);
272 async fn start_ldk() {
273 let args = match cli::parse_startup_args() {
274 Ok(user_args) => user_args,
278 // Initialize the LDK data directory if necessary.
279 let ldk_data_dir = format!("{}/.ldk", args.ldk_storage_dir_path);
280 fs::create_dir_all(ldk_data_dir.clone()).unwrap();
282 // Initialize our bitcoind client.
283 let bitcoind_client = match BitcoindClient::new(
284 args.bitcoind_rpc_host.clone(),
285 args.bitcoind_rpc_port,
286 args.bitcoind_rpc_username.clone(),
287 args.bitcoind_rpc_password.clone(),
291 Ok(client) => Arc::new(client),
293 println!("Failed to connect to bitcoind client: {}", e);
298 // Check that the bitcoind we've connected to is running the network we expect
299 let bitcoind_chain = bitcoind_client.get_blockchain_info().await.chain;
301 != match args.network {
302 bitcoin::Network::Bitcoin => "main",
303 bitcoin::Network::Testnet => "test",
304 bitcoin::Network::Regtest => "regtest",
305 bitcoin::Network::Signet => "signet",
308 "Chain argument ({}) didn't match bitcoind chain ({})",
309 args.network, bitcoind_chain
315 // Step 1: Initialize the FeeEstimator
317 // BitcoindClient implements the FeeEstimator trait, so it'll act as our fee estimator.
318 let fee_estimator = bitcoind_client.clone();
320 // Step 2: Initialize the Logger
321 let logger = Arc::new(FilesystemLogger::new(ldk_data_dir.clone()));
323 // Step 3: Initialize the BroadcasterInterface
325 // BitcoindClient implements the BroadcasterInterface trait, so it'll act as our transaction
327 let broadcaster = bitcoind_client.clone();
329 // Step 4: Initialize Persist
330 let persister = Arc::new(FilesystemPersister::new(ldk_data_dir.clone()));
332 // Step 5: Initialize the ChainMonitor
333 let chain_monitor: Arc<ChainMonitor> = Arc::new(chainmonitor::ChainMonitor::new(
337 fee_estimator.clone(),
341 // Step 6: Initialize the KeysManager
343 // The key seed that we use to derive the node privkey (that corresponds to the node pubkey) and
344 // other secret key material.
345 let keys_seed_path = format!("{}/keys_seed", ldk_data_dir.clone());
346 let keys_seed = if let Ok(seed) = fs::read(keys_seed_path.clone()) {
347 assert_eq!(seed.len(), 32);
348 let mut key = [0; 32];
349 key.copy_from_slice(&seed);
352 let mut key = [0; 32];
353 thread_rng().fill_bytes(&mut key);
354 match File::create(keys_seed_path.clone()) {
356 f.write_all(&key).expect("Failed to write node keys seed to disk");
357 f.sync_all().expect("Failed to sync node keys seed to disk");
360 println!("ERROR: Unable to create keys seed file {}: {}", keys_seed_path, e);
366 let cur = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
367 let keys_manager = Arc::new(KeysManager::new(&keys_seed, cur.as_secs(), cur.subsec_nanos()));
369 // Step 7: Read ChannelMonitor state from disk
370 let mut channelmonitors = persister.read_channelmonitors(keys_manager.clone()).unwrap();
372 // Step 8: Initialize the ChannelManager
373 let mut user_config = UserConfig::default();
374 user_config.peer_channel_config_limits.force_announced_channel_preference = false;
375 let mut restarting_node = true;
376 let (channel_manager_blockhash, mut channel_manager) = {
377 if let Ok(mut f) = fs::File::open(format!("{}/manager", ldk_data_dir.clone())) {
378 let mut channel_monitor_mut_references = Vec::new();
379 for (_, channel_monitor) in channelmonitors.iter_mut() {
380 channel_monitor_mut_references.push(channel_monitor);
382 let read_args = ChannelManagerReadArgs::new(
383 keys_manager.clone(),
384 fee_estimator.clone(),
385 chain_monitor.clone(),
389 channel_monitor_mut_references,
391 <(BlockHash, ChannelManager)>::read(&mut f, read_args).unwrap()
393 // We're starting a fresh node.
394 restarting_node = false;
395 let getinfo_resp = bitcoind_client.get_blockchain_info().await;
397 let chain_params = ChainParameters {
398 network: args.network,
399 best_block: BestBlock::new(
400 getinfo_resp.latest_blockhash,
401 getinfo_resp.latest_height as u32,
404 let fresh_channel_manager = channelmanager::ChannelManager::new(
405 fee_estimator.clone(),
406 chain_monitor.clone(),
409 keys_manager.clone(),
413 (getinfo_resp.latest_blockhash, fresh_channel_manager)
417 // Step 9: Sync ChannelMonitors and ChannelManager to chain tip
418 let mut chain_listener_channel_monitors = Vec::new();
419 let mut cache = UnboundedCache::new();
420 let mut chain_tip: Option<poll::ValidatedBlockHeader> = None;
422 let mut chain_listeners =
423 vec![(channel_manager_blockhash, &mut channel_manager as &mut dyn chain::Listen)];
425 for (blockhash, channel_monitor) in channelmonitors.drain(..) {
426 let outpoint = channel_monitor.get_funding_txo().0;
427 chain_listener_channel_monitors.push((
429 (channel_monitor, broadcaster.clone(), fee_estimator.clone(), logger.clone()),
434 for monitor_listener_info in chain_listener_channel_monitors.iter_mut() {
435 chain_listeners.push((
436 monitor_listener_info.0,
437 &mut monitor_listener_info.1 as &mut dyn chain::Listen,
441 init::synchronize_listeners(
442 &mut bitcoind_client.deref(),
452 // Step 10: Give ChannelMonitors to ChainMonitor
453 for item in chain_listener_channel_monitors.drain(..) {
454 let channel_monitor = item.1 .0;
455 let funding_outpoint = item.2;
456 chain_monitor.watch_channel(funding_outpoint, channel_monitor).unwrap();
459 // Step 11: Optional: Initialize the NetGraphMsgHandler
460 let genesis = genesis_block(args.network).header.block_hash();
461 let network_graph_path = format!("{}/network_graph", ldk_data_dir.clone());
462 let network_graph = disk::read_network(Path::new(&network_graph_path), genesis);
463 let router = Arc::new(NetGraphMsgHandler::from_net_graph(
464 None::<Arc<dyn chain::Access + Send + Sync>>,
468 let router_persist = Arc::clone(&router);
469 tokio::spawn(async move {
470 let mut interval = tokio::time::interval(Duration::from_secs(600));
472 interval.tick().await;
473 if disk::persist_network(
474 Path::new(&network_graph_path),
475 &*router_persist.network_graph.read().unwrap(),
479 // Persistence errors here are non-fatal as we can just fetch the routing graph
480 // again later, but they may indicate a disk error which could be fatal elsewhere.
482 "Warning: Failed to persist network graph, check your disk and permissions"
488 // Step 12: Initialize the PeerManager
489 let channel_manager: Arc<ChannelManager> = Arc::new(channel_manager);
490 let mut ephemeral_bytes = [0; 32];
491 rand::thread_rng().fill_bytes(&mut ephemeral_bytes);
492 let lightning_msg_handler =
493 MessageHandler { chan_handler: channel_manager.clone(), route_handler: router.clone() };
494 let peer_manager: Arc<PeerManager> = Arc::new(PeerManager::new(
495 lightning_msg_handler,
496 keys_manager.get_node_secret(),
502 // Step 13: Initialize networking
504 let peer_manager_connection_handler = peer_manager.clone();
505 let listening_port = args.ldk_peer_listening_port;
506 tokio::spawn(async move {
507 let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", listening_port))
509 .expect("Failed to bind to listen port - is something else already listening on it?");
511 let peer_mgr = peer_manager_connection_handler.clone();
512 let tcp_stream = listener.accept().await.unwrap().0;
513 tokio::spawn(async move {
514 lightning_net_tokio::setup_inbound(
516 tcp_stream.into_std().unwrap(),
523 // Step 14: Connect and Disconnect Blocks
524 if chain_tip.is_none() {
526 Some(init::validate_best_block_header(&mut bitcoind_client.deref()).await.unwrap());
528 let channel_manager_listener = channel_manager.clone();
529 let chain_monitor_listener = chain_monitor.clone();
530 let bitcoind_block_source = bitcoind_client.clone();
531 let network = args.network;
532 tokio::spawn(async move {
533 let mut derefed = bitcoind_block_source.deref();
534 let chain_poller = poll::ChainPoller::new(&mut derefed, network);
535 let chain_listener = (chain_monitor_listener, channel_manager_listener);
537 SpvClient::new(chain_tip.unwrap(), chain_poller, &mut cache, &chain_listener);
539 spv_client.poll_best_tip().await.unwrap();
540 tokio::time::sleep(Duration::from_secs(1)).await;
544 // Step 15: Handle LDK Events
545 let channel_manager_event_listener = channel_manager.clone();
546 let keys_manager_listener = keys_manager.clone();
547 // TODO: persist payment info to disk
548 let inbound_payments: PaymentInfoStorage = Arc::new(Mutex::new(HashMap::new()));
549 let outbound_payments: PaymentInfoStorage = Arc::new(Mutex::new(HashMap::new()));
550 let inbound_pmts_for_events = inbound_payments.clone();
551 let outbound_pmts_for_events = outbound_payments.clone();
552 let network = args.network;
553 let bitcoind_rpc = bitcoind_client.clone();
554 let handle = tokio::runtime::Handle::current();
555 let event_handler = move |event| {
556 handle.block_on(handle_ldk_events(
557 channel_manager_event_listener.clone(),
558 bitcoind_rpc.clone(),
559 keys_manager_listener.clone(),
560 inbound_pmts_for_events.clone(),
561 outbound_pmts_for_events.clone(),
566 // Step 16: Persist ChannelManager
567 let data_dir = ldk_data_dir.clone();
568 let persist_channel_manager_callback =
569 move |node: &ChannelManager| FilesystemPersister::persist_manager(data_dir.clone(), &*node);
570 // Step 17: Background Processing
571 let background_processor = BackgroundProcessor::start(
572 persist_channel_manager_callback,
574 chain_monitor.clone(),
575 channel_manager.clone(),
576 peer_manager.clone(),
580 // Reconnect to channel peers if possible.
581 let peer_data_path = format!("{}/channel_peer_data", ldk_data_dir.clone());
582 match disk::read_channel_peer_data(Path::new(&peer_data_path)) {
584 for (pubkey, peer_addr) in info.drain() {
585 for chan_info in channel_manager.list_channels() {
586 if pubkey == chan_info.counterparty.node_id {
588 cli::connect_peer_if_necessary(pubkey, peer_addr, peer_manager.clone())
594 Err(e) => println!("ERROR: errored reading channel peer info from disk: {:?}", e),
597 // Regularly broadcast our node_announcement. This is only required (or possible) if we have
598 // some public channels, and is only useful if we have public listen address(es) to announce.
599 // In a production environment, this should occur only after the announcement of new channels
600 // to avoid churn in the global network graph.
601 let chan_manager = Arc::clone(&channel_manager);
602 let network = args.network;
603 if !args.ldk_announced_listen_addr.is_empty() {
604 tokio::spawn(async move {
605 let mut interval = tokio::time::interval(Duration::from_secs(60));
607 interval.tick().await;
608 chan_manager.broadcast_node_announcement(
610 args.ldk_announced_node_name,
611 args.ldk_announced_listen_addr.clone(),
618 cli::poll_for_user_input(
619 peer_manager.clone(),
620 channel_manager.clone(),
621 keys_manager.clone(),
625 ldk_data_dir.clone(),
631 // Stop the background processor.
632 background_processor.stop().unwrap();
636 pub async fn main() {