--- /dev/null
+name: Continuous Integration Checks
+
+on: [push, pull_request]
+
+jobs:
+ build:
+ strategy:
+ matrix:
+ toolchain: [ stable, beta ]
+ include:
+ - toolchain: stable
+ check-fmt: true
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout source code
+ uses: actions/checkout@v2
+ - name: Install Rust ${{ matrix.toolchain }} toolchain
+ uses: actions-rs/toolchain@v1
+ with:
+ toolchain: ${{ matrix.toolchain }}
+ override: true
+ profile: minimal
+ - name: Build on Rust ${{ matrix.toolchain }}
+ run: cargo build --verbose --color always
+ - name: Check formatting
+ if: matrix.check-fmt
+ run: rustup component add rustfmt && cargo fmt --all -- --check
cd ldk-sample
cargo run <bitcoind-rpc-username>:<bitcoind-rpc-password>@<bitcoind-rpc-host>:<bitcoind-rpc-port> <ldk_storage_directory_path> [<ldk-peer-listening-port>] [bitcoin-network]
```
+`bitcoind`'s RPC username and password likely can be found through `cat ~/.bitcoin/.cookie`.
+
`bitcoin-network`: defaults to `testnet`. Options: `testnet`, `regtest`.
`ldk-peer-listening-port`: defaults to 9735.
## License
-Licensed under either of
+Licensed under either:
* Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
* MIT License ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
--- /dev/null
+hard_tabs = true # use tab characters for indentation, spaces for alignment
+use_field_init_shorthand = true
+max_width = 100
+use_small_heuristics = "Max"
+fn_args_layout = "Compressed"
\ No newline at end of file
+use crate::convert::{BlockchainInfo, FeeResponse, FundedTx, NewAddress, RawTx, SignedTx};
use base64;
use bitcoin::blockdata::transaction::Transaction;
use bitcoin::consensus::encode;
use bitcoin::util::address::Address;
-use crate::convert::{BlockchainInfo, FeeResponse, FundedTx, NewAddress, RawTx, SignedTx};
use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
use lightning_block_sync::http::HttpEndpoint;
use lightning_block_sync::rpc::RpcClient;
use tokio::runtime::{Handle, Runtime};
pub struct BitcoindClient {
- bitcoind_rpc_client: Mutex<RpcClient>,
- host: String,
- port: u16,
- rpc_user: String,
- rpc_password: String,
- runtime: Mutex<Runtime>,
+ bitcoind_rpc_client: Mutex<RpcClient>,
+ host: String,
+ port: u16,
+ rpc_user: String,
+ rpc_password: String,
+ runtime: Mutex<Runtime>,
}
impl BitcoindClient {
- pub fn new(host: String, port: u16, rpc_user: String, rpc_password: String) ->
- std::io::Result<Self>
- {
- let http_endpoint = HttpEndpoint::for_host(host.clone()).with_port(port);
- let rpc_credentials = base64::encode(format!("{}:{}", rpc_user.clone(),
- rpc_password.clone()));
- let bitcoind_rpc_client = RpcClient::new(&rpc_credentials, http_endpoint)?;
- let client = Self {
- bitcoind_rpc_client: Mutex::new(bitcoind_rpc_client),
- host,
- port,
- rpc_user,
- rpc_password,
- runtime: Mutex::new(Runtime::new().unwrap()),
- };
- Ok(client)
- }
-
- pub fn get_new_rpc_client(&self) -> std::io::Result<RpcClient> {
- let http_endpoint = HttpEndpoint::for_host(self.host.clone()).with_port(self.port);
- let rpc_credentials = base64::encode(format!("{}:{}",
- self.rpc_user.clone(),
- self.rpc_password.clone()));
- RpcClient::new(&rpc_credentials, http_endpoint)
- }
-
- pub fn create_raw_transaction(&self, outputs: Vec<HashMap<String, f64>>) -> RawTx {
- let runtime = self.runtime.lock().unwrap();
- let mut rpc = self.bitcoind_rpc_client.lock().unwrap();
-
- let outputs_json = serde_json::json!(outputs);
- runtime.block_on(rpc.call_method::<RawTx>("createrawtransaction", &vec![serde_json::json!([]), outputs_json])).unwrap()
- }
-
- pub fn fund_raw_transaction(&self, raw_tx: RawTx) -> FundedTx {
- let runtime = self.runtime.lock().unwrap();
- let mut rpc = self.bitcoind_rpc_client.lock().unwrap();
-
- let raw_tx_json = serde_json::json!(raw_tx.0);
- runtime.block_on(rpc.call_method("fundrawtransaction", &[raw_tx_json])).unwrap()
- }
-
- pub fn sign_raw_transaction_with_wallet(&self, tx_hex: String) -> SignedTx {
- let runtime = self.runtime.lock().unwrap();
- let mut rpc = self.bitcoind_rpc_client.lock().unwrap();
-
- let tx_hex_json = serde_json::json!(tx_hex);
- runtime.block_on(rpc.call_method("signrawtransactionwithwallet",
- &vec![tx_hex_json])).unwrap()
- }
-
- pub fn get_new_address(&self) -> Address {
- let runtime = self.runtime.lock().unwrap();
- let mut rpc = self.bitcoind_rpc_client.lock().unwrap();
-
- let addr_args = vec![serde_json::json!("LDK output address")];
- let addr = runtime.block_on(rpc.call_method::<NewAddress>("getnewaddress", &addr_args)).unwrap();
- Address::from_str(addr.0.as_str()).unwrap()
- }
-
- pub fn get_blockchain_info(&self) -> BlockchainInfo {
- let runtime = self.runtime.lock().unwrap();
- let mut rpc = self.bitcoind_rpc_client.lock().unwrap();
-
- runtime.block_on(rpc.call_method::<BlockchainInfo>("getblockchaininfo",
- &vec![])).unwrap()
- }
+ pub fn new(
+ host: String, port: u16, rpc_user: String, rpc_password: String,
+ ) -> std::io::Result<Self> {
+ let http_endpoint = HttpEndpoint::for_host(host.clone()).with_port(port);
+ let rpc_credentials =
+ base64::encode(format!("{}:{}", rpc_user.clone(), rpc_password.clone()));
+ let bitcoind_rpc_client = RpcClient::new(&rpc_credentials, http_endpoint)?;
+ let client = Self {
+ bitcoind_rpc_client: Mutex::new(bitcoind_rpc_client),
+ host,
+ port,
+ rpc_user,
+ rpc_password,
+ runtime: Mutex::new(Runtime::new().unwrap()),
+ };
+ Ok(client)
+ }
+
+ pub fn get_new_rpc_client(&self) -> std::io::Result<RpcClient> {
+ let http_endpoint = HttpEndpoint::for_host(self.host.clone()).with_port(self.port);
+ let rpc_credentials =
+ base64::encode(format!("{}:{}", self.rpc_user.clone(), self.rpc_password.clone()));
+ RpcClient::new(&rpc_credentials, http_endpoint)
+ }
+
+ pub fn create_raw_transaction(&self, outputs: Vec<HashMap<String, f64>>) -> RawTx {
+ let runtime = self.runtime.lock().unwrap();
+ let mut rpc = self.bitcoind_rpc_client.lock().unwrap();
+
+ let outputs_json = serde_json::json!(outputs);
+ runtime
+ .block_on(rpc.call_method::<RawTx>(
+ "createrawtransaction",
+ &vec![serde_json::json!([]), outputs_json],
+ ))
+ .unwrap()
+ }
+
+ pub fn fund_raw_transaction(&self, raw_tx: RawTx) -> FundedTx {
+ let runtime = self.runtime.lock().unwrap();
+ let mut rpc = self.bitcoind_rpc_client.lock().unwrap();
+
+ let raw_tx_json = serde_json::json!(raw_tx.0);
+ runtime.block_on(rpc.call_method("fundrawtransaction", &[raw_tx_json])).unwrap()
+ }
+
+ pub fn sign_raw_transaction_with_wallet(&self, tx_hex: String) -> SignedTx {
+ let runtime = self.runtime.lock().unwrap();
+ let mut rpc = self.bitcoind_rpc_client.lock().unwrap();
+
+ let tx_hex_json = serde_json::json!(tx_hex);
+ runtime
+ .block_on(rpc.call_method("signrawtransactionwithwallet", &vec![tx_hex_json]))
+ .unwrap()
+ }
+
+ pub fn get_new_address(&self) -> Address {
+ let runtime = self.runtime.lock().unwrap();
+ let mut rpc = self.bitcoind_rpc_client.lock().unwrap();
+
+ let addr_args = vec![serde_json::json!("LDK output address")];
+ let addr =
+ runtime.block_on(rpc.call_method::<NewAddress>("getnewaddress", &addr_args)).unwrap();
+ Address::from_str(addr.0.as_str()).unwrap()
+ }
+
+ pub fn get_blockchain_info(&self) -> BlockchainInfo {
+ let runtime = self.runtime.lock().unwrap();
+ let mut rpc = self.bitcoind_rpc_client.lock().unwrap();
+
+ runtime.block_on(rpc.call_method::<BlockchainInfo>("getblockchaininfo", &vec![])).unwrap()
+ }
}
impl FeeEstimator for BitcoindClient {
- fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32 {
- let runtime = self.runtime.lock().unwrap();
- let mut rpc = self.bitcoind_rpc_client.lock().unwrap();
-
- let (conf_target, estimate_mode, default) = match confirmation_target {
- ConfirmationTarget::Background => (144, "ECONOMICAL", 253),
- ConfirmationTarget::Normal => (18, "ECONOMICAL", 20000),
- ConfirmationTarget::HighPriority => (6, "ECONOMICAL", 50000),
- };
-
- // This function may be called from a tokio runtime, or not. So we need to check before
- // making the call to avoid the error "cannot run a tokio runtime from within a tokio runtime".
- let conf_target_json = serde_json::json!(conf_target);
- let estimate_mode_json = serde_json::json!(estimate_mode);
- let resp = match Handle::try_current() {
- Ok(_) => {
- tokio::task::block_in_place(|| {
- runtime.block_on(rpc.call_method::<FeeResponse>("estimatesmartfee",
- &vec![conf_target_json,
- estimate_mode_json])).unwrap()
- })
- },
- _ => runtime.block_on(rpc.call_method::<FeeResponse>("estimatesmartfee",
- &vec![conf_target_json,
- estimate_mode_json])).unwrap()
- };
- if resp.errored {
- return default
- }
- resp.feerate.unwrap()
- }
+ fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32 {
+ let runtime = self.runtime.lock().unwrap();
+ let mut rpc = self.bitcoind_rpc_client.lock().unwrap();
+
+ let (conf_target, estimate_mode, default) = match confirmation_target {
+ ConfirmationTarget::Background => (144, "ECONOMICAL", 253),
+ ConfirmationTarget::Normal => (18, "ECONOMICAL", 20000),
+ ConfirmationTarget::HighPriority => (6, "ECONOMICAL", 50000),
+ };
+
+ // This function may be called from a tokio runtime, or not. So we need to check before
+ // making the call to avoid the error "cannot run a tokio runtime from within a tokio runtime".
+ let conf_target_json = serde_json::json!(conf_target);
+ let estimate_mode_json = serde_json::json!(estimate_mode);
+ let resp = match Handle::try_current() {
+ Ok(_) => tokio::task::block_in_place(|| {
+ runtime
+ .block_on(rpc.call_method::<FeeResponse>(
+ "estimatesmartfee",
+ &vec![conf_target_json, estimate_mode_json],
+ ))
+ .unwrap()
+ }),
+ _ => runtime
+ .block_on(rpc.call_method::<FeeResponse>(
+ "estimatesmartfee",
+ &vec![conf_target_json, estimate_mode_json],
+ ))
+ .unwrap(),
+ };
+ if resp.errored {
+ return default;
+ }
+ resp.feerate.unwrap()
+ }
}
impl BroadcasterInterface for BitcoindClient {
- fn broadcast_transaction(&self, tx: &Transaction) {
- let mut rpc = self.bitcoind_rpc_client.lock().unwrap();
- let runtime = self.runtime.lock().unwrap();
-
- let tx_serialized = serde_json::json!(encode::serialize_hex(tx));
- // This function may be called from a tokio runtime, or not. So we need to check before
- // making the call to avoid the error "cannot run a tokio runtime from within a tokio runtime".
- match Handle::try_current() {
- Ok(_) => {
- tokio::task::block_in_place(|| {
- runtime.block_on(rpc.call_method::<RawTx>("sendrawtransaction",
- &vec![tx_serialized])).unwrap();
- });
- },
- _ => {
- runtime.block_on(rpc.call_method::<RawTx>("sendrawtransaction",
- &vec![tx_serialized])).unwrap();
- }
- }
- }
+ fn broadcast_transaction(&self, tx: &Transaction) {
+ let mut rpc = self.bitcoind_rpc_client.lock().unwrap();
+ let runtime = self.runtime.lock().unwrap();
+
+ let tx_serialized = serde_json::json!(encode::serialize_hex(tx));
+ // This function may be called from a tokio runtime, or not. So we need to check before
+ // making the call to avoid the error "cannot run a tokio runtime from within a tokio runtime".
+ match Handle::try_current() {
+ Ok(_) => {
+ tokio::task::block_in_place(|| {
+ runtime
+ .block_on(
+ rpc.call_method::<RawTx>("sendrawtransaction", &vec![tx_serialized]),
+ )
+ .unwrap();
+ });
+ }
+ _ => {
+ runtime
+ .block_on(rpc.call_method::<RawTx>("sendrawtransaction", &vec![tx_serialized]))
+ .unwrap();
+ }
+ }
+ }
}
-use bitcoin::network::constants::Network;
-use bitcoin::hashes::Hash;
-use bitcoin::hashes::sha256::Hash as Sha256Hash;
-use bitcoin::secp256k1::Secp256k1;
-use bitcoin::secp256k1::key::{PublicKey, SecretKey};
-use crate::{ChannelManager, FilesystemLogger, HTLCDirection, HTLCStatus,
- PaymentInfoStorage, PeerManager, SatoshiAmount};
use crate::disk;
use crate::hex_utils;
+use crate::{
+ ChannelManager, FilesystemLogger, HTLCDirection, HTLCStatus, PaymentInfoStorage, PeerManager,
+ SatoshiAmount,
+};
+use bitcoin::hashes::sha256::Hash as Sha256Hash;
+use bitcoin::hashes::Hash;
+use bitcoin::network::constants::Network;
+use bitcoin::secp256k1::key::{PublicKey, SecretKey};
+use bitcoin::secp256k1::Secp256k1;
use lightning::chain;
use lightning::ln::channelmanager::{PaymentHash, PaymentPreimage, PaymentSecret};
use lightning::ln::features::InvoiceFeatures;
use tokio::sync::mpsc;
pub(crate) struct LdkUserInfo {
- pub(crate) bitcoind_rpc_username: String,
- pub(crate) bitcoind_rpc_password: String,
- pub(crate) bitcoind_rpc_port: u16,
- pub(crate) bitcoind_rpc_host: String,
- pub(crate) ldk_storage_dir_path: String,
- pub(crate) ldk_peer_listening_port: u16,
- pub(crate) network: Network,
+ pub(crate) bitcoind_rpc_username: String,
+ pub(crate) bitcoind_rpc_password: String,
+ pub(crate) bitcoind_rpc_port: u16,
+ pub(crate) bitcoind_rpc_host: String,
+ pub(crate) ldk_storage_dir_path: String,
+ pub(crate) ldk_peer_listening_port: u16,
+ pub(crate) network: Network,
}
pub(crate) fn parse_startup_args() -> Result<LdkUserInfo, ()> {
- if env::args().len() < 4 {
- println!("ldk-tutorial-node requires 3 arguments: `cargo run <bitcoind-rpc-username>:<bitcoind-rpc-password>@<bitcoind-rpc-host>:<bitcoind-rpc-port> ldk_storage_directory_path [<ldk-incoming-peer-listening-port>] [bitcoin-network]`");
- return Err(())
- }
- let bitcoind_rpc_info = env::args().skip(1).next().unwrap();
- let bitcoind_rpc_info_parts: Vec<&str> = bitcoind_rpc_info.split("@").collect();
- if bitcoind_rpc_info_parts.len() != 2 {
- println!("ERROR: bad bitcoind RPC URL provided");
- return Err(())
- }
- let rpc_user_and_password: Vec<&str> = bitcoind_rpc_info_parts[0].split(":").collect();
- if rpc_user_and_password.len() != 2 {
- println!("ERROR: bad bitcoind RPC username/password combo provided");
- return Err(())
- }
- let bitcoind_rpc_username = rpc_user_and_password[0].to_string();
- let bitcoind_rpc_password = rpc_user_and_password[1].to_string();
- let bitcoind_rpc_path: Vec<&str> = bitcoind_rpc_info_parts[1].split(":").collect();
- if bitcoind_rpc_path.len() != 2 {
- println!("ERROR: bad bitcoind RPC path provided");
- return Err(())
- }
- let bitcoind_rpc_host = bitcoind_rpc_path[0].to_string();
- let bitcoind_rpc_port = bitcoind_rpc_path[1].parse::<u16>().unwrap();
-
- let ldk_storage_dir_path = env::args().skip(2).next().unwrap();
-
- let mut ldk_peer_port_set = true;
- let ldk_peer_listening_port: u16 = match env::args().skip(3).next().map(|p| p.parse()) {
- Some(Ok(p)) => p,
- Some(Err(e)) => panic!(e),
- None => {
- ldk_peer_port_set = false;
- 9735
- },
- };
-
- let arg_idx = match ldk_peer_port_set {
- true => 4,
- false => 3,
- };
- let network: Network = match env::args().skip(arg_idx).next().as_ref().map(String::as_str) {
- Some("testnet") => Network::Testnet,
- Some("regtest") => Network::Regtest,
- Some(_) => panic!("Unsupported network provided. Options are: `regtest`, `testnet`"),
- None => Network::Testnet
- };
- Ok(LdkUserInfo {
- bitcoind_rpc_username,
- bitcoind_rpc_password,
- bitcoind_rpc_host,
- bitcoind_rpc_port,
- ldk_storage_dir_path,
- ldk_peer_listening_port,
- network,
- })
+ if env::args().len() < 4 {
+ println!("ldk-tutorial-node requires 3 arguments: `cargo run <bitcoind-rpc-username>:<bitcoind-rpc-password>@<bitcoind-rpc-host>:<bitcoind-rpc-port> ldk_storage_directory_path [<ldk-incoming-peer-listening-port>] [bitcoin-network]`");
+ return Err(());
+ }
+ let bitcoind_rpc_info = env::args().skip(1).next().unwrap();
+ let bitcoind_rpc_info_parts: Vec<&str> = bitcoind_rpc_info.split("@").collect();
+ if bitcoind_rpc_info_parts.len() != 2 {
+ println!("ERROR: bad bitcoind RPC URL provided");
+ return Err(());
+ }
+ let rpc_user_and_password: Vec<&str> = bitcoind_rpc_info_parts[0].split(":").collect();
+ if rpc_user_and_password.len() != 2 {
+ println!("ERROR: bad bitcoind RPC username/password combo provided");
+ return Err(());
+ }
+ let bitcoind_rpc_username = rpc_user_and_password[0].to_string();
+ let bitcoind_rpc_password = rpc_user_and_password[1].to_string();
+ let bitcoind_rpc_path: Vec<&str> = bitcoind_rpc_info_parts[1].split(":").collect();
+ if bitcoind_rpc_path.len() != 2 {
+ println!("ERROR: bad bitcoind RPC path provided");
+ return Err(());
+ }
+ let bitcoind_rpc_host = bitcoind_rpc_path[0].to_string();
+ let bitcoind_rpc_port = bitcoind_rpc_path[1].parse::<u16>().unwrap();
+
+ let ldk_storage_dir_path = env::args().skip(2).next().unwrap();
+
+ let mut ldk_peer_port_set = true;
+ let ldk_peer_listening_port: u16 = match env::args().skip(3).next().map(|p| p.parse()) {
+ Some(Ok(p)) => p,
+ Some(Err(e)) => panic!(e),
+ None => {
+ ldk_peer_port_set = false;
+ 9735
+ }
+ };
+
+ let arg_idx = match ldk_peer_port_set {
+ true => 4,
+ false => 3,
+ };
+ let network: Network = match env::args().skip(arg_idx).next().as_ref().map(String::as_str) {
+ Some("testnet") => Network::Testnet,
+ Some("regtest") => Network::Regtest,
+ Some(_) => panic!("Unsupported network provided. Options are: `regtest`, `testnet`"),
+ None => Network::Testnet,
+ };
+ Ok(LdkUserInfo {
+ bitcoind_rpc_username,
+ bitcoind_rpc_password,
+ bitcoind_rpc_host,
+ bitcoind_rpc_port,
+ ldk_storage_dir_path,
+ ldk_peer_listening_port,
+ network,
+ })
}
-pub(crate) fn poll_for_user_input(peer_manager: Arc<PeerManager>, channel_manager:
- Arc<ChannelManager>, router: Arc<NetGraphMsgHandler<Arc<dyn
- chain::Access>, Arc<FilesystemLogger>>>, payment_storage:
- PaymentInfoStorage, node_privkey: SecretKey, event_notifier:
- mpsc::Sender<()>, ldk_data_dir: String, logger: Arc<FilesystemLogger>,
- runtime_handle: Handle, network: Network) {
- println!("LDK startup successful. To view available commands: \"help\".\nLDK logs are available at <your-supplied-ldk-data-dir-path>/.ldk/logs");
- let stdin = io::stdin();
- print!("> "); io::stdout().flush().unwrap(); // Without flushing, the `>` doesn't print
- for line in stdin.lock().lines() {
- let _ = event_notifier.try_send(());
- let line = line.unwrap();
- let mut words = line.split_whitespace();
- if let Some(word) = words.next() {
- match word {
- "help" => help(),
- "openchannel" => {
- let peer_pubkey_and_ip_addr = words.next();
- let channel_value_sat = words.next();
- if peer_pubkey_and_ip_addr.is_none() || channel_value_sat.is_none() {
- println!("ERROR: openchannel takes 2 arguments: `openchannel pubkey@host:port channel_amt_satoshis`");
- print!("> "); io::stdout().flush().unwrap(); continue;
- }
- let peer_pubkey_and_ip_addr = peer_pubkey_and_ip_addr.unwrap();
- let (pubkey, peer_addr) = match parse_peer_info(peer_pubkey_and_ip_addr.to_string()) {
- Ok(info) => info,
- Err(e) => {
- println!("{:?}", e.into_inner().unwrap());
- print!("> "); io::stdout().flush().unwrap(); continue;
- }
- };
-
- let chan_amt_sat: Result<u64, _> = channel_value_sat.unwrap().parse();
- if chan_amt_sat.is_err() {
- println!("ERROR: channel amount must be a number");
- print!("> "); io::stdout().flush().unwrap(); continue;
- }
-
- if connect_peer_if_necessary(pubkey, peer_addr, peer_manager.clone(),
- event_notifier.clone(),
- runtime_handle.clone()).is_err() {
- print!("> "); io::stdout().flush().unwrap(); continue;
- };
-
- if open_channel(pubkey, chan_amt_sat.unwrap(), channel_manager.clone()).is_ok() {
- let peer_data_path = format!("{}/channel_peer_data", ldk_data_dir.clone());
- let _ = disk::persist_channel_peer(Path::new(&peer_data_path), peer_pubkey_and_ip_addr);
- }
- },
- "sendpayment" => {
- let invoice_str = words.next();
- if invoice_str.is_none() {
- println!("ERROR: sendpayment requires an invoice: `sendpayment <invoice>`");
- print!("> "); io::stdout().flush().unwrap(); continue;
- }
-
- let invoice_res = lightning_invoice::Invoice::from_str(invoice_str.unwrap());
- if invoice_res.is_err() {
- println!("ERROR: invalid invoice: {:?}", invoice_res.unwrap_err());
- print!("> "); io::stdout().flush().unwrap(); continue;
- }
- let invoice = invoice_res.unwrap();
-
- let amt_pico_btc = invoice.amount_pico_btc();
- if amt_pico_btc.is_none () {
- println!("ERROR: invalid invoice: must contain amount to pay");
- print!("> "); io::stdout().flush().unwrap(); continue;
- }
- let amt_msat = amt_pico_btc.unwrap() / 10;
-
- let payee_pubkey = invoice.recover_payee_pub_key();
- let final_cltv = *invoice.min_final_cltv_expiry().unwrap_or(&9) as u32;
-
- let mut payment_hash = PaymentHash([0; 32]);
- payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
-
-
- let payment_secret = match invoice.payment_secret() {
- Some(secret) => {
- let mut payment_secret = PaymentSecret([0; 32]);
- payment_secret.0.copy_from_slice(&secret.0);
- Some(payment_secret)
- },
- None => None
- };
-
- // rust-lightning-invoice doesn't currently support features, so we parse features
- // manually from the invoice.
- let mut invoice_features = InvoiceFeatures::empty();
- for field in &invoice.into_signed_raw().raw_invoice().data.tagged_fields {
- match field {
- lightning_invoice::RawTaggedField::UnknownSemantics(vec) => {
- if vec[0] == bech32::u5::try_from_u8(5).unwrap() {
- if vec.len() >= 6 && vec[5].to_u8() & 0b10000 != 0 {
- invoice_features = invoice_features.set_variable_length_onion_optional();
- }
- if vec.len() >= 6 && vec[5].to_u8() & 0b01000 != 0 {
- invoice_features = invoice_features.set_variable_length_onion_required();
- }
- if vec.len() >= 4 && vec[3].to_u8() & 0b00001 != 0 {
- invoice_features = invoice_features.set_payment_secret_optional();
- }
- if vec.len() >= 5 && vec[4].to_u8() & 0b10000 != 0 {
- invoice_features = invoice_features.set_payment_secret_required();
- }
- if vec.len() >= 4 && vec[3].to_u8() & 0b00100 != 0 {
- invoice_features = invoice_features.set_basic_mpp_optional();
- }
- if vec.len() >= 4 && vec[3].to_u8() & 0b00010 != 0 {
- invoice_features = invoice_features.set_basic_mpp_required();
- }
- }
- },
- _ => {}
- }
- }
- let invoice_features_opt = match invoice_features == InvoiceFeatures::empty() {
- true => None,
- false => Some(invoice_features)
- };
- send_payment(payee_pubkey, amt_msat, final_cltv, payment_hash,
- payment_secret, invoice_features_opt, router.clone(),
- channel_manager.clone(), payment_storage.clone(),
- logger.clone());
- },
- "getinvoice" => {
- let amt_str = words.next();
- if amt_str.is_none() {
- println!("ERROR: getinvoice requires an amount in satoshis");
- print!("> "); io::stdout().flush().unwrap(); continue;
- }
-
- let amt_sat: Result<u64, _> = amt_str.unwrap().parse();
- if amt_sat.is_err() {
- println!("ERROR: getinvoice provided payment amount was not a number");
- print!("> "); io::stdout().flush().unwrap(); continue;
- }
- get_invoice(amt_sat.unwrap(), payment_storage.clone(), node_privkey.clone(),
- channel_manager.clone(), network);
- },
- "connectpeer" => {
- let peer_pubkey_and_ip_addr = words.next();
- if peer_pubkey_and_ip_addr.is_none() {
- println!("ERROR: connectpeer requires peer connection info: `connectpeer pubkey@host:port`");
- print!("> "); io::stdout().flush().unwrap(); continue;
- }
- let (pubkey, peer_addr) = match parse_peer_info(peer_pubkey_and_ip_addr.unwrap().to_string()) {
- Ok(info) => info,
- Err(e) => {
- println!("{:?}", e.into_inner().unwrap());
- print!("> "); io::stdout().flush().unwrap(); continue;
- }
- };
- if connect_peer_if_necessary(pubkey, peer_addr, peer_manager.clone(),
- event_notifier.clone(), runtime_handle.clone()).is_ok() {
- println!("SUCCESS: connected to peer {}", pubkey);
- }
-
- },
- "listchannels" => list_channels(channel_manager.clone()),
- "listpayments" => list_payments(payment_storage.clone()),
- "closechannel" => {
- let channel_id_str = words.next();
- if channel_id_str.is_none() {
- println!("ERROR: closechannel requires a channel ID: `closechannel <channel_id>`");
- print!("> "); io::stdout().flush().unwrap(); continue;
- }
- let channel_id_vec = hex_utils::to_vec(channel_id_str.unwrap());
- if channel_id_vec.is_none() {
- println!("ERROR: couldn't parse channel_id as hex");
- print!("> "); io::stdout().flush().unwrap(); continue;
- }
- let mut channel_id = [0; 32];
- channel_id.copy_from_slice(&channel_id_vec.unwrap());
- close_channel(channel_id, channel_manager.clone());
- },
- "forceclosechannel" => {
- let channel_id_str = words.next();
- if channel_id_str.is_none() {
- println!("ERROR: forceclosechannel requires a channel ID: `forceclosechannel <channel_id>`");
- print!("> "); io::stdout().flush().unwrap(); continue;
- }
- let channel_id_vec = hex_utils::to_vec(channel_id_str.unwrap());
- if channel_id_vec.is_none() {
- println!("ERROR: couldn't parse channel_id as hex");
- print!("> "); io::stdout().flush().unwrap(); continue;
- }
- let mut channel_id = [0; 32];
- channel_id.copy_from_slice(&channel_id_vec.unwrap());
- force_close_channel(channel_id, channel_manager.clone());
- }
- _ => println!("Unknown command. See `\"help\" for available commands.")
- }
- }
- print!("> "); io::stdout().flush().unwrap();
-
- }
+pub(crate) fn poll_for_user_input(
+ peer_manager: Arc<PeerManager>, channel_manager: Arc<ChannelManager>,
+ router: Arc<NetGraphMsgHandler<Arc<dyn chain::Access>, Arc<FilesystemLogger>>>,
+ payment_storage: PaymentInfoStorage, node_privkey: SecretKey, event_notifier: mpsc::Sender<()>,
+ ldk_data_dir: String, logger: Arc<FilesystemLogger>, runtime_handle: Handle, network: Network,
+) {
+ println!("LDK startup successful. To view available commands: \"help\".\nLDK logs are available at <your-supplied-ldk-data-dir-path>/.ldk/logs");
+ let stdin = io::stdin();
+ print!("> ");
+ io::stdout().flush().unwrap(); // Without flushing, the `>` doesn't print
+ for line in stdin.lock().lines() {
+ let _ = event_notifier.try_send(());
+ let line = line.unwrap();
+ let mut words = line.split_whitespace();
+ if let Some(word) = words.next() {
+ match word {
+ "help" => help(),
+ "openchannel" => {
+ let peer_pubkey_and_ip_addr = words.next();
+ let channel_value_sat = words.next();
+ if peer_pubkey_and_ip_addr.is_none() || channel_value_sat.is_none() {
+ println!("ERROR: openchannel has 2 required arguments: `openchannel pubkey@host:port channel_amt_satoshis` [--public]");
+ print!("> ");
+ io::stdout().flush().unwrap();
+ continue;
+ }
+ let peer_pubkey_and_ip_addr = peer_pubkey_and_ip_addr.unwrap();
+ let (pubkey, peer_addr) =
+ match parse_peer_info(peer_pubkey_and_ip_addr.to_string()) {
+ Ok(info) => info,
+ Err(e) => {
+ println!("{:?}", e.into_inner().unwrap());
+ print!("> ");
+ io::stdout().flush().unwrap();
+ continue;
+ }
+ };
+
+ let chan_amt_sat: Result<u64, _> = channel_value_sat.unwrap().parse();
+ if chan_amt_sat.is_err() {
+ println!("ERROR: channel amount must be a number");
+ print!("> ");
+ io::stdout().flush().unwrap();
+ continue;
+ }
+
+ if connect_peer_if_necessary(
+ pubkey,
+ peer_addr,
+ peer_manager.clone(),
+ event_notifier.clone(),
+ runtime_handle.clone(),
+ )
+ .is_err()
+ {
+ print!("> ");
+ io::stdout().flush().unwrap();
+ continue;
+ };
+
+ // let private_channel = match words.next().as_ref().map(String::as_str) {
+ let announce_channel = match words.next() {
+ Some("--public") | Some("--public=true") | Some("--public true") => true,
+ Some("--public=false") | Some("--public false") => false,
+ Some(_) => {
+ println!("ERROR: invalid `--public` command format");
+ print!("> ");
+ io::stdout().flush().unwrap();
+ continue;
+ }
+ None => false,
+ };
+
+ if open_channel(
+ pubkey,
+ chan_amt_sat.unwrap(),
+ announce_channel,
+ channel_manager.clone(),
+ )
+ .is_ok()
+ {
+ let peer_data_path = format!("{}/channel_peer_data", ldk_data_dir.clone());
+ let _ = disk::persist_channel_peer(
+ Path::new(&peer_data_path),
+ peer_pubkey_and_ip_addr,
+ );
+ }
+ }
+ "sendpayment" => {
+ let invoice_str = words.next();
+ if invoice_str.is_none() {
+ println!("ERROR: sendpayment requires an invoice: `sendpayment <invoice>`");
+ print!("> ");
+ io::stdout().flush().unwrap();
+ continue;
+ }
+
+ let invoice_res = lightning_invoice::Invoice::from_str(invoice_str.unwrap());
+ if invoice_res.is_err() {
+ println!("ERROR: invalid invoice: {:?}", invoice_res.unwrap_err());
+ print!("> ");
+ io::stdout().flush().unwrap();
+ continue;
+ }
+ let invoice = invoice_res.unwrap();
+
+ let amt_pico_btc = invoice.amount_pico_btc();
+ if amt_pico_btc.is_none() {
+ println!("ERROR: invalid invoice: must contain amount to pay");
+ print!("> ");
+ io::stdout().flush().unwrap();
+ continue;
+ }
+ let amt_msat = amt_pico_btc.unwrap() / 10;
+
+ let payee_pubkey = invoice.recover_payee_pub_key();
+ let final_cltv = *invoice.min_final_cltv_expiry().unwrap_or(&9) as u32;
+
+ let mut payment_hash = PaymentHash([0; 32]);
+ payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
+
+ let payment_secret = match invoice.payment_secret() {
+ Some(secret) => {
+ let mut payment_secret = PaymentSecret([0; 32]);
+ payment_secret.0.copy_from_slice(&secret.0);
+ Some(payment_secret)
+ }
+ None => None,
+ };
+
+ // rust-lightning-invoice doesn't currently support features, so we parse features
+ // manually from the invoice.
+ let mut invoice_features = InvoiceFeatures::empty();
+ for field in &invoice.into_signed_raw().raw_invoice().data.tagged_fields {
+ match field {
+ lightning_invoice::RawTaggedField::UnknownSemantics(vec) => {
+ if vec[0] == bech32::u5::try_from_u8(5).unwrap() {
+ if vec.len() >= 6 && vec[5].to_u8() & 0b10000 != 0 {
+ invoice_features =
+ invoice_features.set_variable_length_onion_optional();
+ }
+ if vec.len() >= 6 && vec[5].to_u8() & 0b01000 != 0 {
+ invoice_features =
+ invoice_features.set_variable_length_onion_required();
+ }
+ if vec.len() >= 4 && vec[3].to_u8() & 0b00001 != 0 {
+ invoice_features =
+ invoice_features.set_payment_secret_optional();
+ }
+ if vec.len() >= 5 && vec[4].to_u8() & 0b10000 != 0 {
+ invoice_features =
+ invoice_features.set_payment_secret_required();
+ }
+ if vec.len() >= 4 && vec[3].to_u8() & 0b00100 != 0 {
+ invoice_features =
+ invoice_features.set_basic_mpp_optional();
+ }
+ if vec.len() >= 4 && vec[3].to_u8() & 0b00010 != 0 {
+ invoice_features =
+ invoice_features.set_basic_mpp_required();
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+ let invoice_features_opt = match invoice_features == InvoiceFeatures::empty() {
+ true => None,
+ false => Some(invoice_features),
+ };
+ send_payment(
+ payee_pubkey,
+ amt_msat,
+ final_cltv,
+ payment_hash,
+ payment_secret,
+ invoice_features_opt,
+ router.clone(),
+ channel_manager.clone(),
+ payment_storage.clone(),
+ logger.clone(),
+ );
+ }
+ "getinvoice" => {
+ let amt_str = words.next();
+ if amt_str.is_none() {
+ println!("ERROR: getinvoice requires an amount in satoshis");
+ print!("> ");
+ io::stdout().flush().unwrap();
+ continue;
+ }
+
+ let amt_sat: Result<u64, _> = amt_str.unwrap().parse();
+ if amt_sat.is_err() {
+ println!("ERROR: getinvoice provided payment amount was not a number");
+ print!("> ");
+ io::stdout().flush().unwrap();
+ continue;
+ }
+ get_invoice(
+ amt_sat.unwrap(),
+ payment_storage.clone(),
+ node_privkey.clone(),
+ channel_manager.clone(),
+ network,
+ );
+ }
+ "connectpeer" => {
+ let peer_pubkey_and_ip_addr = words.next();
+ if peer_pubkey_and_ip_addr.is_none() {
+ println!("ERROR: connectpeer requires peer connection info: `connectpeer pubkey@host:port`");
+ print!("> ");
+ io::stdout().flush().unwrap();
+ continue;
+ }
+ let (pubkey, peer_addr) =
+ match parse_peer_info(peer_pubkey_and_ip_addr.unwrap().to_string()) {
+ Ok(info) => info,
+ Err(e) => {
+ println!("{:?}", e.into_inner().unwrap());
+ print!("> ");
+ io::stdout().flush().unwrap();
+ continue;
+ }
+ };
+ if connect_peer_if_necessary(
+ pubkey,
+ peer_addr,
+ peer_manager.clone(),
+ event_notifier.clone(),
+ runtime_handle.clone(),
+ )
+ .is_ok()
+ {
+ println!("SUCCESS: connected to peer {}", pubkey);
+ }
+ }
+ "listchannels" => list_channels(channel_manager.clone()),
+ "listpayments" => list_payments(payment_storage.clone()),
+ "closechannel" => {
+ let channel_id_str = words.next();
+ if channel_id_str.is_none() {
+ println!("ERROR: closechannel requires a channel ID: `closechannel <channel_id>`");
+ print!("> ");
+ io::stdout().flush().unwrap();
+ continue;
+ }
+ let channel_id_vec = hex_utils::to_vec(channel_id_str.unwrap());
+ if channel_id_vec.is_none() {
+ println!("ERROR: couldn't parse channel_id as hex");
+ print!("> ");
+ io::stdout().flush().unwrap();
+ continue;
+ }
+ let mut channel_id = [0; 32];
+ channel_id.copy_from_slice(&channel_id_vec.unwrap());
+ close_channel(channel_id, channel_manager.clone());
+ }
+ "forceclosechannel" => {
+ let channel_id_str = words.next();
+ if channel_id_str.is_none() {
+ println!("ERROR: forceclosechannel requires a channel ID: `forceclosechannel <channel_id>`");
+ print!("> ");
+ io::stdout().flush().unwrap();
+ continue;
+ }
+ let channel_id_vec = hex_utils::to_vec(channel_id_str.unwrap());
+ if channel_id_vec.is_none() {
+ println!("ERROR: couldn't parse channel_id as hex");
+ print!("> ");
+ io::stdout().flush().unwrap();
+ continue;
+ }
+ let mut channel_id = [0; 32];
+ channel_id.copy_from_slice(&channel_id_vec.unwrap());
+ force_close_channel(channel_id, channel_manager.clone());
+ }
+ _ => println!("Unknown command. See `\"help\" for available commands."),
+ }
+ }
+ print!("> ");
+ io::stdout().flush().unwrap();
+ }
}
fn help() {
- println!("openchannel pubkey@host:port <channel_amt_satoshis>");
- println!("sendpayment <invoice>");
- println!("getinvoice <amt_in_satoshis>");
- println!("connectpeer pubkey@host:port");
- println!("listchannels");
- println!("listpayments");
- println!("closechannel <channel_id>");
- println!("forceclosechannel <channel_id>");
+ println!("openchannel pubkey@host:port <channel_amt_satoshis>");
+ println!("sendpayment <invoice>");
+ println!("getinvoice <amt_in_satoshis>");
+ println!("connectpeer pubkey@host:port");
+ println!("listchannels");
+ println!("listpayments");
+ println!("closechannel <channel_id>");
+ println!("forceclosechannel <channel_id>");
}
fn list_channels(channel_manager: Arc<ChannelManager>) {
- print!("[");
- for chan_info in channel_manager.list_channels() {
- println!("");
- println!("\t{{");
- println!("\t\tchannel_id: {},", hex_utils::hex_str(&chan_info.channel_id[..]));
- println!("\t\tpeer_pubkey: {},", hex_utils::hex_str(&chan_info.remote_network_id.serialize()));
- let mut pending_channel = false;
- match chan_info.short_channel_id {
- Some(id) => println!("\t\tshort_channel_id: {},", id),
- None => {
- pending_channel = true;
- }
- }
- println!("\t\tpending_open: {},", pending_channel);
- println!("\t\tchannel_value_satoshis: {},", chan_info.channel_value_satoshis);
- println!("\t\tchannel_can_send_payments: {},", chan_info.is_live);
- println!("\t}},");
- }
- println!("]");
+ print!("[");
+ for chan_info in channel_manager.list_channels() {
+ println!("");
+ println!("\t{{");
+ println!("\t\tchannel_id: {},", hex_utils::hex_str(&chan_info.channel_id[..]));
+ println!(
+ "\t\tpeer_pubkey: {},",
+ hex_utils::hex_str(&chan_info.remote_network_id.serialize())
+ );
+ let mut pending_channel = false;
+ match chan_info.short_channel_id {
+ Some(id) => println!("\t\tshort_channel_id: {},", id),
+ None => {
+ pending_channel = true;
+ }
+ }
+ println!("\t\tpending_open: {},", pending_channel);
+ println!("\t\tchannel_value_satoshis: {},", chan_info.channel_value_satoshis);
+ println!("\t\tchannel_can_send_payments: {},", chan_info.is_live);
+ println!("\t}},");
+ }
+ println!("]");
}
fn list_payments(payment_storage: PaymentInfoStorage) {
- let payments = payment_storage.lock().unwrap();
- print!("[");
- for (payment_hash, payment_info) in payments.deref() {
- let direction_str = match payment_info.1 {
- HTLCDirection::Inbound => "inbound",
- HTLCDirection::Outbound => "outbound",
- };
- println!("");
- println!("\t{{");
- println!("\t\tamount_satoshis: {},", payment_info.3);
- println!("\t\tpayment_hash: {},", hex_utils::hex_str(&payment_hash.0));
- println!("\t\thtlc_direction: {},", direction_str);
- println!("\t\thtlc_status: {},", match payment_info.2 {
- HTLCStatus::Pending => "pending",
- HTLCStatus::Succeeded => "succeeded",
- HTLCStatus::Failed => "failed"
- });
-
-
- println!("\t}},");
- }
- println!("]");
-}
-
-pub(crate) fn connect_peer_if_necessary(pubkey: PublicKey, peer_addr: SocketAddr, peer_manager:
- Arc<PeerManager>, event_notifier: mpsc::Sender<()>, runtime: Handle) ->
- Result<(), ()> {
- for node_pubkey in peer_manager.get_peer_node_ids() {
- if node_pubkey == pubkey {
- return Ok(())
- }
- }
- match TcpStream::connect_timeout(&peer_addr, Duration::from_secs(10)) {
- Ok(stream) => {
- let peer_mgr = peer_manager.clone();
- let event_ntfns = event_notifier.clone();
- runtime.spawn(async move {
- lightning_net_tokio::setup_outbound(peer_mgr, event_ntfns, pubkey, stream).await;
- });
- let mut peer_connected = false;
- while !peer_connected {
- for node_pubkey in peer_manager.get_peer_node_ids() {
- if node_pubkey == pubkey { peer_connected = true; }
- }
- }
- },
- Err(e) => {println!("ERROR: failed to connect to peer: {:?}", e);
- return Err(())
- }
- }
- Ok(())
+ let payments = payment_storage.lock().unwrap();
+ print!("[");
+ for (payment_hash, payment_info) in payments.deref() {
+ let direction_str = match payment_info.1 {
+ HTLCDirection::Inbound => "inbound",
+ HTLCDirection::Outbound => "outbound",
+ };
+ println!("");
+ println!("\t{{");
+ println!("\t\tamount_satoshis: {},", payment_info.3);
+ println!("\t\tpayment_hash: {},", hex_utils::hex_str(&payment_hash.0));
+ println!("\t\thtlc_direction: {},", direction_str);
+ println!(
+ "\t\thtlc_status: {},",
+ match payment_info.2 {
+ HTLCStatus::Pending => "pending",
+ HTLCStatus::Succeeded => "succeeded",
+ HTLCStatus::Failed => "failed",
+ }
+ );
+
+ println!("\t}},");
+ }
+ println!("]");
}
-fn open_channel(peer_pubkey: PublicKey, channel_amt_sat: u64, channel_manager: Arc<ChannelManager>)
- -> Result<(), ()> {
- let mut config = UserConfig::default();
- // lnd's max to_self_delay is 2016, so we want to be compatible.
- config.peer_channel_config_limits.their_to_self_delay = 2016;
- match channel_manager.create_channel(peer_pubkey, channel_amt_sat, 0, 0, None) {
- Ok(_) => {
- println!("EVENT: initiated channel with peer {}. ", peer_pubkey);
- return Ok(())
- },
- Err(e) => {
- println!("ERROR: failed to open channel: {:?}", e);
- return Err(())
- }
- }
+pub(crate) fn connect_peer_if_necessary(
+ pubkey: PublicKey, peer_addr: SocketAddr, peer_manager: Arc<PeerManager>,
+ event_notifier: mpsc::Sender<()>, runtime: Handle,
+) -> Result<(), ()> {
+ for node_pubkey in peer_manager.get_peer_node_ids() {
+ if node_pubkey == pubkey {
+ return Ok(());
+ }
+ }
+ match TcpStream::connect_timeout(&peer_addr, Duration::from_secs(10)) {
+ Ok(stream) => {
+ let peer_mgr = peer_manager.clone();
+ let event_ntfns = event_notifier.clone();
+ runtime.spawn(async move {
+ lightning_net_tokio::setup_outbound(peer_mgr, event_ntfns, pubkey, stream).await;
+ });
+ let mut peer_connected = false;
+ while !peer_connected {
+ for node_pubkey in peer_manager.get_peer_node_ids() {
+ if node_pubkey == pubkey {
+ peer_connected = true;
+ }
+ }
+ }
+ }
+ Err(e) => {
+ println!("ERROR: failed to connect to peer: {:?}", e);
+ return Err(());
+ }
+ }
+ Ok(())
}
-fn send_payment(payee: PublicKey, amt_msat: u64, final_cltv: u32, payment_hash: PaymentHash,
- payment_secret: Option<PaymentSecret>, payee_features: Option<InvoiceFeatures>,
- router: Arc<NetGraphMsgHandler<Arc<dyn chain::Access>, Arc<FilesystemLogger>>>,
- channel_manager: Arc<ChannelManager>, payment_storage: PaymentInfoStorage, logger:
- Arc<FilesystemLogger>) {
- let network_graph = router.network_graph.read().unwrap();
- let first_hops = channel_manager.list_usable_channels();
- let payer_pubkey = channel_manager.get_our_node_id();
-
- let route = router::get_route(&payer_pubkey, &network_graph, &payee, payee_features,
- Some(&first_hops.iter().collect::<Vec<_>>()), &vec![], amt_msat,
- final_cltv, logger);
- 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) {
- Ok(()) => {
- println!("EVENT: initiated sending {} msats to {}", amt_msat, payee);
- HTLCStatus::Pending
- },
- Err(e) => {
- println!("ERROR: failed to send payment: {:?}", e);
- HTLCStatus::Failed
- }
- };
- let mut payments = payment_storage.lock().unwrap();
- payments.insert(payment_hash, (None, HTLCDirection::Outbound, status,
- SatoshiAmount(Some(amt_msat * 1000))));
+fn open_channel(
+ peer_pubkey: PublicKey, channel_amt_sat: u64, announce_channel: bool,
+ channel_manager: Arc<ChannelManager>,
+) -> Result<(), ()> {
+ let mut config = UserConfig::default();
+ if announce_channel {
+ config.channel_options.announced_channel = true;
+ }
+ // lnd's max to_self_delay is 2016, so we want to be compatible.
+ config.peer_channel_config_limits.their_to_self_delay = 2016;
+ match channel_manager.create_channel(peer_pubkey, channel_amt_sat, 0, 0, None) {
+ Ok(_) => {
+ println!("EVENT: initiated channel with peer {}. ", peer_pubkey);
+ return Ok(());
+ }
+ Err(e) => {
+ println!("ERROR: failed to open channel: {:?}", e);
+ return Err(());
+ }
+ }
}
-fn get_invoice(amt_sat: u64, payment_storage: PaymentInfoStorage, our_node_privkey: SecretKey,
- channel_manager: Arc<ChannelManager>, network: Network) {
- let mut payments = payment_storage.lock().unwrap();
- let secp_ctx = Secp256k1::new();
-
- let mut preimage = [0; 32];
- rand::thread_rng().fill_bytes(&mut preimage);
- let payment_hash = Sha256Hash::hash(&preimage);
-
-
- let our_node_pubkey = channel_manager.get_our_node_id();
- let mut invoice = lightning_invoice::InvoiceBuilder::new(match network {
- Network::Bitcoin => lightning_invoice::Currency::Bitcoin,
- Network::Testnet => lightning_invoice::Currency::BitcoinTestnet,
- Network::Regtest => lightning_invoice::Currency::Regtest,
- Network::Signet => panic!("Signet invoices not supported")
- })
- .payment_hash(payment_hash).description("rust-lightning-bitcoinrpc invoice".to_string())
- .amount_pico_btc(amt_sat * 10_000)
- .current_timestamp()
- .payee_pub_key(our_node_pubkey);
-
- // Add route hints to the invoice.
- let our_channels = channel_manager.list_usable_channels();
- for channel in our_channels {
- let short_channel_id = match channel.short_channel_id {
- Some(id) => id.to_be_bytes(),
- None => continue
- };
- let forwarding_info = match channel.counterparty_forwarding_info {
- Some(info) => info,
- None => continue,
- };
- println!("VMW: adding routehop, info.fee base: {}", forwarding_info.fee_base_msat);
- invoice = invoice.route(vec![
- lightning_invoice::RouteHop {
- pubkey: channel.remote_network_id,
- short_channel_id,
- fee_base_msat: forwarding_info.fee_base_msat,
- fee_proportional_millionths: forwarding_info.fee_proportional_millionths,
- cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
- }
- ]);
- }
-
- // Sign the invoice.
- let invoice = invoice.build_signed(|msg_hash| {
- secp_ctx.sign_recoverable(msg_hash, &our_node_privkey)
- });
-
- match invoice {
- Ok(invoice) => println!("SUCCESS: generated invoice: {}", invoice),
- Err(e) => println!("ERROR: failed to create invoice: {:?}", e),
+fn send_payment(
+ payee: PublicKey, amt_msat: u64, final_cltv: u32, payment_hash: PaymentHash,
+ payment_secret: Option<PaymentSecret>, payee_features: Option<InvoiceFeatures>,
+ router: Arc<NetGraphMsgHandler<Arc<dyn chain::Access>, Arc<FilesystemLogger>>>,
+ channel_manager: Arc<ChannelManager>, payment_storage: PaymentInfoStorage,
+ logger: Arc<FilesystemLogger>,
+) {
+ let network_graph = router.network_graph.read().unwrap();
+ let first_hops = channel_manager.list_usable_channels();
+ let payer_pubkey = channel_manager.get_our_node_id();
+
+ let route = router::get_route(
+ &payer_pubkey,
+ &network_graph,
+ &payee,
+ payee_features,
+ Some(&first_hops.iter().collect::<Vec<_>>()),
+ &vec![],
+ amt_msat,
+ final_cltv,
+ logger,
+ );
+ 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)
+ {
+ Ok(()) => {
+ println!("EVENT: initiated sending {} msats to {}", amt_msat, payee);
+ HTLCStatus::Pending
}
+ Err(e) => {
+ println!("ERROR: failed to send payment: {:?}", e);
+ HTLCStatus::Failed
+ }
+ };
+ let mut payments = payment_storage.lock().unwrap();
+ payments.insert(
+ payment_hash,
+ (None, HTLCDirection::Outbound, status, SatoshiAmount(Some(amt_msat / 1000))),
+ );
+}
- payments.insert(PaymentHash(payment_hash.into_inner()), (Some(PaymentPreimage(preimage)),
- HTLCDirection::Inbound,
- HTLCStatus::Pending,
- SatoshiAmount(Some(amt_sat))));
+fn get_invoice(
+ amt_sat: u64, payment_storage: PaymentInfoStorage, our_node_privkey: SecretKey,
+ channel_manager: Arc<ChannelManager>, network: Network,
+) {
+ let mut payments = payment_storage.lock().unwrap();
+ let secp_ctx = Secp256k1::new();
+
+ let mut preimage = [0; 32];
+ rand::thread_rng().fill_bytes(&mut preimage);
+ let payment_hash = Sha256Hash::hash(&preimage);
+
+ let our_node_pubkey = channel_manager.get_our_node_id();
+ let mut invoice = lightning_invoice::InvoiceBuilder::new(match network {
+ Network::Bitcoin => lightning_invoice::Currency::Bitcoin,
+ Network::Testnet => lightning_invoice::Currency::BitcoinTestnet,
+ Network::Regtest => lightning_invoice::Currency::Regtest,
+ Network::Signet => panic!("Signet invoices not supported"),
+ })
+ .payment_hash(payment_hash)
+ .description("rust-lightning-bitcoinrpc invoice".to_string())
+ .amount_pico_btc(amt_sat * 10_000)
+ .current_timestamp()
+ .payee_pub_key(our_node_pubkey);
+
+ // Add route hints to the invoice.
+ let our_channels = channel_manager.list_usable_channels();
+ for channel in our_channels {
+ let short_channel_id = match channel.short_channel_id {
+ Some(id) => id.to_be_bytes(),
+ None => continue,
+ };
+ let forwarding_info = match channel.counterparty_forwarding_info {
+ Some(info) => info,
+ None => continue,
+ };
+ println!("VMW: adding routehop, info.fee base: {}", forwarding_info.fee_base_msat);
+ invoice = invoice.route(vec![lightning_invoice::RouteHop {
+ pubkey: channel.remote_network_id,
+ short_channel_id,
+ fee_base_msat: forwarding_info.fee_base_msat,
+ fee_proportional_millionths: forwarding_info.fee_proportional_millionths,
+ cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
+ }]);
+ }
+
+ // Sign the invoice.
+ let invoice =
+ invoice.build_signed(|msg_hash| secp_ctx.sign_recoverable(msg_hash, &our_node_privkey));
+
+ match invoice {
+ Ok(invoice) => println!("SUCCESS: generated invoice: {}", invoice),
+ Err(e) => println!("ERROR: failed to create invoice: {:?}", e),
+ }
+
+ payments.insert(
+ PaymentHash(payment_hash.into_inner()),
+ (
+ Some(PaymentPreimage(preimage)),
+ HTLCDirection::Inbound,
+ HTLCStatus::Pending,
+ SatoshiAmount(Some(amt_sat)),
+ ),
+ );
}
fn close_channel(channel_id: [u8; 32], channel_manager: Arc<ChannelManager>) {
- match channel_manager.close_channel(&channel_id) {
- Ok(()) => println!("EVENT: initiating channel close"),
- Err(e) => println!("ERROR: failed to close channel: {:?}", e)
- }
+ match channel_manager.close_channel(&channel_id) {
+ Ok(()) => println!("EVENT: initiating channel close"),
+ Err(e) => println!("ERROR: failed to close channel: {:?}", e),
+ }
}
fn force_close_channel(channel_id: [u8; 32], channel_manager: Arc<ChannelManager>) {
- match channel_manager.force_close_channel(&channel_id) {
- Ok(()) => println!("EVENT: initiating channel force-close"),
- Err(e) => println!("ERROR: failed to force-close channel: {:?}", e)
- }
+ match channel_manager.force_close_channel(&channel_id) {
+ Ok(()) => println!("EVENT: initiating channel force-close"),
+ Err(e) => println!("ERROR: failed to force-close channel: {:?}", e),
+ }
}
-pub(crate) fn parse_peer_info(peer_pubkey_and_ip_addr: String) -> Result<(PublicKey, SocketAddr), std::io::Error> {
- let mut pubkey_and_addr = peer_pubkey_and_ip_addr.split("@");
- let pubkey = pubkey_and_addr.next();
- let peer_addr_str = pubkey_and_addr.next();
- if peer_addr_str.is_none() || peer_addr_str.is_none() {
- return Err(std::io::Error::new(std::io::ErrorKind::Other, "ERROR: incorrectly formatted peer
- info. Should be formatted as: `pubkey@host:port`"));
- }
-
- let peer_addr: Result<SocketAddr, _> = peer_addr_str.unwrap().parse();
- if peer_addr.is_err() {
- return Err(std::io::Error::new(std::io::ErrorKind::Other, "ERROR: couldn't parse pubkey@host:port into a socket address"));
- }
-
- let pubkey = hex_utils::to_compressed_pubkey(pubkey.unwrap());
- if pubkey.is_none() {
- return Err(std::io::Error::new(std::io::ErrorKind::Other, "ERROR: unable to parse given pubkey for node"));
- }
-
- Ok((pubkey.unwrap(), peer_addr.unwrap()))
+pub(crate) fn parse_peer_info(
+ peer_pubkey_and_ip_addr: String,
+) -> Result<(PublicKey, SocketAddr), std::io::Error> {
+ let mut pubkey_and_addr = peer_pubkey_and_ip_addr.split("@");
+ let pubkey = pubkey_and_addr.next();
+ let peer_addr_str = pubkey_and_addr.next();
+ if peer_addr_str.is_none() || peer_addr_str.is_none() {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::Other,
+ "ERROR: incorrectly formatted peer
+ info. Should be formatted as: `pubkey@host:port`",
+ ));
+ }
+
+ let peer_addr: Result<SocketAddr, _> = peer_addr_str.unwrap().parse();
+ if peer_addr.is_err() {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::Other,
+ "ERROR: couldn't parse pubkey@host:port into a socket address",
+ ));
+ }
+
+ let pubkey = hex_utils::to_compressed_pubkey(pubkey.unwrap());
+ if pubkey.is_none() {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::Other,
+ "ERROR: unable to parse given pubkey for node",
+ ));
+ }
+
+ Ok((pubkey.unwrap(), peer_addr.unwrap()))
}
-use bitcoin::BlockHash;
use bitcoin::hashes::hex::FromHex;
+use bitcoin::BlockHash;
use lightning_block_sync::http::JsonResponse;
use std::convert::TryInto;
pub struct FundedTx {
- pub changepos: i64,
- pub hex: String,
+ pub changepos: i64,
+ pub hex: String,
}
impl TryInto<FundedTx> for JsonResponse {
- type Error = std::io::Error;
- fn try_into(self) -> std::io::Result<FundedTx> {
- Ok(FundedTx {
- changepos: self.0["changepos"].as_i64().unwrap(),
- hex: self.0["hex"].as_str().unwrap().to_string(),
- })
- }
+ type Error = std::io::Error;
+ fn try_into(self) -> std::io::Result<FundedTx> {
+ Ok(FundedTx {
+ changepos: self.0["changepos"].as_i64().unwrap(),
+ hex: self.0["hex"].as_str().unwrap().to_string(),
+ })
+ }
}
pub struct RawTx(pub String);
impl TryInto<RawTx> for JsonResponse {
- type Error = std::io::Error;
- fn try_into(self) -> std::io::Result<RawTx> {
- Ok(RawTx(self.0.as_str().unwrap().to_string()))
- }
+ type Error = std::io::Error;
+ fn try_into(self) -> std::io::Result<RawTx> {
+ Ok(RawTx(self.0.as_str().unwrap().to_string()))
+ }
}
pub struct SignedTx {
- pub complete: bool,
- pub hex: String,
+ pub complete: bool,
+ pub hex: String,
}
impl TryInto<SignedTx> for JsonResponse {
- type Error = std::io::Error;
- fn try_into(self) -> std::io::Result<SignedTx> {
- Ok(SignedTx {
- hex: self.0["hex"].as_str().unwrap().to_string(),
- complete: self.0["complete"].as_bool().unwrap(),
- })
- }
+ type Error = std::io::Error;
+ fn try_into(self) -> std::io::Result<SignedTx> {
+ Ok(SignedTx {
+ hex: self.0["hex"].as_str().unwrap().to_string(),
+ complete: self.0["complete"].as_bool().unwrap(),
+ })
+ }
}
pub struct NewAddress(pub String);
impl TryInto<NewAddress> for JsonResponse {
- type Error = std::io::Error;
- fn try_into(self) -> std::io::Result<NewAddress> {
- Ok(NewAddress(self.0.as_str().unwrap().to_string()))
- }
+ type Error = std::io::Error;
+ fn try_into(self) -> std::io::Result<NewAddress> {
+ Ok(NewAddress(self.0.as_str().unwrap().to_string()))
+ }
}
pub struct FeeResponse {
- pub feerate: Option<u32>,
- pub errored: bool,
+ pub feerate: Option<u32>,
+ pub errored: bool,
}
impl TryInto<FeeResponse> for JsonResponse {
- type Error = std::io::Error;
- fn try_into(self) -> std::io::Result<FeeResponse> {
- let errored = !self.0["errors"].is_null();
- Ok(FeeResponse {
- errored,
- feerate: match errored {
- true => None,
- // The feerate from bitcoind is in BTC/kb, and we want satoshis/kb.
- false => Some((self.0["feerate"].as_f64().unwrap() * 100_000_000.0).round() as u32)
- }
- })
- }
+ type Error = std::io::Error;
+ fn try_into(self) -> std::io::Result<FeeResponse> {
+ let errored = !self.0["errors"].is_null();
+ Ok(FeeResponse {
+ errored,
+ feerate: match errored {
+ true => None,
+ // The feerate from bitcoind is in BTC/kb, and we want satoshis/kb.
+ false => Some((self.0["feerate"].as_f64().unwrap() * 100_000_000.0).round() as u32),
+ },
+ })
+ }
}
pub struct BlockchainInfo {
- pub latest_height: usize,
- pub latest_blockhash: BlockHash,
+ pub latest_height: usize,
+ pub latest_blockhash: BlockHash,
}
impl TryInto<BlockchainInfo> for JsonResponse {
- type Error = std::io::Error;
- fn try_into(self) -> std::io::Result<BlockchainInfo> {
- Ok(BlockchainInfo {
- latest_height: self.0["blocks"].as_u64().unwrap() as usize,
- latest_blockhash: BlockHash::from_hex(self.0["bestblockhash"].as_str().unwrap()).unwrap(),
- })
- }
+ type Error = std::io::Error;
+ fn try_into(self) -> std::io::Result<BlockchainInfo> {
+ Ok(BlockchainInfo {
+ latest_height: self.0["blocks"].as_u64().unwrap() as usize,
+ latest_blockhash: BlockHash::from_hex(self.0["bestblockhash"].as_str().unwrap())
+ .unwrap(),
+ })
+ }
}
-use bitcoin::{BlockHash, Txid};
+use crate::cli;
use bitcoin::hashes::hex::FromHex;
use bitcoin::secp256k1::key::PublicKey;
-use crate::cli;
+use bitcoin::{BlockHash, Txid};
use lightning::chain::channelmonitor::ChannelMonitor;
use lightning::chain::keysinterface::{InMemorySigner, KeysManager};
use lightning::chain::transaction::OutPoint;
use std::sync::Arc;
use time::OffsetDateTime;
-pub(crate) struct FilesystemLogger{
- data_dir: String
+pub(crate) struct FilesystemLogger {
+ data_dir: String,
}
impl FilesystemLogger {
- pub(crate) fn new(data_dir: String) -> Self {
- let logs_path = format!("{}/logs", data_dir);
- fs::create_dir_all(logs_path.clone()).unwrap();
- Self {
- data_dir: logs_path
- }
- }
+ pub(crate) fn new(data_dir: String) -> Self {
+ let logs_path = format!("{}/logs", data_dir);
+ fs::create_dir_all(logs_path.clone()).unwrap();
+ Self { data_dir: logs_path }
+ }
}
impl Logger for FilesystemLogger {
- fn log(&self, record: &Record) {
- let raw_log = record.args.to_string();
- let log = format!("{} {:<5} [{}:{}] {}\n", OffsetDateTime::now_utc().format("%F %T"),
- record.level.to_string(), record.module_path, record.line, raw_log);
- let logs_file_path = format!("{}/logs.txt", self.data_dir.clone());
- fs::OpenOptions::new().create(true).append(true).open(logs_file_path).unwrap()
- .write_all(log.as_bytes()).unwrap();
- }
+ fn log(&self, record: &Record) {
+ let raw_log = record.args.to_string();
+ let log = format!(
+ "{} {:<5} [{}:{}] {}\n",
+ OffsetDateTime::now_utc().format("%F %T"),
+ record.level.to_string(),
+ record.module_path,
+ record.line,
+ raw_log
+ );
+ let logs_file_path = format!("{}/logs.txt", self.data_dir.clone());
+ fs::OpenOptions::new()
+ .create(true)
+ .append(true)
+ .open(logs_file_path)
+ .unwrap()
+ .write_all(log.as_bytes())
+ .unwrap();
+ }
}
pub(crate) fn persist_channel_peer(path: &Path, peer_info: &str) -> std::io::Result<()> {
- let mut file = fs::OpenOptions::new().create(true).append(true).open(path)?;
- file.write_all(format!("{}\n", peer_info).as_bytes())
+ let mut file = fs::OpenOptions::new().create(true).append(true).open(path)?;
+ file.write_all(format!("{}\n", peer_info).as_bytes())
}
-pub(crate) fn read_channel_peer_data(path: &Path) -> Result<HashMap<PublicKey, SocketAddr>, std::io::Error> {
- let mut peer_data = HashMap::new();
- if !Path::new(&path).exists() {
- return Ok(HashMap::new())
- }
- let file = File::open(path)?;
- let reader = BufReader::new(file);
- for line in reader.lines() {
- match cli::parse_peer_info(line.unwrap()) {
- Ok((pubkey, socket_addr)) => {
- peer_data.insert(pubkey, socket_addr);
- },
- Err(e) => return Err(e)
- }
- }
- Ok(peer_data)
+pub(crate) fn read_channel_peer_data(
+ path: &Path,
+) -> Result<HashMap<PublicKey, SocketAddr>, std::io::Error> {
+ let mut peer_data = HashMap::new();
+ if !Path::new(&path).exists() {
+ return Ok(HashMap::new());
+ }
+ let file = File::open(path)?;
+ let reader = BufReader::new(file);
+ for line in reader.lines() {
+ match cli::parse_peer_info(line.unwrap()) {
+ Ok((pubkey, socket_addr)) => {
+ peer_data.insert(pubkey, socket_addr);
+ }
+ Err(e) => return Err(e),
+ }
+ }
+ Ok(peer_data)
}
+pub(crate) fn read_channelmonitors(
+ path: String, keys_manager: Arc<KeysManager>,
+) -> Result<HashMap<OutPoint, (BlockHash, ChannelMonitor<InMemorySigner>)>, std::io::Error> {
+ if !Path::new(&path).exists() {
+ return Ok(HashMap::new());
+ }
+ let mut outpoint_to_channelmonitor = HashMap::new();
+ for file_option in fs::read_dir(path).unwrap() {
+ let file = file_option.unwrap();
+ let owned_file_name = file.file_name();
+ let filename = owned_file_name.to_str();
+ if !filename.is_some() || !filename.unwrap().is_ascii() || filename.unwrap().len() < 65 {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::Other,
+ "Invalid ChannelMonitor file name",
+ ));
+ }
-pub(crate) fn read_channelmonitors(path: String, keys_manager: Arc<KeysManager>) ->
- Result<HashMap<OutPoint, (BlockHash, ChannelMonitor<InMemorySigner>)>, std::io::Error>
-{
- if !Path::new(&path).exists() {
- return Ok(HashMap::new())
- }
- let mut outpoint_to_channelmonitor = HashMap::new();
- for file_option in fs::read_dir(path).unwrap() {
- let file = file_option.unwrap();
- let owned_file_name = file.file_name();
- let filename = owned_file_name.to_str();
- if !filename.is_some() || !filename.unwrap().is_ascii() || filename.unwrap().len() < 65 {
- return Err(std::io::Error::new(std::io::ErrorKind::Other, "Invalid ChannelMonitor file name"));
- }
-
- let txid = Txid::from_hex(filename.unwrap().split_at(64).0);
- if txid.is_err() {
- return Err(std::io::Error::new(std::io::ErrorKind::Other, "Invalid tx ID in filename"));
- }
+ let txid = Txid::from_hex(filename.unwrap().split_at(64).0);
+ if txid.is_err() {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::Other,
+ "Invalid tx ID in filename",
+ ));
+ }
- let index = filename.unwrap().split_at(65).1.split('.').next().unwrap().parse();
- if index.is_err() {
- return Err(std::io::Error::new(std::io::ErrorKind::Other, "Invalid tx index in filename"));
- }
+ let index = filename.unwrap().split_at(65).1.split('.').next().unwrap().parse();
+ if index.is_err() {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::Other,
+ "Invalid tx index in filename",
+ ));
+ }
- let contents = fs::read(&file.path())?;
+ let contents = fs::read(&file.path())?;
- if let Ok((blockhash, channel_monitor)) =
- <(BlockHash, ChannelMonitor<InMemorySigner>)>::read(&mut Cursor::new(&contents),
- &*keys_manager)
- {
- outpoint_to_channelmonitor.insert(OutPoint { txid: txid.unwrap(), index: index.unwrap() },
- (blockhash, channel_monitor));
- } else {
- return Err(std::io::Error::new(std::io::ErrorKind::Other,
- "Failed to deserialize ChannelMonitor"));
- }
- }
- Ok(outpoint_to_channelmonitor)
+ if let Ok((blockhash, channel_monitor)) =
+ <(BlockHash, ChannelMonitor<InMemorySigner>)>::read(
+ &mut Cursor::new(&contents),
+ &*keys_manager,
+ ) {
+ outpoint_to_channelmonitor.insert(
+ OutPoint { txid: txid.unwrap(), index: index.unwrap() },
+ (blockhash, channel_monitor),
+ );
+ } else {
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::Other,
+ "Failed to deserialize ChannelMonitor",
+ ));
+ }
+ }
+ Ok(outpoint_to_channelmonitor)
}
use bitcoin::secp256k1::key::PublicKey;
pub fn to_vec(hex: &str) -> Option<Vec<u8>> {
- let mut out = Vec::with_capacity(hex.len() / 2);
+ let mut out = Vec::with_capacity(hex.len() / 2);
- let mut b = 0;
- for (idx, c) in hex.as_bytes().iter().enumerate() {
- b <<= 4;
- match *c {
- b'A'..=b'F' => b |= c - b'A' + 10,
- b'a'..=b'f' => b |= c - b'a' + 10,
- b'0'..=b'9' => b |= c - b'0',
- _ => return None,
- }
- if (idx & 1) == 1 {
- out.push(b);
- b = 0;
- }
- }
+ let mut b = 0;
+ for (idx, c) in hex.as_bytes().iter().enumerate() {
+ b <<= 4;
+ match *c {
+ b'A'..=b'F' => b |= c - b'A' + 10,
+ b'a'..=b'f' => b |= c - b'a' + 10,
+ b'0'..=b'9' => b |= c - b'0',
+ _ => return None,
+ }
+ if (idx & 1) == 1 {
+ out.push(b);
+ b = 0;
+ }
+ }
- Some(out)
+ Some(out)
}
#[inline]
pub fn hex_str(value: &[u8]) -> String {
- let mut res = String::with_capacity(64);
- for v in value {
- res += &format!("{:02x}", v);
- }
- res
+ let mut res = String::with_capacity(64);
+ for v in value {
+ res += &format!("{:02x}", v);
+ }
+ res
}
pub fn to_compressed_pubkey(hex: &str) -> Option<PublicKey> {
- let data = match to_vec(&hex[0..33*2]) {
- Some(bytes) => bytes,
- None => return None
- };
- match PublicKey::from_slice(&data) {
- Ok(pk) => Some(pk),
- Err(_) => None,
- }
+ let data = match to_vec(&hex[0..33 * 2]) {
+ Some(bytes) => bytes,
+ None => return None,
+ };
+ match PublicKey::from_slice(&data) {
+ Ok(pk) => Some(pk),
+ Err(_) => None,
+ }
}
mod disk;
mod hex_utils;
-use lightning_background_processor::BackgroundProcessor;
-use bitcoin::BlockHash;
+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::hashes::Hash;
use bitcoin::hashes::sha256::Hash as Sha256;
+use bitcoin::hashes::Hash;
use bitcoin::network::constants::Network;
use bitcoin::secp256k1::Secp256k1;
+use bitcoin::BlockHash;
use bitcoin_bech32::WitnessProgram;
-use crate::bitcoind_client::BitcoindClient;
-use crate::disk::FilesystemLogger;
use lightning::chain;
use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
use lightning::chain::chainmonitor::ChainMonitor;
-use lightning::chain::Filter;
use lightning::chain::keysinterface::{InMemorySigner, KeysInterface, KeysManager};
use lightning::chain::transaction::OutPoint;
+use lightning::chain::Filter;
use lightning::chain::Watch;
use lightning::ln::channelmanager;
-use lightning::ln::channelmanager::{ChainParameters, ChannelManagerReadArgs, PaymentHash, PaymentPreimage,
- SimpleArcChannelManager};
+use lightning::ln::channelmanager::{
+ ChainParameters, ChannelManagerReadArgs, PaymentHash, PaymentPreimage, SimpleArcChannelManager,
+};
use lightning::ln::peer_handler::{MessageHandler, SimpleArcPeerManager};
+use lightning::routing::network_graph::NetGraphMsgHandler;
use lightning::util::config::UserConfig;
use lightning::util::events::{Event, EventsProvider};
use lightning::util::ser::ReadableArgs;
-use lightning_block_sync::UnboundedCache;
-use lightning_block_sync::SpvClient;
+use lightning_background_processor::BackgroundProcessor;
use lightning_block_sync::init;
use lightning_block_sync::poll;
+use lightning_block_sync::SpvClient;
+use lightning_block_sync::UnboundedCache;
use lightning_net_tokio::SocketDescriptor;
use lightning_persister::FilesystemPersister;
use rand::{thread_rng, Rng};
-use lightning::routing::network_graph::NetGraphMsgHandler;
use std::collections::HashMap;
use std::fmt;
use std::fs;
use std::fs::File;
use std::io;
-use std::io:: Write;
+use std::io::Write;
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::thread;
#[derive(PartialEq)]
pub(crate) enum HTLCDirection {
- Inbound,
- Outbound
+ Inbound,
+ Outbound,
}
pub(crate) enum HTLCStatus {
- Pending,
- Succeeded,
- Failed,
+ Pending,
+ Succeeded,
+ Failed,
}
pub(crate) struct SatoshiAmount(Option<u64>);
impl fmt::Display for SatoshiAmount {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- match self.0 {
- Some(amt) => write!(f, "{}", amt),
- None => write!(f, "unknown")
-
- }
- }
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ match self.0 {
+ Some(amt) => write!(f, "{}", amt),
+ None => write!(f, "unknown"),
+ }
+ }
}
-pub(crate) type PaymentInfoStorage = Arc<Mutex<HashMap<PaymentHash, (Option<PaymentPreimage>,
- HTLCDirection, HTLCStatus,
- SatoshiAmount)>>>;
-
-type ArcChainMonitor = ChainMonitor<InMemorySigner, Arc<dyn Filter>, Arc<BitcoindClient>,
-Arc<BitcoindClient>, Arc<FilesystemLogger>, Arc<FilesystemPersister>>;
-
-pub(crate) type PeerManager = SimpleArcPeerManager<SocketDescriptor, ArcChainMonitor, BitcoindClient,
-BitcoindClient, dyn chain::Access, FilesystemLogger>;
-
-pub(crate) type ChannelManager = SimpleArcChannelManager<ArcChainMonitor, BitcoindClient, BitcoindClient,
-FilesystemLogger>;
-
-fn handle_ldk_events(peer_manager: Arc<PeerManager>, channel_manager: Arc<ChannelManager>,
- chain_monitor: Arc<ArcChainMonitor>, bitcoind_client: Arc<BitcoindClient>,
- keys_manager: Arc<KeysManager>, payment_storage: PaymentInfoStorage,
- network: Network)
-{
- let mut pending_txs: HashMap<OutPoint, Transaction> = HashMap::new();
- loop {
- peer_manager.process_events();
- let loop_channel_manager = channel_manager.clone();
- let mut events = channel_manager.get_and_clear_pending_events();
- events.append(&mut chain_monitor.get_and_clear_pending_events());
- for event in events {
- match event {
- Event::FundingGenerationReady { temporary_channel_id, channel_value_satoshis,
- output_script, .. } => {
- // Construct the raw transaction with one output, that is paid the amount of the
- // channel.
- let addr = WitnessProgram::from_scriptpubkey(&output_script[..], match network {
- Network::Bitcoin => bitcoin_bech32::constants::Network::Bitcoin,
- Network::Testnet => bitcoin_bech32::constants::Network::Testnet,
- Network::Regtest => bitcoin_bech32::constants::Network::Regtest,
- Network::Signet => panic!("Signet unsupported"),
- }
- ).expect("Lightning funding tx should always be to a SegWit output").to_address();
- let mut outputs = vec![HashMap::with_capacity(1)];
- outputs[0].insert(addr, channel_value_satoshis as f64 / 100_000_000.0);
- let raw_tx = bitcoind_client.create_raw_transaction(outputs);
-
- // Have your wallet put the inputs into the transaction such that the output is
- // satisfied.
- let funded_tx = bitcoind_client.fund_raw_transaction(raw_tx);
- let change_output_position = funded_tx.changepos;
- assert!(change_output_position == 0 || change_output_position == 1);
-
- // Sign the final funding transaction and broadcast it.
- let signed_tx = bitcoind_client.sign_raw_transaction_with_wallet(funded_tx.hex);
- assert_eq!(signed_tx.complete, true);
- let final_tx: Transaction = encode::deserialize(&hex_utils::to_vec(&signed_tx.hex).unwrap()).unwrap();
- let outpoint = OutPoint {
- txid: final_tx.txid(),
- index: if change_output_position == 0 { 1 } else { 0 }
- };
- // Give the funding transaction back to LDK for opening the channel.
- loop_channel_manager.funding_transaction_generated(&temporary_channel_id,
- outpoint);
- pending_txs.insert(outpoint, final_tx);
- },
- Event::FundingBroadcastSafe { funding_txo, .. } => {
- let funding_tx = pending_txs.remove(&funding_txo).unwrap();
- bitcoind_client.broadcast_transaction(&funding_tx);
- println!("\nEVENT: broadcasted funding transaction");
- print!("> "); io::stdout().flush().unwrap();
- },
- Event::PaymentReceived { payment_hash, payment_secret, amt: amt_msat } => {
- let mut payments = payment_storage.lock().unwrap();
- if let Some((Some(preimage), _, _, _)) = payments.get(&payment_hash) {
- assert!(loop_channel_manager.claim_funds(preimage.clone(), &payment_secret,
- amt_msat));
- println!("\nEVENT: received payment from payment_hash {} of {} satoshis",
- hex_utils::hex_str(&payment_hash.0), amt_msat / 1000);
- print!("> "); io::stdout().flush().unwrap();
- let (_, _, ref mut status, _) = payments.get_mut(&payment_hash).unwrap();
- *status = HTLCStatus::Succeeded;
- } else {
- println!("\nERROR: we received a payment but didn't know the preimage");
- print!("> "); io::stdout().flush().unwrap();
- loop_channel_manager.fail_htlc_backwards(&payment_hash, &payment_secret);
- payments.insert(payment_hash, (None, HTLCDirection::Inbound,
- HTLCStatus::Failed, SatoshiAmount(None)));
- }
- },
- Event::PaymentSent { payment_preimage } => {
- let hashed = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
- let mut payments = payment_storage.lock().unwrap();
- for (payment_hash, (preimage_option, _, status, amt_sat)) in payments.iter_mut() {
- if *payment_hash == hashed {
- *preimage_option = Some(payment_preimage);
- *status = HTLCStatus::Succeeded;
- println!("\nNEW EVENT: successfully sent payment of {} satoshis from \
- payment hash {:?} with preimage {:?}", amt_sat,
- hex_utils::hex_str(&payment_hash.0),
- hex_utils::hex_str(&payment_preimage.0));
- print!("> "); io::stdout().flush().unwrap();
- }
- }
- },
- Event::PaymentFailed { payment_hash, rejected_by_dest } => {
- print!("\nNEW EVENT: Failed to send payment to payment hash {:?}: ",
- hex_utils::hex_str(&payment_hash.0));
- if rejected_by_dest {
- println!("rejected by destination node");
- } else {
- println!("route failed");
- }
- print!("> "); io::stdout().flush().unwrap();
-
- let mut payments = payment_storage.lock().unwrap();
- if payments.contains_key(&payment_hash) {
- let (_, _, ref mut status, _) = payments.get_mut(&payment_hash).unwrap();
- *status = HTLCStatus::Failed;
- }
- },
- Event::PendingHTLCsForwardable { time_forwardable } => {
- let forwarding_channel_manager = loop_channel_manager.clone();
- thread::spawn(move || {
- let min = time_forwardable.as_secs();
- let seconds_to_sleep = thread_rng().gen_range(min, min * 5);
- thread::sleep(Duration::new(seconds_to_sleep, 0));
- forwarding_channel_manager.process_pending_htlc_forwards();
- });
- },
- Event::SpendableOutputs { outputs } => {
- let destination_address = bitcoind_client.get_new_address();
- let output_descriptors = &outputs.iter().map(|a| a).collect::<Vec<_>>();
- let tx_feerate = bitcoind_client.get_est_sat_per_1000_weight(ConfirmationTarget::Normal);
- let spending_tx = keys_manager.spend_spendable_outputs(output_descriptors,
- Vec::new(),
- destination_address.script_pubkey(),
- tx_feerate, &Secp256k1::new()).unwrap();
- bitcoind_client.broadcast_transaction(&spending_tx);
- // XXX maybe need to rescan and blah?
- }
- }
- }
- thread::sleep(Duration::new(1, 0));
- }
+pub(crate) type PaymentInfoStorage = Arc<
+ Mutex<
+ HashMap<PaymentHash, (Option<PaymentPreimage>, HTLCDirection, HTLCStatus, SatoshiAmount)>,
+ >,
+>;
+
+type ArcChainMonitor = ChainMonitor<
+ InMemorySigner,
+ Arc<dyn Filter>,
+ Arc<BitcoindClient>,
+ Arc<BitcoindClient>,
+ Arc<FilesystemLogger>,
+ Arc<FilesystemPersister>,
+>;
+
+pub(crate) type PeerManager = SimpleArcPeerManager<
+ SocketDescriptor,
+ ArcChainMonitor,
+ BitcoindClient,
+ BitcoindClient,
+ dyn chain::Access,
+ FilesystemLogger,
+>;
+
+pub(crate) type ChannelManager =
+ SimpleArcChannelManager<ArcChainMonitor, BitcoindClient, BitcoindClient, FilesystemLogger>;
+
+fn handle_ldk_events(
+ peer_manager: Arc<PeerManager>, channel_manager: Arc<ChannelManager>,
+ chain_monitor: Arc<ArcChainMonitor>, bitcoind_client: Arc<BitcoindClient>,
+ keys_manager: Arc<KeysManager>, payment_storage: PaymentInfoStorage, network: Network,
+) {
+ let mut pending_txs: HashMap<OutPoint, Transaction> = HashMap::new();
+ loop {
+ peer_manager.process_events();
+ let loop_channel_manager = channel_manager.clone();
+ let mut events = channel_manager.get_and_clear_pending_events();
+ events.append(&mut chain_monitor.get_and_clear_pending_events());
+ for event in events {
+ match event {
+ Event::FundingGenerationReady {
+ temporary_channel_id,
+ channel_value_satoshis,
+ output_script,
+ ..
+ } => {
+ // Construct the raw transaction with one output, that is paid the amount of the
+ // channel.
+ let addr = WitnessProgram::from_scriptpubkey(
+ &output_script[..],
+ match network {
+ Network::Bitcoin => bitcoin_bech32::constants::Network::Bitcoin,
+ Network::Testnet => bitcoin_bech32::constants::Network::Testnet,
+ Network::Regtest => bitcoin_bech32::constants::Network::Regtest,
+ Network::Signet => panic!("Signet unsupported"),
+ },
+ )
+ .expect("Lightning funding tx should always be to a SegWit output")
+ .to_address();
+ let mut outputs = vec![HashMap::with_capacity(1)];
+ outputs[0].insert(addr, channel_value_satoshis as f64 / 100_000_000.0);
+ let raw_tx = bitcoind_client.create_raw_transaction(outputs);
+
+ // Have your wallet put the inputs into the transaction such that the output is
+ // satisfied.
+ let funded_tx = bitcoind_client.fund_raw_transaction(raw_tx);
+ let change_output_position = funded_tx.changepos;
+ assert!(change_output_position == 0 || change_output_position == 1);
+
+ // Sign the final funding transaction and broadcast it.
+ let signed_tx = bitcoind_client.sign_raw_transaction_with_wallet(funded_tx.hex);
+ assert_eq!(signed_tx.complete, true);
+ let final_tx: Transaction =
+ encode::deserialize(&hex_utils::to_vec(&signed_tx.hex).unwrap()).unwrap();
+ let outpoint = OutPoint {
+ txid: final_tx.txid(),
+ index: if change_output_position == 0 { 1 } else { 0 },
+ };
+ // Give the funding transaction back to LDK for opening the channel.
+ loop_channel_manager
+ .funding_transaction_generated(&temporary_channel_id, outpoint);
+ pending_txs.insert(outpoint, final_tx);
+ }
+ Event::FundingBroadcastSafe { funding_txo, .. } => {
+ let funding_tx = pending_txs.remove(&funding_txo).unwrap();
+ bitcoind_client.broadcast_transaction(&funding_tx);
+ println!("\nEVENT: broadcasted funding transaction");
+ print!("> ");
+ io::stdout().flush().unwrap();
+ }
+ Event::PaymentReceived { payment_hash, payment_secret, amt: amt_msat } => {
+ let mut payments = payment_storage.lock().unwrap();
+ if let Some((Some(preimage), _, _, _)) = payments.get(&payment_hash) {
+ assert!(loop_channel_manager.claim_funds(
+ preimage.clone(),
+ &payment_secret,
+ amt_msat
+ ));
+ println!(
+ "\nEVENT: received payment from payment_hash {} of {} satoshis",
+ hex_utils::hex_str(&payment_hash.0),
+ amt_msat / 1000
+ );
+ print!("> ");
+ io::stdout().flush().unwrap();
+ let (_, _, ref mut status, _) = payments.get_mut(&payment_hash).unwrap();
+ *status = HTLCStatus::Succeeded;
+ } else {
+ println!("\nERROR: we received a payment but didn't know the preimage");
+ print!("> ");
+ io::stdout().flush().unwrap();
+ loop_channel_manager.fail_htlc_backwards(&payment_hash, &payment_secret);
+ payments.insert(
+ payment_hash,
+ (None, HTLCDirection::Inbound, HTLCStatus::Failed, SatoshiAmount(None)),
+ );
+ }
+ }
+ Event::PaymentSent { payment_preimage } => {
+ let hashed = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
+ let mut payments = payment_storage.lock().unwrap();
+ for (payment_hash, (preimage_option, _, status, amt_sat)) in payments.iter_mut()
+ {
+ if *payment_hash == hashed {
+ *preimage_option = Some(payment_preimage);
+ *status = HTLCStatus::Succeeded;
+ println!(
+ "\nEVENT: successfully sent payment of {} satoshis from \
+ payment hash {:?} with preimage {:?}",
+ amt_sat,
+ hex_utils::hex_str(&payment_hash.0),
+ hex_utils::hex_str(&payment_preimage.0)
+ );
+ print!("> ");
+ io::stdout().flush().unwrap();
+ }
+ }
+ }
+ Event::PaymentFailed { payment_hash, rejected_by_dest } => {
+ print!(
+ "\nEVENT: Failed to send payment to payment hash {:?}: ",
+ hex_utils::hex_str(&payment_hash.0)
+ );
+ if rejected_by_dest {
+ println!("rejected by destination node");
+ } else {
+ println!("route failed");
+ }
+ print!("> ");
+ io::stdout().flush().unwrap();
+
+ let mut payments = payment_storage.lock().unwrap();
+ if payments.contains_key(&payment_hash) {
+ let (_, _, ref mut status, _) = payments.get_mut(&payment_hash).unwrap();
+ *status = HTLCStatus::Failed;
+ }
+ }
+ Event::PendingHTLCsForwardable { time_forwardable } => {
+ let forwarding_channel_manager = loop_channel_manager.clone();
+ thread::spawn(move || {
+ let min = time_forwardable.as_secs();
+ let seconds_to_sleep = thread_rng().gen_range(min, min * 5);
+ thread::sleep(Duration::new(seconds_to_sleep, 0));
+ forwarding_channel_manager.process_pending_htlc_forwards();
+ });
+ }
+ Event::SpendableOutputs { outputs } => {
+ let destination_address = bitcoind_client.get_new_address();
+ let output_descriptors = &outputs.iter().map(|a| a).collect::<Vec<_>>();
+ let tx_feerate =
+ bitcoind_client.get_est_sat_per_1000_weight(ConfirmationTarget::Normal);
+ let spending_tx = keys_manager
+ .spend_spendable_outputs(
+ output_descriptors,
+ Vec::new(),
+ destination_address.script_pubkey(),
+ tx_feerate,
+ &Secp256k1::new(),
+ )
+ .unwrap();
+ bitcoind_client.broadcast_transaction(&spending_tx);
+ // XXX maybe need to rescan and blah?
+ }
+ }
+ }
+ thread::sleep(Duration::new(1, 0));
+ }
}
fn main() {
- let args = match cli::parse_startup_args() {
- Ok(user_args) => user_args,
- Err(()) => return
- };
-
- // Initialize the LDK data directory if necessary.
- let ldk_data_dir = format!("{}/.ldk", args.ldk_storage_dir_path);
- fs::create_dir_all(ldk_data_dir.clone()).unwrap();
-
- // Initialize our bitcoind client.
- let bitcoind_client = match BitcoindClient::new(args.bitcoind_rpc_host.clone(),
- args.bitcoind_rpc_port, args.bitcoind_rpc_username.clone(),
- args.bitcoind_rpc_password.clone()) {
- Ok(client) => Arc::new(client),
- Err(e) => {
- println!("Failed to connect to bitcoind client: {}", e);
- return
- }
- };
- let mut bitcoind_rpc_client = bitcoind_client.get_new_rpc_client().unwrap();
-
- // ## Setup
- // Step 1: Initialize the FeeEstimator
-
- // BitcoindClient implements the FeeEstimator trait, so it'll act as our fee estimator.
- let fee_estimator = bitcoind_client.clone();
-
- // Step 2: Initialize the Logger
- let logger = Arc::new(FilesystemLogger::new(ldk_data_dir.clone()));
-
- // Step 3: Initialize the BroadcasterInterface
-
- // BitcoindClient implements the BroadcasterInterface trait, so it'll act as our transaction
- // broadcaster.
- let broadcaster = bitcoind_client.clone();
-
- // Step 4: Initialize Persist
- let persister = Arc::new(FilesystemPersister::new(ldk_data_dir.clone()));
-
- // Step 5: Initialize the ChainMonitor
- let chain_monitor: Arc<ArcChainMonitor> = Arc::new(ChainMonitor::new(None, broadcaster.clone(),
- logger.clone(), fee_estimator.clone(),
- persister.clone()));
-
- // Step 6: Initialize the KeysManager
-
- // The key seed that we use to derive the node privkey (that corresponds to the node pubkey) and
- // other secret key material.
- let keys_seed_path = format!("{}/keys_seed", ldk_data_dir.clone());
- let keys_seed = if let Ok(seed) = fs::read(keys_seed_path.clone()) {
- assert_eq!(seed.len(), 32);
- let mut key = [0; 32];
- key.copy_from_slice(&seed);
- key
- } else {
- let mut key = [0; 32];
- thread_rng().fill_bytes(&mut key);
- let mut f = File::create(keys_seed_path).unwrap();
- f.write_all(&key).expect("Failed to write node keys seed to disk");
- f.sync_all().expect("Failed to sync node keys seed to disk");
- key
- };
- let cur = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
- let keys_manager = Arc::new(KeysManager::new(&keys_seed, cur.as_secs(), cur.subsec_nanos()));
-
- // Step 7: Read ChannelMonitor state from disk
- let monitors_path = format!("{}/monitors", ldk_data_dir.clone());
- let mut outpoint_to_channelmonitor = disk::read_channelmonitors(monitors_path.to_string(),
- keys_manager.clone()).unwrap();
-
- // Step 9: Initialize the ChannelManager
- let user_config = UserConfig::default();
- let runtime = Runtime::new().unwrap();
- let mut restarting_node = true;
- let (channel_manager_blockhash, mut channel_manager) = {
- if let Ok(mut f) = fs::File::open(format!("{}/manager", ldk_data_dir.clone())) {
- let mut channel_monitor_mut_references = Vec::new();
- for (_, channel_monitor) in outpoint_to_channelmonitor.iter_mut() {
- channel_monitor_mut_references.push(&mut channel_monitor.1);
- }
- let read_args = ChannelManagerReadArgs::new(keys_manager.clone(), fee_estimator.clone(),
- chain_monitor.clone(), broadcaster.clone(),
- logger.clone(), user_config,
- channel_monitor_mut_references);
- <(BlockHash, ChannelManager)>::read(&mut f, read_args).unwrap()
- } else { // We're starting a fresh node.
- restarting_node = false;
- let getinfo_resp = bitcoind_client.get_blockchain_info();
- let chain_params = ChainParameters {
- network: args.network,
- latest_hash: getinfo_resp.latest_blockhash,
- latest_height: getinfo_resp.latest_height,
- };
- let fresh_channel_manager = channelmanager::ChannelManager::new(fee_estimator.clone(),
- chain_monitor.clone(),
- broadcaster.clone(),
- logger.clone(),
- keys_manager.clone(),
- user_config, chain_params);
- (getinfo_resp.latest_blockhash, fresh_channel_manager)
- }
- };
-
- // Step 10: Sync ChannelMonitors and ChannelManager to chain tip
- let mut chain_listener_channel_monitors = Vec::new();
- let mut cache = UnboundedCache::new();
- let mut chain_tip: Option<poll::ValidatedBlockHeader> = None;
- if restarting_node {
- let mut chain_listeners = vec![
- (channel_manager_blockhash, &mut channel_manager as &mut dyn chain::Listen)];
-
- for (outpoint, blockhash_and_monitor) in outpoint_to_channelmonitor.drain() {
- let blockhash = blockhash_and_monitor.0;
- let channel_monitor = blockhash_and_monitor.1;
- chain_listener_channel_monitors.push((blockhash, (channel_monitor,
- broadcaster.clone(), fee_estimator.clone(),
- logger.clone()), outpoint));
- }
-
- for monitor_listener_info in chain_listener_channel_monitors.iter_mut() {
- chain_listeners.push((monitor_listener_info.0,
- &mut monitor_listener_info.1 as &mut dyn chain::Listen));
- }
- chain_tip = Some(runtime.block_on(init::synchronize_listeners(&mut bitcoind_rpc_client, args.network,
- &mut cache, chain_listeners)).unwrap());
- }
-
- // Step 11: Give ChannelMonitors to ChainMonitor
- for item in chain_listener_channel_monitors.drain(..) {
- let channel_monitor = item.1.0;
- let funding_outpoint = item.2;
- chain_monitor.watch_channel(funding_outpoint, channel_monitor).unwrap();
- }
-
- // Step 13: Optional: Initialize the NetGraphMsgHandler
- // XXX persist routing data
- let genesis = genesis_block(args.network).header.block_hash();
- let router = Arc::new(NetGraphMsgHandler::new(genesis, None::<Arc<dyn chain::Access>>, logger.clone()));
-
- // Step 14: Initialize the PeerManager
- let channel_manager: Arc<ChannelManager> = Arc::new(channel_manager);
- let mut ephemeral_bytes = [0; 32];
- rand::thread_rng().fill_bytes(&mut ephemeral_bytes);
- let lightning_msg_handler = MessageHandler { chan_handler: channel_manager.clone(),
- route_handler: router.clone() };
- let peer_manager: Arc<PeerManager> = Arc::new(PeerManager::new(lightning_msg_handler,
- keys_manager.get_node_secret(),
- &ephemeral_bytes, logger.clone()));
-
- // ## Running LDK
- // Step 16: Initialize Peer Connection Handling
-
- // We poll for events in handle_ldk_events(..) rather than waiting for them over the
- // mpsc::channel, so we can leave the event receiver as unused.
- let (event_ntfn_sender, mut _event_ntfn_receiver) = mpsc::channel(2);
- let peer_manager_connection_handler = peer_manager.clone();
- let event_notifier = event_ntfn_sender.clone();
- let listening_port = args.ldk_peer_listening_port;
- runtime.spawn(async move {
- let listener = std::net::TcpListener::bind(format!("0.0.0.0:{}", listening_port)).unwrap();
- loop {
- let tcp_stream = listener.accept().unwrap().0;
- lightning_net_tokio::setup_inbound(peer_manager_connection_handler.clone(),
- event_notifier.clone(), tcp_stream).await;
- }
- });
-
- // Step 17: Connect and Disconnect Blocks
- if chain_tip.is_none() {
- chain_tip = Some(runtime.block_on(init::validate_best_block_header(&mut bitcoind_rpc_client)).unwrap());
- }
- let channel_manager_listener = channel_manager.clone();
- let chain_monitor_listener = chain_monitor.clone();
- let network = args.network;
- runtime.spawn(async move {
- let chain_poller = poll::ChainPoller::new(&mut bitcoind_rpc_client, network);
- let chain_listener = (chain_monitor_listener, channel_manager_listener);
- let mut spv_client = SpvClient::new(chain_tip.unwrap(), chain_poller, &mut cache,
- &chain_listener);
- loop {
- spv_client.poll_best_tip().await.unwrap();
- thread::sleep(Duration::new(1, 0));
- }
- });
-
- // Step 17 & 18: Initialize ChannelManager persistence & Once Per Minute: ChannelManager's
- // timer_chan_freshness_every_min() and PeerManager's timer_tick_occurred
- let runtime_handle = runtime.handle();
- let data_dir = ldk_data_dir.clone();
- let persist_channel_manager_callback = move |node: &ChannelManager| {
- FilesystemPersister::persist_manager(data_dir.clone(), &*node)
- };
- BackgroundProcessor::start(persist_channel_manager_callback, channel_manager.clone(),
- logger.clone());
-
- let peer_manager_processor = peer_manager.clone();
- runtime_handle.spawn(async move {
- loop {
- peer_manager_processor.timer_tick_occurred();
- thread::sleep(Duration::new(60, 0));
- }
- });
-
- // Step 15: Initialize LDK Event Handling
- let peer_manager_event_listener = peer_manager.clone();
- let channel_manager_event_listener = channel_manager.clone();
- let chain_monitor_event_listener = chain_monitor.clone();
- let keys_manager_listener = keys_manager.clone();
- let payment_info: PaymentInfoStorage = Arc::new(Mutex::new(HashMap::new()));
- let payment_info_for_events = payment_info.clone();
- let handle = runtime_handle.clone();
- let network = args.network;
- thread::spawn(move || {
- handle_ldk_events(peer_manager_event_listener, channel_manager_event_listener,
- chain_monitor_event_listener, bitcoind_client.clone(),
- keys_manager_listener, payment_info_for_events, network);
- });
-
- // Reconnect to channel peers if possible.
- let peer_data_path = format!("{}/channel_peer_data", ldk_data_dir.clone());
- match disk::read_channel_peer_data(Path::new(&peer_data_path)) {
- Ok(mut info) => {
- for (pubkey, peer_addr) in info.drain() {
- let _ = cli::connect_peer_if_necessary(pubkey, peer_addr, peer_manager.clone(),
- event_ntfn_sender.clone(), handle.clone());
- }
- },
- Err(e) => println!("ERROR: errored reading channel peer info from disk: {:?}", e),
- }
-
- // Start the CLI.
- cli::poll_for_user_input(peer_manager.clone(), channel_manager.clone(), router.clone(),
- payment_info, keys_manager.get_node_secret(), event_ntfn_sender,
- ldk_data_dir.clone(), logger.clone(), handle, args.network);
+ let args = match cli::parse_startup_args() {
+ Ok(user_args) => user_args,
+ Err(()) => return,
+ };
+
+ // Initialize the LDK data directory if necessary.
+ let ldk_data_dir = format!("{}/.ldk", args.ldk_storage_dir_path);
+ fs::create_dir_all(ldk_data_dir.clone()).unwrap();
+
+ // Initialize our bitcoind client.
+ let bitcoind_client = match BitcoindClient::new(
+ args.bitcoind_rpc_host.clone(),
+ args.bitcoind_rpc_port,
+ args.bitcoind_rpc_username.clone(),
+ args.bitcoind_rpc_password.clone(),
+ ) {
+ Ok(client) => Arc::new(client),
+ Err(e) => {
+ println!("Failed to connect to bitcoind client: {}", e);
+ return;
+ }
+ };
+ let mut bitcoind_rpc_client = bitcoind_client.get_new_rpc_client().unwrap();
+
+ // ## Setup
+ // Step 1: Initialize the FeeEstimator
+
+ // BitcoindClient implements the FeeEstimator trait, so it'll act as our fee estimator.
+ let fee_estimator = bitcoind_client.clone();
+
+ // Step 2: Initialize the Logger
+ let logger = Arc::new(FilesystemLogger::new(ldk_data_dir.clone()));
+
+ // Step 3: Initialize the BroadcasterInterface
+
+ // BitcoindClient implements the BroadcasterInterface trait, so it'll act as our transaction
+ // broadcaster.
+ let broadcaster = bitcoind_client.clone();
+
+ // Step 4: Initialize Persist
+ let persister = Arc::new(FilesystemPersister::new(ldk_data_dir.clone()));
+
+ // Step 5: Initialize the ChainMonitor
+ let chain_monitor: Arc<ArcChainMonitor> = Arc::new(ChainMonitor::new(
+ None,
+ broadcaster.clone(),
+ logger.clone(),
+ fee_estimator.clone(),
+ persister.clone(),
+ ));
+
+ // Step 6: Initialize the KeysManager
+
+ // The key seed that we use to derive the node privkey (that corresponds to the node pubkey) and
+ // other secret key material.
+ let keys_seed_path = format!("{}/keys_seed", ldk_data_dir.clone());
+ let keys_seed = if let Ok(seed) = fs::read(keys_seed_path.clone()) {
+ assert_eq!(seed.len(), 32);
+ let mut key = [0; 32];
+ key.copy_from_slice(&seed);
+ key
+ } else {
+ let mut key = [0; 32];
+ thread_rng().fill_bytes(&mut key);
+ let mut f = File::create(keys_seed_path).unwrap();
+ f.write_all(&key).expect("Failed to write node keys seed to disk");
+ f.sync_all().expect("Failed to sync node keys seed to disk");
+ key
+ };
+ let cur = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
+ let keys_manager = Arc::new(KeysManager::new(&keys_seed, cur.as_secs(), cur.subsec_nanos()));
+
+ // Step 7: Read ChannelMonitor state from disk
+ let monitors_path = format!("{}/monitors", ldk_data_dir.clone());
+ let mut outpoint_to_channelmonitor =
+ disk::read_channelmonitors(monitors_path.to_string(), keys_manager.clone()).unwrap();
+
+ // Step 9: Initialize the ChannelManager
+ let user_config = UserConfig::default();
+ let runtime = Runtime::new().unwrap();
+ let mut restarting_node = true;
+ let (channel_manager_blockhash, mut channel_manager) = {
+ if let Ok(mut f) = fs::File::open(format!("{}/manager", ldk_data_dir.clone())) {
+ let mut channel_monitor_mut_references = Vec::new();
+ for (_, channel_monitor) in outpoint_to_channelmonitor.iter_mut() {
+ channel_monitor_mut_references.push(&mut channel_monitor.1);
+ }
+ let read_args = ChannelManagerReadArgs::new(
+ keys_manager.clone(),
+ fee_estimator.clone(),
+ chain_monitor.clone(),
+ broadcaster.clone(),
+ logger.clone(),
+ user_config,
+ channel_monitor_mut_references,
+ );
+ <(BlockHash, ChannelManager)>::read(&mut f, read_args).unwrap()
+ } else {
+ // We're starting a fresh node.
+ restarting_node = false;
+ let getinfo_resp = bitcoind_client.get_blockchain_info();
+ let chain_params = ChainParameters {
+ network: args.network,
+ latest_hash: getinfo_resp.latest_blockhash,
+ latest_height: getinfo_resp.latest_height,
+ };
+ let fresh_channel_manager = channelmanager::ChannelManager::new(
+ fee_estimator.clone(),
+ chain_monitor.clone(),
+ broadcaster.clone(),
+ logger.clone(),
+ keys_manager.clone(),
+ user_config,
+ chain_params,
+ );
+ (getinfo_resp.latest_blockhash, fresh_channel_manager)
+ }
+ };
+
+ // Step 10: Sync ChannelMonitors and ChannelManager to chain tip
+ let mut chain_listener_channel_monitors = Vec::new();
+ let mut cache = UnboundedCache::new();
+ let mut chain_tip: Option<poll::ValidatedBlockHeader> = None;
+ if restarting_node {
+ let mut chain_listeners =
+ vec![(channel_manager_blockhash, &mut channel_manager as &mut dyn chain::Listen)];
+
+ for (outpoint, blockhash_and_monitor) in outpoint_to_channelmonitor.drain() {
+ let blockhash = blockhash_and_monitor.0;
+ let channel_monitor = blockhash_and_monitor.1;
+ chain_listener_channel_monitors.push((
+ blockhash,
+ (channel_monitor, broadcaster.clone(), fee_estimator.clone(), logger.clone()),
+ outpoint,
+ ));
+ }
+
+ for monitor_listener_info in chain_listener_channel_monitors.iter_mut() {
+ chain_listeners.push((
+ monitor_listener_info.0,
+ &mut monitor_listener_info.1 as &mut dyn chain::Listen,
+ ));
+ }
+ chain_tip = Some(
+ runtime
+ .block_on(init::synchronize_listeners(
+ &mut bitcoind_rpc_client,
+ args.network,
+ &mut cache,
+ chain_listeners,
+ ))
+ .unwrap(),
+ );
+ }
+
+ // Step 11: Give ChannelMonitors to ChainMonitor
+ for item in chain_listener_channel_monitors.drain(..) {
+ let channel_monitor = item.1 .0;
+ let funding_outpoint = item.2;
+ chain_monitor.watch_channel(funding_outpoint, channel_monitor).unwrap();
+ }
+
+ // Step 13: Optional: Initialize the NetGraphMsgHandler
+ // XXX persist routing data
+ let genesis = genesis_block(args.network).header.block_hash();
+ let router =
+ Arc::new(NetGraphMsgHandler::new(genesis, None::<Arc<dyn chain::Access>>, logger.clone()));
+
+ // Step 14: Initialize the PeerManager
+ let channel_manager: Arc<ChannelManager> = Arc::new(channel_manager);
+ let mut ephemeral_bytes = [0; 32];
+ rand::thread_rng().fill_bytes(&mut ephemeral_bytes);
+ let lightning_msg_handler =
+ MessageHandler { chan_handler: channel_manager.clone(), route_handler: router.clone() };
+ let peer_manager: Arc<PeerManager> = Arc::new(PeerManager::new(
+ lightning_msg_handler,
+ keys_manager.get_node_secret(),
+ &ephemeral_bytes,
+ logger.clone(),
+ ));
+
+ // ## Running LDK
+ // Step 16: Initialize Peer Connection Handling
+
+ // We poll for events in handle_ldk_events(..) rather than waiting for them over the
+ // mpsc::channel, so we can leave the event receiver as unused.
+ let (event_ntfn_sender, mut _event_ntfn_receiver) = mpsc::channel(2);
+ let peer_manager_connection_handler = peer_manager.clone();
+ let event_notifier = event_ntfn_sender.clone();
+ let listening_port = args.ldk_peer_listening_port;
+ runtime.spawn(async move {
+ let listener = std::net::TcpListener::bind(format!("0.0.0.0:{}", listening_port)).unwrap();
+ loop {
+ let tcp_stream = listener.accept().unwrap().0;
+ lightning_net_tokio::setup_inbound(
+ peer_manager_connection_handler.clone(),
+ event_notifier.clone(),
+ tcp_stream,
+ )
+ .await;
+ }
+ });
+
+ // Step 17: Connect and Disconnect Blocks
+ if chain_tip.is_none() {
+ chain_tip = Some(
+ runtime.block_on(init::validate_best_block_header(&mut bitcoind_rpc_client)).unwrap(),
+ );
+ }
+ let channel_manager_listener = channel_manager.clone();
+ let chain_monitor_listener = chain_monitor.clone();
+ let network = args.network;
+ runtime.spawn(async move {
+ let chain_poller = poll::ChainPoller::new(&mut bitcoind_rpc_client, network);
+ let chain_listener = (chain_monitor_listener, channel_manager_listener);
+ let mut spv_client =
+ SpvClient::new(chain_tip.unwrap(), chain_poller, &mut cache, &chain_listener);
+ loop {
+ spv_client.poll_best_tip().await.unwrap();
+ thread::sleep(Duration::new(1, 0));
+ }
+ });
+
+ // Step 17 & 18: Initialize ChannelManager persistence & Once Per Minute: ChannelManager's
+ // timer_chan_freshness_every_min() and PeerManager's timer_tick_occurred
+ let runtime_handle = runtime.handle();
+ let data_dir = ldk_data_dir.clone();
+ let persist_channel_manager_callback =
+ move |node: &ChannelManager| FilesystemPersister::persist_manager(data_dir.clone(), &*node);
+ BackgroundProcessor::start(
+ persist_channel_manager_callback,
+ channel_manager.clone(),
+ logger.clone(),
+ );
+
+ let peer_manager_processor = peer_manager.clone();
+ runtime_handle.spawn(async move {
+ loop {
+ peer_manager_processor.timer_tick_occurred();
+ thread::sleep(Duration::new(60, 0));
+ }
+ });
+
+ // Step 15: Initialize LDK Event Handling
+ let peer_manager_event_listener = peer_manager.clone();
+ let channel_manager_event_listener = channel_manager.clone();
+ let chain_monitor_event_listener = chain_monitor.clone();
+ let keys_manager_listener = keys_manager.clone();
+ let payment_info: PaymentInfoStorage = Arc::new(Mutex::new(HashMap::new()));
+ let payment_info_for_events = payment_info.clone();
+ let handle = runtime_handle.clone();
+ let network = args.network;
+ thread::spawn(move || {
+ handle_ldk_events(
+ peer_manager_event_listener,
+ channel_manager_event_listener,
+ chain_monitor_event_listener,
+ bitcoind_client.clone(),
+ keys_manager_listener,
+ payment_info_for_events,
+ network,
+ );
+ });
+
+ // Reconnect to channel peers if possible.
+ let peer_data_path = format!("{}/channel_peer_data", ldk_data_dir.clone());
+ match disk::read_channel_peer_data(Path::new(&peer_data_path)) {
+ Ok(mut info) => {
+ for (pubkey, peer_addr) in info.drain() {
+ let _ = cli::connect_peer_if_necessary(
+ pubkey,
+ peer_addr,
+ peer_manager.clone(),
+ event_ntfn_sender.clone(),
+ handle.clone(),
+ );
+ }
+ }
+ Err(e) => println!("ERROR: errored reading channel peer info from disk: {:?}", e),
+ }
+
+ // Start the CLI.
+ cli::poll_for_user_input(
+ peer_manager.clone(),
+ channel_manager.clone(),
+ router.clone(),
+ payment_info,
+ keys_manager.get_node_secret(),
+ event_ntfn_sender,
+ ldk_data_dir.clone(),
+ logger.clone(),
+ handle,
+ args.network,
+ );
}