[[package]]
name = "lightning"
-version = "0.0.113"
+version = "0.0.114"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "087add70f81d2fdc6d4409bc0cef69e11ad366ef1d0068550159bd22b3ac8664"
+checksum = "800ec68a160529ba3ca12c5db629867c4a8de2df272792c1246602966a5b789b"
dependencies = [
"bitcoin",
]
[[package]]
name = "lightning-background-processor"
-version = "0.0.113"
+version = "0.0.114"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2288d211a2ab15e2c9fb492fb99c7998df1a37f228552f703824ee678b8980c9"
+checksum = "7af76b912df8827d9e6bde2fadbbb7b1e2d04f7da92009d244394bd2faa37380"
dependencies = [
"bitcoin",
"lightning",
[[package]]
name = "lightning-block-sync"
-version = "0.0.113"
+version = "0.0.114"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e2fc7227008536500026866e90d5e2db2da2725c5cdc7d19013df743d9de3e68"
+checksum = "71a6fcb6ffc245cf0aee4a4654145a2a7e670be2d879c14b8ed456cdc4235255"
dependencies = [
"bitcoin",
"chunked_transfer",
[[package]]
name = "lightning-invoice"
-version = "0.21.0"
+version = "0.22.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e9680857590c3529cf8c7d32b04501f215f2bf1e029fdfa22f4112f66c1741e4"
+checksum = "adfb59c6d13e130aece30fc72a7c17d74b201aed0ffb201b740f36e07aaece32"
dependencies = [
"bech32 0.9.1",
"bitcoin_hashes",
[[package]]
name = "lightning-net-tokio"
-version = "0.0.113"
+version = "0.0.114"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2e94b019ffcbd423c67bc8e65093d46cf5c00ff696b4b633936fce6e4d0cb845"
+checksum = "19197703db1195ed908ccd84cd76baaa5916e0d22750a2e1b7188f66516812bd"
dependencies = [
"bitcoin",
"lightning",
[[package]]
name = "lightning-persister"
-version = "0.0.113"
+version = "0.0.114"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "48b28023f8b84764e0b861389fc865a1a1dc3896616a14678ece389b0811fe04"
+checksum = "fce2d2ebf01ec7c9f4fad02846207999118a4ec3992c06d6eab93df7a862066c"
dependencies = [
"bitcoin",
"libc",
[[package]]
name = "lightning-rapid-gossip-sync"
-version = "0.0.113"
+version = "0.0.114"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "488b68c7d24093d35a83f37c560e427f1085f4c5d37918b81b11d95cd3675a0f"
+checksum = "6073e6cac4019f39e0bb02d3c92ebbb22950a46a663059b3b0e19f7928e00edb"
dependencies = [
"bitcoin",
"lightning",
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
-lightning = { version = "0.0.113", features = ["max_level_trace"] }
-lightning-block-sync = { version = "0.0.113", features = [ "rpc-client" ] }
-lightning-invoice = { version = "0.21" }
-lightning-net-tokio = { version = "0.0.113" }
-lightning-persister = { version = "0.0.113" }
-lightning-background-processor = { version = "0.0.113" }
-lightning-rapid-gossip-sync = { version = "0.0.113" }
+lightning = { version = "0.0.114", features = ["max_level_trace"] }
+lightning-block-sync = { version = "0.0.114", features = [ "rpc-client" ] }
+lightning-invoice = { version = "0.22" }
+lightning-net-tokio = { version = "0.0.114" }
+lightning-persister = { version = "0.0.114" }
+lightning-background-processor = { version = "0.0.114" }
+lightning-rapid-gossip-sync = { version = "0.0.114" }
base64 = "0.13.0"
bitcoin = "0.29.0"
use bitcoin::hash_types::{BlockHash, Txid};
use bitcoin::util::address::Address;
use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
+use lightning::routing::utxo::{UtxoLookup, UtxoResult};
use lightning_block_sync::http::HttpEndpoint;
use lightning_block_sync::rpc::RpcClient;
use lightning_block_sync::{AsyncBlockSourceResult, BlockData, BlockHeaderData, BlockSource};
});
}
}
+
+impl UtxoLookup for BitcoindClient {
+ fn get_utxo(&self, _genesis_hash: &BlockHash, _short_channel_id: u64) -> UtxoResult {
+ // P2PGossipSync takes None for a UtxoLookup, so this will never be called.
+ todo!();
+ }
+}
use crate::disk;
use crate::hex_utils;
use crate::{
- ChannelManager, HTLCStatus, InvoicePayer, MillisatAmount, NetworkGraph, OnionMessenger,
- PaymentInfo, PaymentInfoStorage, PeerManager,
+ ChannelManager, HTLCStatus, MillisatAmount, NetworkGraph, OnionMessenger, PaymentInfo,
+ PaymentInfoStorage, PeerManager,
};
use bitcoin::hashes::sha256::Hash as Sha256;
use bitcoin::hashes::Hash;
use bitcoin::network::constants::Network;
use bitcoin::secp256k1::PublicKey;
-use lightning::chain::keysinterface::{KeysInterface, KeysManager, Recipient};
-use lightning::ln::msgs::{DecodeError, NetAddress};
+use lightning::chain::keysinterface::{EntropySource, KeysManager};
+use lightning::ln::channelmanager::{PaymentId, Retry};
+use lightning::ln::msgs::NetAddress;
use lightning::ln::{PaymentHash, PaymentPreimage};
use lightning::onion_message::{CustomOnionMessageContents, Destination, OnionMessageContents};
use lightning::routing::gossip::NodeId;
+use lightning::routing::router::{PaymentParameters, RouteParameters};
use lightning::util::config::{ChannelHandshakeConfig, ChannelHandshakeLimits, UserConfig};
-use lightning::util::events::EventHandler;
use lightning::util::ser::{Writeable, Writer};
-use lightning_invoice::payment::PaymentError;
+use lightning_invoice::payment::pay_invoice;
use lightning_invoice::{utils, Currency, Invoice};
use std::env;
use std::io;
}
}
-pub(crate) async fn poll_for_user_input<E: EventHandler>(
- invoice_payer: Arc<InvoicePayer<E>>, peer_manager: Arc<PeerManager>,
- channel_manager: Arc<ChannelManager>, keys_manager: Arc<KeysManager>,
- network_graph: Arc<NetworkGraph>, onion_messenger: Arc<OnionMessenger>,
- inbound_payments: PaymentInfoStorage, outbound_payments: PaymentInfoStorage,
- ldk_data_dir: String, network: Network, logger: Arc<disk::FilesystemLogger>,
+pub(crate) async fn poll_for_user_input(
+ peer_manager: Arc<PeerManager>, channel_manager: Arc<ChannelManager>,
+ keys_manager: Arc<KeysManager>, network_graph: Arc<NetworkGraph>,
+ onion_messenger: Arc<OnionMessenger>, inbound_payments: PaymentInfoStorage,
+ outbound_payments: PaymentInfoStorage, ldk_data_dir: String, network: Network,
+ logger: Arc<disk::FilesystemLogger>,
) {
println!(
"LDK startup successful. Enter \"help\" to view available commands. Press Ctrl-D to quit."
}
};
- send_payment(&*invoice_payer, &invoice, outbound_payments.clone());
+ send_payment(&*channel_manager, &invoice, outbound_payments.clone());
}
"keysend" => {
let dest_pubkey = match words.next() {
}
};
keysend(
- &*invoice_payer,
+ &*channel_manager,
dest_pubkey,
amt_msat,
&*keys_manager,
"{:?}",
lightning::util::message_signing::sign(
&line.as_bytes()[MSG_STARTPOS..],
- &keys_manager.get_node_secret(Recipient::Node).unwrap()
+ &keys_manager.get_node_secret_key()
)
);
}
fn list_peers(peer_manager: Arc<PeerManager>) {
println!("\t{{");
- for pubkey in peer_manager.get_peer_node_ids() {
+ for (pubkey, _) in peer_manager.get_peer_node_ids() {
println!("\t\t pubkey: {}", pubkey);
}
println!("\t}},");
pub(crate) async fn connect_peer_if_necessary(
pubkey: PublicKey, peer_addr: SocketAddr, peer_manager: Arc<PeerManager>,
) -> Result<(), ()> {
- for node_pubkey in peer_manager.get_peer_node_ids() {
+ for (node_pubkey, _) in peer_manager.get_peer_node_ids() {
if node_pubkey == pubkey {
return Ok(());
}
std::task::Poll::Pending => {}
}
// Avoid blocking the tokio context by sleeping a bit
- match peer_manager.get_peer_node_ids().iter().find(|id| **id == pubkey) {
+ match peer_manager.get_peer_node_ids().iter().find(|(id, _)| *id == pubkey) {
Some(_) => return Ok(()),
None => tokio::time::sleep(Duration::from_millis(10)).await,
}
//check the pubkey matches a valid connected peer
let peers = peer_manager.get_peer_node_ids();
- if !peers.contains(&pubkey) {
+ if !peers.iter().any(|(pk, _)| &pubkey == pk) {
println!("Error: Could not find peer {}", pubkey);
return Err(());
}
- peer_manager.disconnect_by_node_id(pubkey, false);
+ peer_manager.disconnect_by_node_id(pubkey);
Ok(())
}
}
}
-fn send_payment<E: EventHandler>(
- invoice_payer: &InvoicePayer<E>, invoice: &Invoice, payment_storage: PaymentInfoStorage,
+fn send_payment(
+ channel_manager: &ChannelManager, invoice: &Invoice, payment_storage: PaymentInfoStorage,
) {
- let status = match invoice_payer.pay_invoice(invoice) {
- Ok(_payment_id) => {
- let payee_pubkey = invoice.recover_payee_pub_key();
- let amt_msat = invoice.amount_milli_satoshis().unwrap();
- println!("EVENT: initiated sending {} msats to {}", amt_msat, payee_pubkey);
- print!("> ");
- HTLCStatus::Pending
- }
- Err(PaymentError::Invoice(e)) => {
- println!("ERROR: invalid invoice: {}", e);
- print!("> ");
- return;
- }
- Err(PaymentError::Routing(e)) => {
- println!("ERROR: failed to find route: {}", e.err);
- print!("> ");
- return;
- }
- Err(PaymentError::Sending(e)) => {
- println!("ERROR: failed to send payment: {:?}", e);
- print!("> ");
- HTLCStatus::Failed
- }
- };
+ let status =
+ match pay_invoice(invoice, Retry::Timeout(Duration::from_secs(10)), channel_manager) {
+ Ok(_payment_id) => {
+ let payee_pubkey = invoice.recover_payee_pub_key();
+ let amt_msat = invoice.amount_milli_satoshis().unwrap();
+ println!("EVENT: initiated sending {} msats to {}", amt_msat, payee_pubkey);
+ print!("> ");
+ HTLCStatus::Pending
+ }
+ Err(e) => {
+ println!("ERROR: failed to send payment: {:?}", e);
+ print!("> ");
+ HTLCStatus::Failed
+ }
+ };
let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
let payment_secret = Some(invoice.payment_secret().clone());
);
}
-fn keysend<E: EventHandler, K: KeysInterface>(
- invoice_payer: &InvoicePayer<E>, payee_pubkey: PublicKey, amt_msat: u64, keys: &K,
+fn keysend<E: EntropySource>(
+ channel_manager: &ChannelManager, payee_pubkey: PublicKey, amt_msat: u64, entropy_source: &E,
payment_storage: PaymentInfoStorage,
) {
- let payment_preimage = keys.get_secure_random_bytes();
+ let payment_preimage = PaymentPreimage(entropy_source.get_secure_random_bytes());
+ let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
- let status = match invoice_payer.pay_pubkey(
- payee_pubkey,
- PaymentPreimage(payment_preimage),
- amt_msat,
- 40,
+ let route_params = RouteParameters {
+ payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
+ final_value_msat: amt_msat,
+ };
+ let status = match channel_manager.send_spontaneous_payment_with_retry(
+ Some(payment_preimage),
+ PaymentId(payment_hash.0),
+ route_params,
+ Retry::Timeout(Duration::from_secs(10)),
) {
- Ok(_payment_id) => {
+ Ok(_payment_hash) => {
println!("EVENT: initiated sending {} msats to {}", amt_msat, payee_pubkey);
print!("> ");
HTLCStatus::Pending
}
- Err(PaymentError::Invoice(e)) => {
- println!("ERROR: invalid payee: {}", e);
- print!("> ");
- return;
- }
- Err(PaymentError::Routing(e)) => {
- println!("ERROR: failed to find route: {}", e.err);
- print!("> ");
- return;
- }
- Err(PaymentError::Sending(e)) => {
+ Err(e) => {
println!("ERROR: failed to send payment: {:?}", e);
print!("> ");
HTLCStatus::Failed
let mut payments = payment_storage.lock().unwrap();
payments.insert(
- PaymentHash(Sha256::hash(&payment_preimage).into_inner()),
+ payment_hash,
PaymentInfo {
preimage: None,
secret: None,
Some(amt_msat),
"ldk-tutorial-node".to_string(),
expiry_secs,
+ None,
) {
Ok(inv) => {
println!("SUCCESS: generated invoice: {}", inv);
use crate::{cli, NetworkGraph};
use bitcoin::secp256k1::PublicKey;
-use bitcoin::BlockHash;
+use bitcoin::Network;
use chrono::Utc;
use lightning::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
use lightning::util::logger::{Logger, Record};
}
pub(crate) fn read_network(
- path: &Path, genesis_hash: BlockHash, logger: Arc<FilesystemLogger>,
+ path: &Path, network: Network, logger: Arc<FilesystemLogger>,
) -> NetworkGraph {
if let Ok(file) = File::open(path) {
if let Ok(graph) = NetworkGraph::read(&mut BufReader::new(file), logger.clone()) {
return graph;
}
}
- NetworkGraph::new(genesis_hash, logger)
+ NetworkGraph::new(network, logger)
}
pub(crate) fn read_scorer(
use crate::bitcoind_client::BitcoindClient;
use crate::disk::FilesystemLogger;
-use bitcoin::blockdata::constants::genesis_block;
use bitcoin::blockdata::transaction::Transaction;
use bitcoin::consensus::encode;
use bitcoin::network::constants::Network;
use bitcoin_bech32::WitnessProgram;
use lightning::chain;
use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
-use lightning::chain::keysinterface::{InMemorySigner, KeysInterface, KeysManager, Recipient};
+use lightning::chain::keysinterface::{EntropySource, InMemorySigner, KeysManager};
use lightning::chain::{chainmonitor, ChannelMonitorUpdateStatus};
use lightning::chain::{Filter, Watch};
use lightning::ln::channelmanager;
use lightning::routing::gossip;
use lightning::routing::gossip::{NodeId, P2PGossipSync};
use lightning::routing::router::DefaultRouter;
-use lightning::routing::scoring::ProbabilisticScorer;
use lightning::util::config::UserConfig;
use lightning::util::events::{Event, PaymentPurpose};
use lightning::util::ser::ReadableArgs;
use lightning_block_sync::poll;
use lightning_block_sync::SpvClient;
use lightning_block_sync::UnboundedCache;
-use lightning_invoice::payment;
use lightning_net_tokio::SocketDescriptor;
use lightning_persister::FilesystemPersister;
use rand::{thread_rng, Rng};
ChainMonitor,
BitcoindClient,
BitcoindClient,
- dyn chain::Access + Send + Sync,
+ BitcoindClient,
FilesystemLogger,
>;
pub(crate) type ChannelManager =
SimpleArcChannelManager<ChainMonitor, BitcoindClient, BitcoindClient, FilesystemLogger>;
-pub(crate) type InvoicePayer<E> =
- payment::InvoicePayer<Arc<ChannelManager>, Router, Arc<FilesystemLogger>, E>;
-
-type Router = DefaultRouter<
- Arc<NetworkGraph>,
- Arc<FilesystemLogger>,
- Arc<Mutex<ProbabilisticScorer<Arc<NetworkGraph>, Arc<FilesystemLogger>>>>,
->;
-
pub(crate) type NetworkGraph = gossip::NetworkGraph<Arc<FilesystemLogger>>;
type OnionMessenger = SimpleArcOnionMessenger<FilesystemLogger>;
let keys_manager = Arc::new(KeysManager::new(&keys_seed, cur.as_secs(), cur.subsec_nanos()));
// Step 7: Read ChannelMonitor state from disk
- let mut channelmonitors = persister.read_channelmonitors(keys_manager.clone()).unwrap();
+ let mut channelmonitors =
+ persister.read_channelmonitors(keys_manager.clone(), keys_manager.clone()).unwrap();
// Step 8: Poll for the best chain tip, which may be used by the channel manager & spv client
let polled_chain_tip = init::validate_best_block_header(bitcoind_client.as_ref())
.await
.expect("Failed to fetch best block header and best block");
- // Step 9: Initialize the ChannelManager
+ // Step 9: Initialize routing ProbabilisticScorer
+ let network_graph_path = format!("{}/network_graph", ldk_data_dir.clone());
+ let network_graph =
+ Arc::new(disk::read_network(Path::new(&network_graph_path), args.network, logger.clone()));
+
+ let scorer_path = format!("{}/scorer", ldk_data_dir.clone());
+ let scorer = Arc::new(Mutex::new(disk::read_scorer(
+ Path::new(&scorer_path),
+ Arc::clone(&network_graph),
+ Arc::clone(&logger),
+ )));
+
+ // Step 10: Create Router
+ let router = Arc::new(DefaultRouter::new(
+ network_graph.clone(),
+ logger.clone(),
+ keys_manager.get_secure_random_bytes(),
+ scorer.clone(),
+ ));
+
+ // Step 11: Initialize the ChannelManager
let mut user_config = UserConfig::default();
user_config.channel_handshake_limits.force_announced_channel_preference = false;
let mut restarting_node = true;
channel_monitor_mut_references.push(channel_monitor);
}
let read_args = ChannelManagerReadArgs::new(
+ keys_manager.clone(),
+ keys_manager.clone(),
keys_manager.clone(),
fee_estimator.clone(),
chain_monitor.clone(),
broadcaster.clone(),
+ router,
logger.clone(),
user_config,
channel_monitor_mut_references,
fee_estimator.clone(),
chain_monitor.clone(),
broadcaster.clone(),
+ router,
logger.clone(),
keys_manager.clone(),
+ keys_manager.clone(),
+ keys_manager.clone(),
user_config,
chain_params,
);
}
};
- // Step 10: Sync ChannelMonitors and ChannelManager to chain tip
+ // Step 12: Sync ChannelMonitors and ChannelManager to chain tip
let mut chain_listener_channel_monitors = Vec::new();
let mut cache = UnboundedCache::new();
let chain_tip = if restarting_node {
polled_chain_tip
};
- // Step 11: Give ChannelMonitors to ChainMonitor
+ // Step 13: Give ChannelMonitors to ChainMonitor
for item in chain_listener_channel_monitors.drain(..) {
let channel_monitor = item.1 .0;
let funding_outpoint = item.2;
);
}
- // Step 12: Optional: Initialize the P2PGossipSync
- let genesis = genesis_block(args.network).header.block_hash();
- let network_graph_path = format!("{}/network_graph", ldk_data_dir.clone());
- let network_graph =
- Arc::new(disk::read_network(Path::new(&network_graph_path), genesis, logger.clone()));
+ // Step 14: Optional: Initialize the P2PGossipSync
let gossip_sync = Arc::new(P2PGossipSync::new(
Arc::clone(&network_graph),
- None::<Arc<dyn chain::Access + Send + Sync>>,
+ None::<Arc<BitcoindClient>>,
logger.clone(),
));
- // Step 13: Initialize the PeerManager
+ // Step 15: Initialize the PeerManager
let channel_manager: Arc<ChannelManager> = Arc::new(channel_manager);
let onion_messenger: Arc<OnionMessenger> = Arc::new(OnionMessenger::new(
+ Arc::clone(&keys_manager),
Arc::clone(&keys_manager),
Arc::clone(&logger),
IgnoringMessageHandler {},
};
let peer_manager: Arc<PeerManager> = Arc::new(PeerManager::new(
lightning_msg_handler,
- keys_manager.get_node_secret(Recipient::Node).unwrap(),
current_time.try_into().unwrap(),
&ephemeral_bytes,
logger.clone(),
IgnoringMessageHandler {},
+ Arc::clone(&keys_manager),
));
// ## Running LDK
- // Step 14: Initialize networking
+ // Step 16: Initialize networking
let peer_manager_connection_handler = peer_manager.clone();
let listening_port = args.ldk_peer_listening_port;
}
});
- // Step 15: Connect and Disconnect Blocks
+ // Step 17: Connect and Disconnect Blocks
let channel_manager_listener = channel_manager.clone();
let chain_monitor_listener = chain_monitor.clone();
let bitcoind_block_source = bitcoind_client.clone();
}
});
- // Step 16: Handle LDK Events
+ // Step 18: Handle LDK Events
let channel_manager_event_listener = channel_manager.clone();
let keys_manager_listener = keys_manager.clone();
// TODO: persist payment info to disk
));
};
- // Step 17: Initialize routing ProbabilisticScorer
- let scorer_path = format!("{}/scorer", ldk_data_dir.clone());
- let scorer = Arc::new(Mutex::new(disk::read_scorer(
- Path::new(&scorer_path),
- Arc::clone(&network_graph),
- Arc::clone(&logger),
- )));
-
- // Step 18: Create InvoicePayer
- let router = DefaultRouter::new(
- network_graph.clone(),
- logger.clone(),
- keys_manager.get_secure_random_bytes(),
- scorer.clone(),
- );
- let invoice_payer = Arc::new(InvoicePayer::new(
- channel_manager.clone(),
- router,
- logger.clone(),
- event_handler,
- payment::Retry::Timeout(Duration::from_secs(10)),
- ));
-
// Step 19: Persist ChannelManager and NetworkGraph
let persister = Arc::new(FilesystemPersister::new(ldk_data_dir.clone()));
// Step 20: Background Processing
let background_processor = BackgroundProcessor::start(
persister,
- invoice_payer.clone(),
+ event_handler,
chain_monitor.clone(),
channel_manager.clone(),
GossipSync::p2p(gossip_sync.clone()),
.list_channels()
.iter()
.map(|chan| chan.counterparty.node_id)
- .filter(|id| !peers.contains(id))
+ .filter(|id| !peers.iter().any(|(pk, _)| id == pk))
{
if stop_connect.load(Ordering::Acquire) {
return;
// Start the CLI.
cli::poll_for_user_input(
- Arc::clone(&invoice_payer),
Arc::clone(&peer_manager),
Arc::clone(&channel_manager),
Arc::clone(&keys_manager),