use crate::disk;
use crate::hex_utils;
use crate::{
- ChannelManager, FilesystemLogger, HTLCStatus, MillisatAmount, PaymentInfo, PaymentInfoStorage,
- PeerManager,
+ ChannelManager, FilesystemLogger, HTLCStatus, InvoicePayer, MillisatAmount, PaymentInfo,
+ PaymentInfoStorage, PeerManager,
};
use bitcoin::hashes::Hash;
use bitcoin::network::constants::Network;
use bitcoin::secp256k1::key::PublicKey;
use lightning::chain::keysinterface::{KeysInterface, KeysManager};
-use lightning::ln::features::InvoiceFeatures;
use lightning::ln::msgs::NetAddress;
-use lightning::ln::{PaymentHash, PaymentSecret};
+use lightning::ln::PaymentHash;
use lightning::routing::network_graph::NetworkGraph;
use lightning::routing::router;
-use lightning::routing::router::{Payee, RouteHint, RouteParameters};
+use lightning::routing::router::{Payee, RouteParameters};
use lightning::routing::scorer::Scorer;
use lightning::util::config::{ChannelConfig, ChannelHandshakeLimits, UserConfig};
+use lightning::util::events::EventHandler;
+use lightning_invoice::payment::PaymentError;
use lightning_invoice::{utils, Currency, Invoice};
use std::env;
use std::io;
use std::ops::Deref;
use std::path::Path;
use std::str::FromStr;
-use std::sync::Arc;
+use std::sync::{Arc, Mutex};
use std::time::Duration;
pub(crate) struct LdkUserInfo {
})
}
-pub(crate) async fn poll_for_user_input(
- peer_manager: Arc<PeerManager>, channel_manager: Arc<ChannelManager>,
- keys_manager: Arc<KeysManager>, network_graph: Arc<NetworkGraph>,
+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>, scorer: Arc<Mutex<Scorer>>,
inbound_payments: PaymentInfoStorage, outbound_payments: PaymentInfoStorage,
ldk_data_dir: String, logger: Arc<FilesystemLogger>, network: Network,
) {
continue;
}
};
- let last_hops = invoice.route_hints();
- let amt_msat = invoice.amount_milli_satoshis();
- if amt_msat.is_none() {
- println!("ERROR: invalid invoice: must contain amount to pay");
- print!("> ");
- io::stdout().flush().unwrap();
- continue;
- }
-
- let payee_pubkey = invoice.recover_payee_pub_key();
- let final_cltv = invoice.min_final_cltv_expiry() as u32;
- let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
- let payment_secret = Some(invoice.payment_secret().clone());
- let invoice_features = invoice.features().cloned();
-
- send_payment(
- payee_pubkey,
- amt_msat.unwrap(),
- final_cltv,
- payment_hash,
- payment_secret,
- invoice_features,
- last_hops,
- network_graph.clone(),
- channel_manager.clone(),
- outbound_payments.clone(),
- logger.clone(),
- );
+ send_payment(&*invoice_payer, &invoice, outbound_payments.clone());
}
"keysend" => {
let dest_pubkey = match words.next() {
channel_manager.clone(),
outbound_payments.clone(),
logger.clone(),
+ scorer.clone(),
);
}
"getinvoice" => {
}
}
-fn send_payment(
- payee_pubkey: PublicKey, amt_msat: u64, final_cltv: u32, payment_hash: PaymentHash,
- payment_secret: Option<PaymentSecret>, payee_features: Option<InvoiceFeatures>,
- route_hints: Vec<RouteHint>, network_graph: Arc<NetworkGraph>,
- channel_manager: Arc<ChannelManager>, payment_storage: PaymentInfoStorage,
- logger: Arc<FilesystemLogger>,
+fn send_payment<E: EventHandler>(
+ invoice_payer: &InvoicePayer<E>, invoice: &Invoice, payment_storage: PaymentInfoStorage,
) {
- let first_hops = channel_manager.list_usable_channels();
- let payer_pubkey = channel_manager.get_our_node_id();
-
- let mut payee = Payee::from_node_id(payee_pubkey).with_route_hints(route_hints);
- if let Some(features) = payee_features {
- payee = payee.with_features(features);
- }
- let params =
- RouteParameters { payee, final_value_msat: amt_msat, final_cltv_expiry_delta: final_cltv };
-
- let route = router::find_route(
- &payer_pubkey,
- ¶ms,
- &network_graph,
- Some(&first_hops.iter().collect::<Vec<_>>()),
- logger,
- &Scorer::default(),
- );
- if let Err(e) = route {
- println!("ERROR: failed to find route: {}", e.err);
- return;
- }
- let status = match channel_manager.send_payment(&route.unwrap(), payment_hash, &payment_secret)
- {
+ 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(e) => {
+ 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 payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
+ let payment_secret = Some(invoice.payment_secret().clone());
+
let mut payments = payment_storage.lock().unwrap();
payments.insert(
payment_hash,
preimage: None,
secret: payment_secret,
status,
- amt_msat: MillisatAmount(Some(amt_msat)),
+ amt_msat: MillisatAmount(invoice.amount_milli_satoshis()),
},
);
}
fn keysend(
payee_pubkey: PublicKey, amt_msat: u64, network_graph: Arc<NetworkGraph>,
channel_manager: Arc<ChannelManager>, payment_storage: PaymentInfoStorage,
- logger: Arc<FilesystemLogger>,
+ logger: Arc<FilesystemLogger>, scorer: Arc<Mutex<Scorer>>,
) {
let first_hops = channel_manager.list_usable_channels();
let payer_pubkey = channel_manager.get_our_node_id();
&network_graph,
Some(&first_hops.iter().collect::<Vec<_>>()),
logger,
- &Scorer::default(),
+ &scorer.lock().unwrap(),
) {
Ok(r) => r,
Err(e) => {
};
use lightning::ln::peer_handler::{IgnoringMessageHandler, MessageHandler, SimpleArcPeerManager};
use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
-use lightning::routing::network_graph::NetGraphMsgHandler;
+use lightning::routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
+use lightning::routing::scorer::Scorer;
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_invoice::utils::DefaultRouter;
use lightning_net_tokio::SocketDescriptor;
use lightning_persister::FilesystemPersister;
use rand::{thread_rng, Rng};
pub(crate) type ChannelManager =
SimpleArcChannelManager<ChainMonitor, BitcoindClient, BitcoindClient, FilesystemLogger>;
+pub(crate) type InvoicePayer<E> = payment::InvoicePayer<
+ Arc<ChannelManager>,
+ Router,
+ Arc<Mutex<Scorer>>,
+ Arc<FilesystemLogger>,
+ E,
+>;
+
+type Router = DefaultRouter<Arc<NetworkGraph>, Arc<FilesystemLogger>>;
+
async fn handle_ldk_events(
channel_manager: Arc<ChannelManager>, bitcoind_client: Arc<BitcoindClient>,
keys_manager: Arc<KeysManager>, inbound_payments: PaymentInfoStorage,
Event::PaymentPathFailed {
payment_hash,
rejected_by_dest,
- network_update: _,
all_paths_failed,
- path: _,
short_channel_id,
..
} => {
if *rejected_by_dest {
println!(": re-attempting the payment will not succeed");
} else {
- println!(": payment may be retried");
+ println!(": exhausted payment retry attempts");
}
print!("> ");
io::stdout().flush().unwrap();
event,
));
};
- // Step 16: Persist ChannelManager
+
+ // Step 16: Create InvoicePayer
+ let router = DefaultRouter::new(network_graph.clone(), logger.clone());
+ let scorer = Arc::new(Mutex::new(Scorer::default()));
+ let invoice_payer = Arc::new(InvoicePayer::new(
+ channel_manager.clone(),
+ router,
+ scorer.clone(),
+ logger.clone(),
+ event_handler,
+ payment::RetryAttempts(5),
+ ));
+
+ // Step 17: Persist ChannelManager
let data_dir = ldk_data_dir.clone();
let persist_channel_manager_callback =
move |node: &ChannelManager| FilesystemPersister::persist_manager(data_dir.clone(), &*node);
- // Step 17: Background Processing
+
+ // Step 18: Background Processing
let background_processor = BackgroundProcessor::start(
persist_channel_manager_callback,
- event_handler,
+ invoice_payer.clone(),
chain_monitor.clone(),
channel_manager.clone(),
Some(network_gossip.clone()),
// Start the CLI.
cli::poll_for_user_input(
+ invoice_payer.clone(),
peer_manager.clone(),
channel_manager.clone(),
keys_manager.clone(),
network_graph.clone(),
+ scorer.clone(),
inbound_payments,
outbound_payments,
ldk_data_dir.clone(),