diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 1a70ea03f..9a0bf1356 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -25,3 +25,5 @@ jobs: - name: Check formatting if: matrix.check-fmt run: rustup component add rustfmt && cargo fmt --all -- --check + - name: Test on Rust ${{ matrix.toolchain }} + run: cargo test diff --git a/Cargo.toml b/Cargo.toml index d996a65ec..820b51267 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,30 +1,63 @@ [package] -name = "ldk-lite" +name = "ldk-node" version = "0.1.0" authors = ["Elias Rohrer "] license = "MIT OR Apache-2.0" edition = "2018" +description = "A ready-to-go node implementation built using LDK." # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -lightning = { version = "0.0.110", features = ["max_level_trace", "std"] } -lightning-invoice = { version = "0.18" } -lightning-net-tokio = { version = "0.0.110" } -lightning-persister = { version = "0.0.110" } -lightning-background-processor = { version = "0.0.110" } -lightning-rapid-gossip-sync = { version = "0.0.110" } +#lightning = { version = "0.0.114", features = ["max_level_trace", "std"] } +#lightning-invoice = { version = "0.22" } +#lightning-net-tokio = { version = "0.0.114" } +#lightning-persister = { version = "0.0.114" } +#lightning-background-processor = { version = "0.0.114" } +#lightning-rapid-gossip-sync = { version = "0.0.114" } +#lightning-transaction-sync = { version = "0.0.114", features = ["esplora-async"] } -#bdk = "0.20.0" -bdk = { git = "https://github.com/tnull/bdk", branch="feat/use-external-esplora-client", features = ["use-esplora-ureq", "key-value-db"]} -bitcoin = "0.28.1" +lightning = { git = "https://github.com/lightningdevkit/rust-lightning", branch="main", features = ["max_level_trace", "std"] } +lightning-invoice = { git = "https://github.com/lightningdevkit/rust-lightning", branch="main" } +lightning-net-tokio = { git = "https://github.com/lightningdevkit/rust-lightning", branch="main" } +lightning-persister = { git = "https://github.com/lightningdevkit/rust-lightning", branch="main" } +lightning-background-processor = { git = "https://github.com/lightningdevkit/rust-lightning", branch="main" } +lightning-rapid-gossip-sync = { git = "https://github.com/lightningdevkit/rust-lightning", branch="main" } +lightning-transaction-sync = { git = "https://github.com/lightningdevkit/rust-lightning", branch="main", features = ["esplora-async"] } + +#lightning = { git = "https://github.com/tnull/rust-lightning", branch="2023-03-expose-impl-writeable-tlv-based-enum-common", features = ["max_level_trace", "std"] } +#lightning-invoice = { git = "https://github.com/tnull/rust-lightning", branch="2023-03-expose-impl-writeable-tlv-based-enum-common" } +#lightning-net-tokio = { git = "https://github.com/tnull/rust-lightning", branch="2023-03-expose-impl-writeable-tlv-based-enum-common" } +#lightning-persister = { git = "https://github.com/tnull/rust-lightning", branch="2023-03-expose-impl-writeable-tlv-based-enum-common" } +#lightning-background-processor = { git = "https://github.com/tnull/rust-lightning", branch="2023-03-expose-impl-writeable-tlv-based-enum-common" } +#lightning-rapid-gossip-sync = { git = "https://github.com/tnull/rust-lightning", branch="2023-03-expose-impl-writeable-tlv-based-enum-common" } +#lightning-transaction-sync = { git = "https://github.com/tnull/rust-lightning", branch="2023-03-expose-impl-writeable-tlv-based-enum-common", features = ["esplora-async"] } + +#lightning = { path = "../rust-lightning/lightning", features = ["max_level_trace", "std"] } +#lightning-invoice = { path = "../rust-lightning/lightning-invoice" } +#lightning-net-tokio = { path = "../rust-lightning/lightning-net-tokio" } +#lightning-persister = { path = "../rust-lightning/lightning-persister" } +#lightning-background-processor = { path = "../rust-lightning/lightning-background-processor" } +#lightning-rapid-gossip-sync = { path = "../rust-lightning/lightning-rapid-gossip-sync" } +#lightning-transaction-sync = { path = "../rust-lightning/lightning-transaction-sync", features = ["esplora-async"] } + +bdk = { version = "=0.27.1", default-features = false, features = ["async-interface", "use-esplora-async", "sqlite-bundled"]} +reqwest = { version = "0.11", default-features = false, features = ["json", "rustls-tls"] } +rusqlite = { version = "0.28.0", features = ["bundled"] } +bitcoin = "0.29.2" rand = "0.8.5" chrono = "0.4" futures = "0.3" serde_json = { version = "1.0" } -tokio = { version = "1", features = [ "io-util", "macros", "rt", "rt-multi-thread", "sync", "net", "time" ] } +tokio = { version = "1", default-features = false, features = [ "rt-multi-thread", "time", "sync" ] } +esplora-client = { version = "=0.3", default-features = false } +[dev-dependencies] +electrsd = { version = "0.22.0", features = ["legacy", "esplora_a33e97e1", "bitcoind_23_0"] } +electrum-client = "0.12.0" +once_cell = "1.16.0" +proptest = "1.0.0" [profile.release] panic = "abort" diff --git a/README.md b/README.md index 22385f1fe..a82bd2758 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,2 @@ # LDK Node -A ready-to-go node implementation based on LDK. +A ready-to-go node implementation built using LDK. diff --git a/src/error.rs b/src/error.rs index e3b34613a..cefa57538 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,17 +1,11 @@ -use bdk::blockchain::esplora; -use lightning::ln::msgs; -use lightning::util::errors; -use lightning_invoice::payment; use std::fmt; -use std::io; -use std::time; -#[derive(Debug)] +#[derive(Debug, PartialEq, Eq)] /// An error that possibly needs to be handled by the user. -pub enum LdkLiteError { - /// Returned when trying to start LdkLite while it is already running. +pub enum Error { + /// Returned when trying to start [`crate::Node`] while it is already running. AlreadyRunning, - /// Returned when trying to stop LdkLite while it is not running. + /// Returned when trying to stop [`crate::Node`] while it is not running. NotRunning, /// The funding transaction could not be created. FundingTxCreationFailed, @@ -19,112 +13,73 @@ pub enum LdkLiteError { ConnectionFailed, /// Payment of the given invoice has already been intiated. NonUniquePaymentHash, + /// The given amount is invalid. + InvalidAmount, + /// The given invoice is invalid. + InvalidInvoice, + /// Invoice creation failed. + InvoiceCreationFailed, + /// There are insufficient funds to complete the given operation. + InsufficientFunds, + /// An attempted payment has failed. + PaymentFailed, /// A given peer info could not be parsed. - PeerInfoParse(&'static str), - /// A wrapped LDK `APIError` - LdkApi(errors::APIError), - /// A wrapped LDK `DecodeError` - LdkDecode(msgs::DecodeError), - /// A wrapped LDK `PaymentError` - LdkPayment(payment::PaymentError), - /// A wrapped LDK `SignOrCreationError` - LdkInvoiceCreation(lightning_invoice::SignOrCreationError), - /// A wrapped BDK error - Bdk(bdk::Error), - /// A wrapped `EsploraError` - Esplora(esplora::EsploraError), - /// A wrapped `Bip32` error - Bip32(bitcoin::util::bip32::Error), - /// A wrapped `std::io::Error` - StdIo(io::Error), - /// A wrapped `SystemTimeError` - StdTime(time::SystemTimeError), + PeerInfoParseFailed, + /// A channel could not be opened. + ChannelCreationFailed, + /// A channel could not be closed. + ChannelClosingFailed, + /// Persistence failed. + PersistenceFailed, + /// A wallet operation failed. + WalletOperationFailed, + /// A siging operation failed. + WalletSigningFailed, + /// A transaction sync operation failed. + TxSyncFailed, } -impl fmt::Display for LdkLiteError { +impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - LdkLiteError::AlreadyRunning => write!(f, "LDKLite is already running."), - LdkLiteError::NotRunning => write!(f, "LDKLite is not running."), - LdkLiteError::FundingTxCreationFailed => { - write!(f, "the funding transaction could not be created") + Self::AlreadyRunning => write!(f, "Node is already running."), + Self::NotRunning => write!(f, "Node is not running."), + Self::FundingTxCreationFailed => { + write!(f, "Funding transaction could not be created.") } - LdkLiteError::ConnectionFailed => write!(f, "network connection closed"), - LdkLiteError::NonUniquePaymentHash => write!(f, "an invoice must not get payed twice."), - LdkLiteError::PeerInfoParse(ref e) => { - write!(f, "given peer info could not be parsed: {}", e) + Self::ConnectionFailed => write!(f, "Network connection closed."), + Self::NonUniquePaymentHash => write!(f, "An invoice must not get payed twice."), + Self::InvalidAmount => write!(f, "The given amount is invalid."), + Self::InvalidInvoice => write!(f, "The given invoice is invalid."), + Self::InvoiceCreationFailed => write!(f, "Failed to create invoice."), + Self::InsufficientFunds => { + write!(f, "There are insufficient funds to complete the given operation.") } - LdkLiteError::LdkDecode(ref e) => write!(f, "LDK decode error: {}", e), - LdkLiteError::LdkApi(ref e) => write!(f, "LDK API error: {:?}", e), - LdkLiteError::LdkPayment(ref e) => write!(f, "LDK payment error: {:?}", e), - LdkLiteError::LdkInvoiceCreation(ref e) => { - write!(f, "LDK invoice sign or creation error: {:?}", e) - } - LdkLiteError::Bdk(ref e) => write!(f, "BDK error: {}", e), - LdkLiteError::Esplora(ref e) => write!(f, "Esplora error: {}", e), - LdkLiteError::Bip32(ref e) => write!(f, "Bitcoin error: {}", e), - LdkLiteError::StdIo(ref e) => write!(f, "IO error: {}", e), - LdkLiteError::StdTime(ref e) => write!(f, "time error: {}", e), + Self::PaymentFailed => write!(f, "Failed to send the given payment."), + Self::PeerInfoParseFailed => write!(f, "Failed to parse the given peer information."), + Self::ChannelCreationFailed => write!(f, "Failed to create channel."), + Self::ChannelClosingFailed => write!(f, "Failed to close channel."), + Self::PersistenceFailed => write!(f, "Failed to persist data."), + Self::WalletOperationFailed => write!(f, "Failed to conduct wallet operation."), + Self::WalletSigningFailed => write!(f, "Failed to sign given transaction."), + Self::TxSyncFailed => write!(f, "Failed to sync transactions."), } } } -impl From for LdkLiteError { - fn from(e: errors::APIError) -> Self { - Self::LdkApi(e) - } -} +impl std::error::Error for Error {} -impl From for LdkLiteError { - fn from(e: msgs::DecodeError) -> Self { - Self::LdkDecode(e) - } -} - -impl From for LdkLiteError { - fn from(e: payment::PaymentError) -> Self { - Self::LdkPayment(e) - } -} - -impl From for LdkLiteError { - fn from(e: lightning_invoice::SignOrCreationError) -> Self { - Self::LdkInvoiceCreation(e) - } -} - -impl From for LdkLiteError { +impl From for Error { fn from(e: bdk::Error) -> Self { - Self::Bdk(e) - } -} - -impl From for LdkLiteError { - fn from(e: bdk::sled::Error) -> Self { - Self::Bdk(bdk::Error::Sled(e)) - } -} - -impl From for LdkLiteError { - fn from(e: bitcoin::util::bip32::Error) -> Self { - Self::Bip32(e) - } -} - -impl From for LdkLiteError { - fn from(e: io::Error) -> Self { - Self::StdIo(e) - } -} - -impl From for LdkLiteError { - fn from(e: time::SystemTimeError) -> Self { - Self::StdTime(e) + match e { + bdk::Error::Signer(_) => Self::WalletSigningFailed, + _ => Self::WalletOperationFailed, + } } } -impl From for LdkLiteError { - fn from(e: esplora::EsploraError) -> Self { - Self::Esplora(e) +impl From for Error { + fn from(_e: lightning_transaction_sync::TxSyncError) -> Self { + Self::TxSyncFailed } } diff --git a/src/event.rs b/src/event.rs index 9b4e598f8..10f0c364a 100644 --- a/src/event.rs +++ b/src/event.rs @@ -3,9 +3,10 @@ use crate::{ PaymentInfoStorage, PaymentStatus, Wallet, }; -use crate::logger::{log_error, log_given_level, log_info, log_internal, Logger}; +use crate::logger::{log_error, log_info, Logger}; use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator}; +use lightning::impl_writeable_tlv_based_enum; use lightning::ln::PaymentHash; use lightning::routing::gossip::NodeId; use lightning::util::errors::APIError; @@ -25,9 +26,9 @@ use std::time::Duration; /// The event queue will be persisted under this key. pub(crate) const EVENTS_PERSISTENCE_KEY: &str = "events"; -/// An event emitted by [`LdkLite`], which should be handled by the user. +/// An event emitted by [`Node`], which should be handled by the user. /// -/// [`LdkLite`]: [`crate::LdkLite`] +/// [`Node`]: [`crate::Node`] #[derive(Debug, Clone, PartialEq, Eq)] pub enum Event { /// A sent payment was successful. @@ -63,74 +64,26 @@ pub enum Event { }, } -// TODO: Figure out serialization more concretely - see issue #30 -impl Readable for Event { - fn read( - reader: &mut R, - ) -> Result { - match Readable::read(reader)? { - 0u8 => { - let payment_hash: PaymentHash = Readable::read(reader)?; - Ok(Self::PaymentSuccessful { payment_hash }) - } - 1u8 => { - let payment_hash: PaymentHash = Readable::read(reader)?; - Ok(Self::PaymentFailed { payment_hash }) - } - 2u8 => { - let payment_hash: PaymentHash = Readable::read(reader)?; - let amount_msat: u64 = Readable::read(reader)?; - Ok(Self::PaymentReceived { payment_hash, amount_msat }) - } - 3u8 => { - let channel_id: [u8; 32] = Readable::read(reader)?; - let user_channel_id: u128 = Readable::read(reader)?; - Ok(Self::ChannelReady { channel_id, user_channel_id }) - } - 4u8 => { - let channel_id: [u8; 32] = Readable::read(reader)?; - let user_channel_id: u128 = Readable::read(reader)?; - Ok(Self::ChannelClosed { channel_id, user_channel_id }) - } - _ => Err(lightning::ln::msgs::DecodeError::InvalidValue), - } - } -} - -impl Writeable for Event { - fn write(&self, writer: &mut W) -> Result<(), lightning::io::Error> { - match self { - Self::PaymentSuccessful { payment_hash } => { - 0u8.write(writer)?; - payment_hash.write(writer)?; - Ok(()) - } - Self::PaymentFailed { payment_hash } => { - 1u8.write(writer)?; - payment_hash.write(writer)?; - Ok(()) - } - Self::PaymentReceived { payment_hash, amount_msat } => { - 2u8.write(writer)?; - payment_hash.write(writer)?; - amount_msat.write(writer)?; - Ok(()) - } - Self::ChannelReady { channel_id, user_channel_id } => { - 3u8.write(writer)?; - channel_id.write(writer)?; - user_channel_id.write(writer)?; - Ok(()) - } - Self::ChannelClosed { channel_id, user_channel_id } => { - 4u8.write(writer)?; - channel_id.write(writer)?; - user_channel_id.write(writer)?; - Ok(()) - } - } - } -} +impl_writeable_tlv_based_enum!(Event, + (0, PaymentSuccessful) => { + (0, payment_hash, required), + }, + (1, PaymentFailed) => { + (0, payment_hash, required), + }, + (2, PaymentReceived) => { + (0, payment_hash, required), + (1, amount_msat, required), + }, + (3, ChannelReady) => { + (0, channel_id, required), + (1, user_channel_id, required), + }, + (4, ChannelClosed) => { + (0, channel_id, required), + (1, user_channel_id, required), + }; +); pub(crate) struct EventQueue where @@ -233,7 +186,7 @@ where K::Target: KVStorePersister, L::Target: Logger, { - wallet: Arc>, + wallet: Arc>, event_queue: Arc>, channel_manager: Arc, network_graph: Arc, @@ -251,7 +204,7 @@ where L::Target: Logger, { pub fn new( - wallet: Arc>, event_queue: Arc>, + wallet: Arc>, event_queue: Arc>, channel_manager: Arc, network_graph: Arc, keys_manager: Arc, inbound_payments: Arc, outbound_payments: Arc, tokio_runtime: Arc, @@ -324,7 +277,8 @@ where } } } - Err(_err) => { + Err(err) => { + log_error!(self.logger, "Failed to create funding transaction: {}", err); self.channel_manager .force_close_without_broadcasting_txn( &temporary_channel_id, @@ -400,6 +354,7 @@ where payment.status = PaymentStatus::Succeeded; payment.preimage = payment_preimage; payment.secret = payment_secret; + payment.amount_msat = Some(amount_msat); } hash_map::Entry::Vacant(e) => { e.insert(PaymentInfo { @@ -480,17 +435,19 @@ where let output_descriptors = &outputs.iter().collect::>(); let tx_feerate = self.wallet.get_est_sat_per_1000_weight(ConfirmationTarget::Normal); - let spending_tx = self - .keys_manager - .spend_spendable_outputs( - output_descriptors, - Vec::new(), - destination_address.script_pubkey(), - tx_feerate, - &Secp256k1::new(), - ) - .unwrap(); - self.wallet.broadcast_transaction(&spending_tx); + let res = self.keys_manager.spend_spendable_outputs( + output_descriptors, + Vec::new(), + destination_address.script_pubkey(), + tx_feerate, + &Secp256k1::new(), + ); + match res { + Ok(spending_tx) => self.wallet.broadcast_transaction(&spending_tx), + Err(err) => { + log_error!(self.logger, "Error spending outputs: {:?}", err); + } + } } LdkEvent::OpenChannelRequest { .. } => {} LdkEvent::PaymentForwarded { @@ -588,21 +545,29 @@ mod tests { #[test] fn event_queue_persistence() { - let test_persister = Arc::new(TestPersister::new()); - let event_queue = EventQueue::new(Arc::clone(&test_persister)); + let persister = Arc::new(TestPersister::new()); + let event_queue = EventQueue::new(Arc::clone(&persister)); let expected_event = Event::ChannelReady { channel_id: [23u8; 32], user_channel_id: 2323 }; event_queue.add_event(expected_event.clone()).unwrap(); - assert!(test_persister.get_and_clear_pending_persist()); + assert!(persister.get_and_clear_did_persist()); // Check we get the expected event and that it is returned until we mark it handled. for _ in 0..5 { assert_eq!(event_queue.next_event(), expected_event); - assert_eq!(false, test_persister.get_and_clear_pending_persist()); + assert_eq!(false, persister.get_and_clear_did_persist()); } + // Check we can read back what we persisted. + let persisted_bytes = persister.get_persisted_bytes(EVENTS_PERSISTENCE_KEY).unwrap(); + let deser_event_queue = + EventQueue::read(&mut &persisted_bytes[..], Arc::clone(&persister)).unwrap(); + assert_eq!(deser_event_queue.next_event(), expected_event); + assert!(!persister.get_and_clear_did_persist()); + // Check we persisted on `event_handled()` event_queue.event_handled().unwrap(); - assert!(test_persister.get_and_clear_pending_persist()); + + assert!(persister.get_and_clear_did_persist()); } } diff --git a/src/io_utils.rs b/src/io_utils.rs new file mode 100644 index 000000000..6453aac75 --- /dev/null +++ b/src/io_utils.rs @@ -0,0 +1,62 @@ +use crate::{Config, FilesystemLogger, NetworkGraph, Scorer, WALLET_KEYS_SEED_LEN}; + +use lightning::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters}; +use lightning::util::ser::ReadableArgs; + +use rand::{thread_rng, RngCore}; + +use std::fs; +use std::io::{BufReader, Write}; +use std::path::Path; +use std::sync::Arc; + +pub(crate) fn read_or_generate_seed_file(keys_seed_path: &str) -> [u8; WALLET_KEYS_SEED_LEN] { + if Path::new(&keys_seed_path).exists() { + let seed = fs::read(keys_seed_path).expect("Failed to read keys seed file"); + assert_eq!( + seed.len(), + WALLET_KEYS_SEED_LEN, + "Failed to read keys seed file: unexpected length" + ); + let mut key = [0; WALLET_KEYS_SEED_LEN]; + key.copy_from_slice(&seed); + key + } else { + let mut key = [0; WALLET_KEYS_SEED_LEN]; + thread_rng().fill_bytes(&mut key); + + let mut f = fs::File::create(keys_seed_path).expect("Failed to create keys seed file"); + 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 + } +} + +pub(crate) fn read_network_graph(config: &Config, logger: Arc) -> NetworkGraph { + let ldk_data_dir = format!("{}/ldk", config.storage_dir_path); + let network_graph_path = format!("{}/network_graph", ldk_data_dir); + + if let Ok(file) = fs::File::open(network_graph_path) { + if let Ok(graph) = NetworkGraph::read(&mut BufReader::new(file), Arc::clone(&logger)) { + return graph; + } + } + + NetworkGraph::new(config.network, logger) +} + +pub(crate) fn read_scorer( + config: &Config, network_graph: Arc, logger: Arc, +) -> Scorer { + let ldk_data_dir = format!("{}/ldk", config.storage_dir_path); + let scorer_path = format!("{}/scorer", ldk_data_dir); + + let params = ProbabilisticScoringParameters::default(); + if let Ok(file) = fs::File::open(scorer_path) { + let args = (params.clone(), Arc::clone(&network_graph), Arc::clone(&logger)); + if let Ok(scorer) = ProbabilisticScorer::read(&mut BufReader::new(file), args) { + return scorer; + } + } + ProbabilisticScorer::new(params, network_graph, logger) +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 000000000..b23fa912d --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,1242 @@ +// This file is Copyright its original authors, visible in version contror +// history. +// +// This file is licensed under the Apache License, Version 2.0 or the MIT license +// , at your option. +// You may not use this file except in accordance with one or both of these +// licenses. + +#![crate_name = "ldk_node"] + +//! A library providing a simplified API for the Lightning Dev Kit. While LDK itself provides a +//! highly configurable and adaptable interface, this API champions simplicity and ease of use over +//! configurability. To this end, it provides an opionated set of design choices and ready-to-go +//! default modules, while still enabling some configurability when dearly needed by the user: +//! - Chain data is accessed through an Esplora client. +//! - Wallet and channel states are persisted to disk. +//! - Gossip is retrieved over the P2P network. + +#![deny(missing_docs)] +#![deny(broken_intra_doc_links)] +#![deny(private_intra_doc_links)] +#![allow(bare_trait_objects)] +#![allow(ellipsis_inclusive_range_patterns)] +#![cfg_attr(docsrs, feature(doc_auto_cfg))] + +mod error; +mod event; +mod hex_utils; +mod io_utils; +mod logger; +mod peer_store; +#[cfg(test)] +mod tests; +mod types; +mod wallet; + +pub use bitcoin; +pub use lightning; +pub use lightning_invoice; + +pub use error::Error; +pub use event::Event; +use event::{EventHandler, EventQueue}; +use peer_store::{PeerInfo, PeerInfoStorage}; +use types::{ + ChainMonitor, ChannelManager, GossipSync, KeysManager, NetworkGraph, OnionMessenger, + PaymentInfoStorage, PeerManager, Scorer, +}; +pub use types::{PaymentInfo, PaymentStatus}; +use wallet::Wallet; + +use logger::{log_error, log_info, FilesystemLogger, Logger}; + +use lightning::chain::keysinterface::EntropySource; +use lightning::chain::{chainmonitor, BestBlock, Confirm, Watch}; +use lightning::ln::channelmanager; +use lightning::ln::channelmanager::{ + ChainParameters, ChannelDetails, ChannelManagerReadArgs, PaymentId, Retry, +}; +use lightning::ln::peer_handler::{IgnoringMessageHandler, MessageHandler}; +use lightning::ln::{PaymentHash, PaymentPreimage}; +use lightning::routing::gossip::P2PGossipSync; +use lightning::routing::utxo::UtxoLookup; + +use lightning::util::config::{ChannelHandshakeConfig, ChannelHandshakeLimits, UserConfig}; +use lightning::util::ser::ReadableArgs; + +use lightning_background_processor::BackgroundProcessor; +use lightning_background_processor::GossipSync as BPGossipSync; +use lightning_persister::FilesystemPersister; + +use lightning_transaction_sync::EsploraSyncClient; + +use lightning::routing::router::{DefaultRouter, PaymentParameters, RouteParameters}; +use lightning_invoice::{payment, Currency, Invoice}; + +use bdk::bitcoin::secp256k1::Secp256k1; +use bdk::blockchain::esplora::EsploraBlockchain; +use bdk::database::SqliteDatabase; +use bdk::template::Bip84; + +use bitcoin::hashes::sha256::Hash as Sha256; +use bitcoin::hashes::Hash; +use bitcoin::secp256k1::PublicKey; +use bitcoin::BlockHash; + +use rand::Rng; + +use std::collections::HashMap; +use std::convert::{TryFrom, TryInto}; +use std::default::Default; +use std::fs; +use std::net::SocketAddr; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, RwLock}; +use std::time::{Duration, Instant, SystemTime}; + +// The 'stop gap' parameter used by BDK's wallet sync. This seems to configure the threshold +// number of blocks after which BDK stops looking for scripts belonging to the wallet. +const BDK_CLIENT_STOP_GAP: usize = 20; + +// The number of concurrent requests made against the API provider. +const BDK_CLIENT_CONCURRENCY: u8 = 8; + +// The timeout after which we abandon retrying failed payments. +const LDK_PAYMENT_RETRY_TIMEOUT: Duration = Duration::from_secs(10); + +// The time in between peer reconnection attempts. +const PEER_RECONNECTION_INTERVAL: Duration = Duration::from_secs(10); + +// The length in bytes of our wallets' keys seed. +const WALLET_KEYS_SEED_LEN: usize = 64; + +#[derive(Debug, Clone)] +/// Represents the configuration of an [`Node`] instance. +pub struct Config { + /// The path where the underlying LDK and BDK persist their data. + pub storage_dir_path: String, + /// The URL of the utilized Esplora server. + pub esplora_server_url: String, + /// The used Bitcoin network. + pub network: bitcoin::Network, + /// The IP address and TCP port the node will listen on. + pub listening_address: Option, + /// The default CLTV expiry delta to be used for payments. + pub default_cltv_expiry_delta: u32, +} + +impl Default for Config { + fn default() -> Self { + Self { + storage_dir_path: "/tmp/ldk_node/".to_string(), + esplora_server_url: "http://localhost:3002".to_string(), + network: bitcoin::Network::Regtest, + listening_address: Some("0.0.0.0:9735".to_string()), + default_cltv_expiry_delta: 144, + } + } +} + +#[derive(Debug, Clone)] +enum WalletEntropySource { + SeedFile(String), + SeedBytes([u8; WALLET_KEYS_SEED_LEN]), +} + +/// A builder for an [`Node`] instance, allowing to set some configuration and module choices from +/// the getgo. +#[derive(Debug, Clone)] +pub struct Builder { + config: Config, + entropy_source: Option, +} + +impl Builder { + /// Creates a new builder instance with the default configuration. + pub fn new() -> Self { + let config = Config::default(); + let entropy_source = None; + Self { config, entropy_source } + } + + /// Creates a new builder instance from an [`Config`]. + pub fn from_config(config: Config) -> Self { + let entropy_source = None; + Self { config, entropy_source } + } + + /// Configures the [`Node`] instance to source its wallet entropy from a seed file on disk. + /// + /// If the given file does not exist a new random seed file will be generated and + /// stored at the given location. + pub fn set_entropy_seed_path(&mut self, seed_path: String) -> &mut Self { + self.entropy_source = Some(WalletEntropySource::SeedFile(seed_path)); + self + } + + /// Configures the [`Node`] instance to source its wallet entropy from the given seed bytes. + pub fn set_entropy_seed_bytes(&mut self, seed_bytes: [u8; WALLET_KEYS_SEED_LEN]) -> &mut Self { + self.entropy_source = Some(WalletEntropySource::SeedBytes(seed_bytes)); + self + } + + /// Sets the used storage directory path. + /// + /// Default: `/tmp/ldk_node/` + pub fn set_storage_dir_path(&mut self, storage_dir_path: String) -> &mut Self { + self.config.storage_dir_path = storage_dir_path; + self + } + + /// Sets the Esplora server URL. + /// + /// Default: `https://blockstream.info/api` + pub fn set_esplora_server_url(&mut self, esplora_server_url: String) -> &mut Self { + self.config.esplora_server_url = esplora_server_url; + self + } + + /// Sets the Bitcoin network used. + /// + /// Options: `mainnet`/`bitcoin`, `testnet`, `regtest`, `signet` + /// + /// Default: `testnet` + pub fn set_network(&mut self, network: &str) -> &mut Self { + self.config.network = match network { + "mainnet" => bitcoin::Network::Bitcoin, + "bitcoin" => bitcoin::Network::Bitcoin, + "testnet" => bitcoin::Network::Testnet, + "regtest" => bitcoin::Network::Regtest, + "signet" => bitcoin::Network::Signet, + _ => bitcoin::Network::Regtest, + }; + self + } + + /// Sets the IP address and TCP port on which [`Node`] will listen for incoming network connections. + /// + /// Format: `ADDR:PORT` + /// Default: `0.0.0.0:9735` + pub fn set_listening_address(&mut self, listening_address: String) -> &mut Self { + self.config.listening_address = Some(listening_address); + self + } + + /// Builds an [`Node`] instance according to the options previously configured. + pub fn build(&self) -> Node { + let config = Arc::new(self.config.clone()); + + let ldk_data_dir = format!("{}/ldk", config.storage_dir_path); + fs::create_dir_all(ldk_data_dir.clone()).expect("Failed to create LDK data directory"); + + let bdk_data_dir = format!("{}/bdk", config.storage_dir_path); + fs::create_dir_all(bdk_data_dir.clone()).expect("Failed to create BDK data directory"); + + // Initialize the Logger + let log_file_path = format!("{}/ldk_node.log", config.storage_dir_path); + let logger = Arc::new(FilesystemLogger::new(log_file_path)); + + // Initialize the on-chain wallet and chain access + let seed_bytes = if let Some(entropy_source) = &self.entropy_source { + // Use the configured entropy source, if the user set one. + match entropy_source { + WalletEntropySource::SeedBytes(bytes) => bytes.clone(), + WalletEntropySource::SeedFile(seed_path) => { + io_utils::read_or_generate_seed_file(seed_path) + } + } + } else { + // Default to read or generate from the default location generate a seed file. + let seed_path = format!("{}/keys_seed", config.storage_dir_path); + io_utils::read_or_generate_seed_file(&seed_path) + }; + + let xprv = bitcoin::util::bip32::ExtendedPrivKey::new_master(config.network, &seed_bytes) + .expect("Failed to read wallet master key"); + + let wallet_name = bdk::wallet::wallet_name_from_descriptor( + Bip84(xprv, bdk::KeychainKind::External), + Some(Bip84(xprv, bdk::KeychainKind::Internal)), + config.network, + &Secp256k1::new(), + ) + .expect("Failed to derive on-chain wallet name"); + + let database_path = format!("{}/{}.sqlite", bdk_data_dir, wallet_name); + let database = SqliteDatabase::new(database_path); + + let bdk_wallet = bdk::Wallet::new( + Bip84(xprv, bdk::KeychainKind::External), + Some(Bip84(xprv, bdk::KeychainKind::Internal)), + config.network, + database, + ) + .expect("Failed to setup on-chain wallet"); + + let tx_sync = Arc::new(EsploraSyncClient::new( + config.esplora_server_url.clone(), + Arc::clone(&logger), + )); + + let blockchain = + EsploraBlockchain::from_client(tx_sync.client().clone(), BDK_CLIENT_STOP_GAP) + .with_concurrency(BDK_CLIENT_CONCURRENCY); + + let wallet = Arc::new(Wallet::new(blockchain, bdk_wallet, Arc::clone(&logger))); + + // Initialize Persist + let persister = Arc::new(FilesystemPersister::new(ldk_data_dir.clone())); + + // Initialize the ChainMonitor + let chain_monitor: Arc = Arc::new(chainmonitor::ChainMonitor::new( + Some(Arc::clone(&tx_sync)), + Arc::clone(&wallet), + Arc::clone(&logger), + Arc::clone(&wallet), + Arc::clone(&persister), + )); + + // Initialize the KeysManager + let cur_time = SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .expect("System time error: Clock may have gone backwards"); + let ldk_seed_bytes: [u8; 32] = xprv.private_key.secret_bytes(); + let keys_manager = Arc::new(KeysManager::new( + &ldk_seed_bytes, + cur_time.as_secs(), + cur_time.subsec_nanos(), + Arc::clone(&wallet), + )); + + // Initialize the network graph, scorer, and router + let network_graph = + Arc::new(io_utils::read_network_graph(config.as_ref(), Arc::clone(&logger))); + let scorer = Arc::new(Mutex::new(io_utils::read_scorer( + config.as_ref(), + Arc::clone(&network_graph), + Arc::clone(&logger), + ))); + + let router = Arc::new(DefaultRouter::new( + Arc::clone(&network_graph), + Arc::clone(&logger), + keys_manager.get_secure_random_bytes(), + Arc::clone(&scorer), + )); + + // Read ChannelMonitor state from disk + let mut channel_monitors = persister + .read_channelmonitors(Arc::clone(&keys_manager), Arc::clone(&keys_manager)) + .expect("Failed to read channel monitors from disk"); + + // Initialize the ChannelManager + let mut user_config = UserConfig::default(); + user_config.channel_handshake_limits.force_announced_channel_preference = false; + let channel_manager = { + if let Ok(mut f) = fs::File::open(format!("{}/manager", ldk_data_dir)) { + let channel_monitor_references = + channel_monitors.iter_mut().map(|(_, chanmon)| chanmon).collect(); + let read_args = ChannelManagerReadArgs::new( + Arc::clone(&keys_manager), + Arc::clone(&keys_manager), + Arc::clone(&keys_manager), + Arc::clone(&wallet), + Arc::clone(&chain_monitor), + Arc::clone(&wallet), + Arc::clone(&router), + Arc::clone(&logger), + user_config, + channel_monitor_references, + ); + let (_hash, channel_manager) = + <(BlockHash, ChannelManager)>::read(&mut f, read_args) + .expect("Failed to read channel manager from disk"); + channel_manager + } else { + // We're starting a fresh node. + let genesis_block_hash = + bitcoin::blockdata::constants::genesis_block(config.network) + .header + .block_hash(); + + let chain_params = ChainParameters { + network: config.network, + best_block: BestBlock::new(genesis_block_hash, 0), + }; + channelmanager::ChannelManager::new( + Arc::clone(&wallet), + Arc::clone(&chain_monitor), + Arc::clone(&wallet), + Arc::clone(&router), + Arc::clone(&logger), + Arc::clone(&keys_manager), + Arc::clone(&keys_manager), + Arc::clone(&keys_manager), + user_config, + chain_params, + ) + } + }; + + let channel_manager = Arc::new(channel_manager); + + // Give ChannelMonitors to ChainMonitor + for (_blockhash, channel_monitor) in channel_monitors.into_iter() { + let funding_outpoint = channel_monitor.get_funding_txo().0; + chain_monitor.watch_channel(funding_outpoint, channel_monitor); + } + + // Initialize the P2PGossipSync + let gossip_sync = Arc::new(P2PGossipSync::new( + Arc::clone(&network_graph), + None::>, + Arc::clone(&logger), + )); + + // Initialize the PeerManager + let onion_messenger: Arc = Arc::new(OnionMessenger::new( + Arc::clone(&keys_manager), + Arc::clone(&keys_manager), + Arc::clone(&logger), + IgnoringMessageHandler {}, + )); + let ephemeral_bytes: [u8; 32] = keys_manager.get_secure_random_bytes(); + let lightning_msg_handler = MessageHandler { + chan_handler: Arc::clone(&channel_manager), + route_handler: Arc::clone(&gossip_sync), + onion_message_handler: onion_messenger, + }; + + let cur_time = SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .expect("System time error: Clock may have gone backwards"); + let peer_manager: Arc = Arc::new(PeerManager::new( + lightning_msg_handler, + cur_time.as_secs().try_into().expect("System time error"), + &ephemeral_bytes, + Arc::clone(&logger), + IgnoringMessageHandler {}, + Arc::clone(&keys_manager), + )); + + // Init payment info storage + // TODO: persist payment info to disk + let inbound_payments = Arc::new(Mutex::new(HashMap::new())); + let outbound_payments = Arc::new(Mutex::new(HashMap::new())); + + // Restore event handler from disk or create a new one. + let event_queue = if let Ok(mut f) = + fs::File::open(format!("{}/{}", ldk_data_dir, event::EVENTS_PERSISTENCE_KEY)) + { + Arc::new( + EventQueue::read(&mut f, Arc::clone(&persister)) + .expect("Failed to read event queue from disk."), + ) + } else { + Arc::new(EventQueue::new(Arc::clone(&persister))) + }; + + let peer_store = if let Ok(mut f) = + fs::File::open(format!("{}/{}", ldk_data_dir, peer_store::PEER_INFO_PERSISTENCE_KEY)) + { + Arc::new( + PeerInfoStorage::read(&mut f, Arc::clone(&persister)) + .expect("Failed to read peer information from disk."), + ) + } else { + Arc::new(PeerInfoStorage::new(Arc::clone(&persister))) + }; + + let running = RwLock::new(None); + + Node { + running, + config, + wallet, + tx_sync, + event_queue, + channel_manager, + chain_monitor, + peer_manager, + keys_manager, + network_graph, + gossip_sync, + persister, + logger, + scorer, + inbound_payments, + outbound_payments, + peer_store, + } + } +} + +/// Wraps all objects that need to be preserved during the run time of [`Node`]. Will be dropped +/// upon [`Node::stop()`]. +struct Runtime { + tokio_runtime: Arc, + _background_processor: BackgroundProcessor, + stop_networking: Arc, + stop_wallet_sync: Arc, +} + +/// The main interface object of the simplified API, wrapping the necessary LDK and BDK functionalities. +/// +/// Needs to be initialized and instantiated through [`Builder::build`]. +pub struct Node { + running: RwLock>, + config: Arc, + wallet: Arc>, + tx_sync: Arc>>, + event_queue: Arc>>, + channel_manager: Arc, + chain_monitor: Arc, + peer_manager: Arc, + keys_manager: Arc, + network_graph: Arc, + gossip_sync: Arc, + persister: Arc, + logger: Arc, + scorer: Arc>, + inbound_payments: Arc, + outbound_payments: Arc, + peer_store: Arc>, +} + +impl Node { + /// Starts the necessary background tasks, such as handling events coming from user input, + /// LDK/BDK, and the peer-to-peer network. + /// + /// After this returns, the [`Node`] instance can be controlled via the provided API methods in + /// a thread-safe manner. + pub fn start(&self) -> Result<(), Error> { + // Acquire a run lock and hold it until we're setup. + let mut run_lock = self.running.write().unwrap(); + if run_lock.is_some() { + // We're already running. + return Err(Error::AlreadyRunning); + } + + let runtime = self.setup_runtime()?; + *run_lock = Some(runtime); + Ok(()) + } + + /// Disconnects all peers, stops all running background tasks, and shuts down [`Node`]. + /// + /// After this returns most API methods will return [`Error::NotRunning`]. + pub fn stop(&self) -> Result<(), Error> { + let mut run_lock = self.running.write().unwrap(); + if run_lock.is_none() { + return Err(Error::NotRunning); + } + + let runtime = run_lock.as_ref().unwrap(); + + // Stop wallet sync + runtime.stop_wallet_sync.store(true, Ordering::Release); + + // Stop networking + runtime.stop_networking.store(true, Ordering::Release); + self.peer_manager.disconnect_all_peers(); + + // Drop the held runtimes. + self.wallet.drop_runtime(); + + // Drop the runtime, which stops the background processor and any possibly remaining tokio threads. + *run_lock = None; + Ok(()) + } + + fn setup_runtime(&self) -> Result { + let tokio_runtime = + Arc::new(tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap()); + + self.wallet.set_runtime(Arc::clone(&tokio_runtime)); + + let event_handler = Arc::new(EventHandler::new( + Arc::clone(&self.wallet), + Arc::clone(&self.event_queue), + Arc::clone(&self.channel_manager), + Arc::clone(&self.network_graph), + Arc::clone(&self.keys_manager), + Arc::clone(&self.inbound_payments), + Arc::clone(&self.outbound_payments), + Arc::clone(&tokio_runtime), + Arc::clone(&self.logger), + Arc::clone(&self.config), + )); + + // Setup wallet sync + let wallet = Arc::clone(&self.wallet); + let tx_sync = Arc::clone(&self.tx_sync); + let sync_cman = Arc::clone(&self.channel_manager); + let sync_cmon = Arc::clone(&self.chain_monitor); + let sync_logger = Arc::clone(&self.logger); + let stop_wallet_sync = Arc::new(AtomicBool::new(false)); + let stop_sync = Arc::clone(&stop_wallet_sync); + + std::thread::spawn(move || { + tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on( + async move { + loop { + if stop_sync.load(Ordering::Acquire) { + return; + } + let now = Instant::now(); + match wallet.sync().await { + Ok(()) => log_info!( + sync_logger, + "Background sync of on-chain wallet finished in {}ms.", + now.elapsed().as_millis() + ), + Err(err) => { + log_error!( + sync_logger, + "Background sync of on-chain wallet failed: {}", + err + ) + } + } + tokio::time::sleep(Duration::from_secs(20)).await; + } + }, + ); + }); + + let sync_logger = Arc::clone(&self.logger); + let stop_sync = Arc::clone(&stop_wallet_sync); + tokio_runtime.spawn(async move { + loop { + if stop_sync.load(Ordering::Acquire) { + return; + } + let now = Instant::now(); + let confirmables = vec![ + &*sync_cman as &(dyn Confirm + Sync + Send), + &*sync_cmon as &(dyn Confirm + Sync + Send), + ]; + match tx_sync.sync(confirmables).await { + Ok(()) => log_info!( + sync_logger, + "Background sync of Lightning wallet finished in {}ms.", + now.elapsed().as_millis() + ), + Err(e) => { + log_error!(sync_logger, "Background sync of Lightning wallet failed: {}", e) + } + } + tokio::time::sleep(Duration::from_secs(5)).await; + } + }); + + let stop_networking = Arc::new(AtomicBool::new(false)); + if let Some(listening_address) = &self.config.listening_address { + // Setup networking + let peer_manager_connection_handler = Arc::clone(&self.peer_manager); + let stop_listen = Arc::clone(&stop_networking); + let listening_address = listening_address.clone(); + + tokio_runtime.spawn(async move { + let listener = + tokio::net::TcpListener::bind(listening_address).await.expect( + "Failed to bind to listen address/port - is something else already listening on it?", + ); + loop { + if stop_listen.load(Ordering::Acquire) { + return; + } + let peer_mgr = Arc::clone(&peer_manager_connection_handler); + let tcp_stream = listener.accept().await.unwrap().0; + tokio::spawn(async move { + lightning_net_tokio::setup_inbound( + Arc::clone(&peer_mgr), + tcp_stream.into_std().unwrap(), + ) + .await; + }); + } + }); + } + + // Regularly reconnect to channel peers. + let connect_cm = Arc::clone(&self.channel_manager); + let connect_pm = Arc::clone(&self.peer_manager); + let connect_logger = Arc::clone(&self.logger); + let connect_peer_store = Arc::clone(&self.peer_store); + let stop_connect = Arc::clone(&stop_networking); + tokio_runtime.spawn(async move { + let mut interval = tokio::time::interval(PEER_RECONNECTION_INTERVAL); + loop { + if stop_connect.load(Ordering::Acquire) { + return; + } + let pm_peers = connect_pm + .get_peer_node_ids() + .iter() + .map(|(peer, _addr)| *peer) + .collect::>(); + for node_id in connect_cm + .list_channels() + .iter() + .map(|chan| chan.counterparty.node_id) + .filter(|id| !pm_peers.contains(id)) + { + if let Some(peer_info) = connect_peer_store.get_peer(&node_id) { + let _ = do_connect_peer( + peer_info.pubkey, + peer_info.address, + Arc::clone(&connect_pm), + Arc::clone(&connect_logger), + ) + .await; + } + } + interval.tick().await; + } + }); + + // Setup background processing + let _background_processor = BackgroundProcessor::start( + Arc::clone(&self.persister), + Arc::clone(&event_handler), + Arc::clone(&self.chain_monitor), + Arc::clone(&self.channel_manager), + BPGossipSync::p2p(Arc::clone(&self.gossip_sync)), + Arc::clone(&self.peer_manager), + Arc::clone(&self.logger), + Some(Arc::clone(&self.scorer)), + ); + + // TODO: frequently check back on background_processor if there was an error + Ok(Runtime { tokio_runtime, _background_processor, stop_networking, stop_wallet_sync }) + } + + /// Blocks until the next event is available. + /// + /// Note: this will always return the same event until handling is confirmed via [`Node::event_handled`]. + pub fn next_event(&self) -> Event { + self.event_queue.next_event() + } + + /// Confirm the last retrieved event handled. + pub fn event_handled(&self) { + self.event_queue.event_handled().unwrap(); + } + + /// Returns our own node id + pub fn node_id(&self) -> PublicKey { + self.channel_manager.get_our_node_id() + } + + /// Returns our own listening address and port. + pub fn listening_address(&self) -> Option { + self.config.listening_address.clone() + } + + /// Retrieve a new on-chain/funding address. + pub fn new_funding_address(&self) -> Result { + let funding_address = self.wallet.get_new_address()?; + log_info!(self.logger, "Generated new funding address: {}", funding_address); + Ok(funding_address) + } + + /// Retrieve the current on-chain balance. + pub fn on_chain_balance(&self) -> Result { + self.wallet.get_balance() + } + + /// Retrieve a list of known channels. + pub fn list_channels(&self) -> Vec { + self.channel_manager.list_channels() + } + + /// Connect to a node and open a new channel. Disconnects and re-connects are handled automatically + /// + /// Returns a temporary channel id + pub fn connect_open_channel( + &self, node_pubkey_and_address: &str, channel_amount_sats: u64, announce_channel: bool, + ) -> Result<(), Error> { + let runtime_lock = self.running.read().unwrap(); + if runtime_lock.is_none() { + return Err(Error::NotRunning); + } + + let runtime = runtime_lock.as_ref().unwrap(); + + let cur_balance = self.wallet.get_balance()?; + if cur_balance.get_spendable() < channel_amount_sats { + log_error!(self.logger, "Unable to create channel due to insufficient funds."); + return Err(Error::InsufficientFunds); + } + + let peer_info = PeerInfo::try_from(node_pubkey_and_address.to_string())?; + + let con_peer_pubkey = peer_info.pubkey.clone(); + let con_peer_addr = peer_info.address.clone(); + let con_success = Arc::new(AtomicBool::new(false)); + let con_success_cloned = Arc::clone(&con_success); + let con_logger = Arc::clone(&self.logger); + let con_pm = Arc::clone(&self.peer_manager); + + tokio::task::block_in_place(move || { + runtime.tokio_runtime.block_on(async move { + let res = + connect_peer_if_necessary(con_peer_pubkey, con_peer_addr, con_pm, con_logger) + .await; + con_success_cloned.store(res.is_ok(), Ordering::Release); + }) + }); + + if !con_success.load(Ordering::Acquire) { + return Err(Error::ConnectionFailed); + } + + let user_config = UserConfig { + channel_handshake_limits: ChannelHandshakeLimits { + // lnd's max to_self_delay is 2016, so we want to be compatible. + their_to_self_delay: 2016, + ..Default::default() + }, + channel_handshake_config: ChannelHandshakeConfig { + announced_channel: announce_channel, + ..Default::default() + }, + ..Default::default() + }; + + let user_channel_id: u128 = rand::thread_rng().gen::(); + + match self.channel_manager.create_channel( + peer_info.pubkey, + channel_amount_sats, + 0, + user_channel_id, + Some(user_config), + ) { + Ok(_) => { + self.peer_store.add_peer(peer_info.clone())?; + log_info!( + self.logger, + "Initiated channel creation with peer {}. ", + peer_info.pubkey + ); + Ok(()) + } + Err(e) => { + log_error!(self.logger, "Failed to initiate channel creation: {:?}", e); + Err(Error::ChannelCreationFailed) + } + } + } + + /// Sync the LDK and BDK wallets with the current chain state. + /// + /// Note that the wallets will be also synced regularly in the background. + pub fn sync_wallets(&self) -> Result<(), Error> { + let runtime_lock = self.running.read().unwrap(); + if runtime_lock.is_none() { + return Err(Error::NotRunning); + } + let wallet = Arc::clone(&self.wallet); + let tx_sync = Arc::clone(&self.tx_sync); + let sync_cman = Arc::clone(&self.channel_manager); + let sync_cmon = Arc::clone(&self.chain_monitor); + let sync_logger = Arc::clone(&self.logger); + let confirmables = vec![ + &*sync_cman as &(dyn Confirm + Sync + Send), + &*sync_cmon as &(dyn Confirm + Sync + Send), + ]; + + let runtime = runtime_lock.as_ref().unwrap(); + tokio::task::block_in_place(move || { + tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on( + async move { + let now = Instant::now(); + match wallet.sync().await { + Ok(()) => { + log_info!( + sync_logger, + "Sync of on-chain wallet finished in {}ms.", + now.elapsed().as_millis() + ); + Ok(()) + } + Err(e) => { + log_error!(sync_logger, "Sync of on-chain wallet failed: {}", e); + Err(e) + } + } + }, + ) + })?; + + let sync_logger = Arc::clone(&self.logger); + tokio::task::block_in_place(move || { + runtime.tokio_runtime.block_on(async move { + let now = Instant::now(); + match tx_sync.sync(confirmables).await { + Ok(()) => { + log_info!( + sync_logger, + "Sync of Lightning wallet finished in {}ms.", + now.elapsed().as_millis() + ); + Ok(()) + } + Err(e) => { + log_error!(sync_logger, "Sync of Lightning wallet failed: {}", e); + Err(e) + } + } + }) + })?; + + Ok(()) + } + + /// Close a previously opened channel. + pub fn close_channel( + &self, channel_id: &[u8; 32], counterparty_node_id: &PublicKey, + ) -> Result<(), Error> { + self.peer_store.remove_peer(counterparty_node_id)?; + match self.channel_manager.close_channel(channel_id, counterparty_node_id) { + Ok(_) => Ok(()), + Err(_) => Err(Error::ChannelClosingFailed), + } + } + + /// Send a payement given an invoice. + pub fn send_payment(&self, invoice: Invoice) -> Result { + if self.running.read().unwrap().is_none() { + return Err(Error::NotRunning); + } + + let mut outbound_payments_lock = self.outbound_payments.lock().unwrap(); + + let payment_hash = PaymentHash((*invoice.payment_hash()).into_inner()); + let payment_secret = Some(*invoice.payment_secret()); + + match lightning_invoice::payment::pay_invoice( + &invoice, + Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT), + self.channel_manager.as_ref(), + ) { + Ok(_payment_id) => { + let payee_pubkey = invoice.recover_payee_pub_key(); + let amt_msat = invoice.amount_milli_satoshis().unwrap(); + log_info!(self.logger, "Initiated sending {}msat to {}", amt_msat, payee_pubkey); + + outbound_payments_lock.insert( + payment_hash, + PaymentInfo { + preimage: None, + secret: payment_secret, + status: PaymentStatus::Pending, + amount_msat: invoice.amount_milli_satoshis(), + }, + ); + + Ok(payment_hash) + } + Err(payment::PaymentError::Invoice(e)) => { + log_error!(self.logger, "Failed to send payment due to invalid invoice: {}", e); + Err(Error::InvalidInvoice) + } + Err(payment::PaymentError::Sending(e)) => { + log_error!(self.logger, "Failed to send payment: {:?}", e); + + outbound_payments_lock.insert( + payment_hash, + PaymentInfo { + preimage: None, + secret: payment_secret, + status: PaymentStatus::Failed, + amount_msat: invoice.amount_milli_satoshis(), + }, + ); + Err(Error::PaymentFailed) + } + } + } + + /// Send a payment given an invoice and an amount in millisatoshi. + /// + /// This will fail if the amount given is less than the value required by the given invoice. + /// + /// This can be used to pay a so-called "zero-amount" invoice, i.e., an invoice that leaves the + /// amount paid to be determined by the user. + pub fn send_payment_using_amount( + &self, invoice: Invoice, amount_msat: u64, + ) -> Result { + if self.running.read().unwrap().is_none() { + return Err(Error::NotRunning); + } + + let mut outbound_payments_lock = self.outbound_payments.lock().unwrap(); + + if let Some(invoice_amount_msat) = invoice.amount_milli_satoshis() { + if amount_msat < invoice_amount_msat { + log_error!( + self.logger, + "Failed to pay as the given amount needs to be at least the invoice amount: required {}msat, gave {}msat.", invoice_amount_msat, amount_msat); + return Err(Error::InvalidAmount); + } + } + + let payment_id = PaymentId(invoice.payment_hash().into_inner()); + let payment_hash = PaymentHash((*invoice.payment_hash()).into_inner()); + let payment_secret = Some(*invoice.payment_secret()); + let expiry_time = invoice.duration_since_epoch().saturating_add(invoice.expiry_time()); + let mut payment_params = PaymentParameters::from_node_id( + invoice.recover_payee_pub_key(), + invoice.min_final_cltv_expiry_delta() as u32, + ) + .with_expiry_time(expiry_time.as_secs()) + .with_route_hints(invoice.route_hints()); + if let Some(features) = invoice.features() { + payment_params = payment_params.with_features(features.clone()); + } + let route_params = RouteParameters { payment_params, final_value_msat: amount_msat }; + + let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT); + + match self + .channel_manager + .send_payment_with_retry( + payment_hash, + &payment_secret, + payment_id, + route_params, + retry_strategy, + ) + .map_err(payment::PaymentError::Sending) + { + Ok(_payment_id) => { + let payee_pubkey = invoice.recover_payee_pub_key(); + log_info!( + self.logger, + "Initiated sending {} msat to {}", + amount_msat, + payee_pubkey + ); + + outbound_payments_lock.insert( + payment_hash, + PaymentInfo { + preimage: None, + secret: payment_secret, + status: PaymentStatus::Pending, + amount_msat: Some(amount_msat), + }, + ); + + Ok(payment_hash) + } + Err(payment::PaymentError::Invoice(e)) => { + log_error!(self.logger, "Failed to send payment due to invalid invoice: {}", e); + Err(Error::InvalidInvoice) + } + Err(payment::PaymentError::Sending(e)) => { + log_error!(self.logger, "Failed to send payment: {:?}", e); + + outbound_payments_lock.insert( + payment_hash, + PaymentInfo { + preimage: None, + secret: payment_secret, + status: PaymentStatus::Failed, + amount_msat: Some(amount_msat), + }, + ); + Err(Error::PaymentFailed) + } + } + } + + /// Send a spontaneous, aka. "keysend", payment + pub fn send_spontaneous_payment( + &self, amount_msat: u64, node_id: &str, + ) -> Result { + if self.running.read().unwrap().is_none() { + return Err(Error::NotRunning); + } + + let mut outbound_payments_lock = self.outbound_payments.lock().unwrap(); + + let pubkey = hex_utils::to_compressed_pubkey(node_id).ok_or(Error::PeerInfoParseFailed)?; + + let payment_preimage = PaymentPreimage(self.keys_manager.get_secure_random_bytes()); + let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()); + + let route_params = RouteParameters { + payment_params: PaymentParameters::from_node_id( + pubkey, + self.config.default_cltv_expiry_delta, + ), + final_value_msat: amount_msat, + }; + + match self.channel_manager.send_spontaneous_payment_with_retry( + Some(payment_preimage), + PaymentId(payment_hash.0), + route_params, + Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT), + ) { + Ok(_payment_id) => { + log_info!(self.logger, "Initiated sending {}msat to {}.", amount_msat, node_id); + outbound_payments_lock.insert( + payment_hash, + PaymentInfo { + preimage: None, + secret: None, + status: PaymentStatus::Pending, + amount_msat: Some(amount_msat), + }, + ); + Ok(payment_hash) + } + Err(e) => { + log_error!(self.logger, "Failed to send payment: {:?}", e); + outbound_payments_lock.insert( + payment_hash, + PaymentInfo { + preimage: None, + secret: None, + status: PaymentStatus::Failed, + amount_msat: Some(amount_msat), + }, + ); + Err(Error::PaymentFailed) + } + } + } + + /// Returns a payable invoice that can be used to request and receive a payment of the amount + /// given. + pub fn receive_payment( + &self, amount_msat: u64, description: &str, expiry_secs: u32, + ) -> Result { + self.receive_payment_inner(Some(amount_msat), description, expiry_secs) + } + + /// Returns a payable invoice that can be used to request and receive a payment for which the + /// amount is to be determined by the user, also known as a "zero-amount" invoice. + pub fn receive_variable_amount_payment( + &self, description: &str, expiry_secs: u32, + ) -> Result { + self.receive_payment_inner(None, description, expiry_secs) + } + + fn receive_payment_inner( + &self, amount_msat: Option, description: &str, expiry_secs: u32, + ) -> Result { + let mut inbound_payments_lock = self.inbound_payments.lock().unwrap(); + + let currency = match self.config.network { + bitcoin::Network::Bitcoin => Currency::Bitcoin, + bitcoin::Network::Testnet => Currency::BitcoinTestnet, + bitcoin::Network::Regtest => Currency::Regtest, + bitcoin::Network::Signet => Currency::Signet, + }; + let keys_manager = Arc::clone(&self.keys_manager); + let invoice = match lightning_invoice::utils::create_invoice_from_channelmanager( + &self.channel_manager, + keys_manager, + Arc::clone(&self.logger), + currency, + amount_msat, + description.to_string(), + expiry_secs, + None, + ) { + Ok(inv) => { + log_info!(self.logger, "Invoice created: {}", inv); + inv + } + Err(e) => { + log_error!(self.logger, "Failed to create invoice: {}", e); + return Err(Error::InvoiceCreationFailed); + } + }; + + let payment_hash = PaymentHash((*invoice.payment_hash()).into_inner()); + inbound_payments_lock.insert( + payment_hash, + PaymentInfo { + preimage: None, + secret: Some(*invoice.payment_secret()), + status: PaymentStatus::Pending, + amount_msat, + }, + ); + Ok(invoice) + } + + /// Query for information about the status of a specific payment. + pub fn payment_info(&self, payment_hash: &[u8; 32]) -> Option { + let payment_hash = PaymentHash(*payment_hash); + + { + let outbound_payments_lock = self.outbound_payments.lock().unwrap(); + if let Some(payment_info) = outbound_payments_lock.get(&payment_hash) { + return Some((*payment_info).clone()); + } + } + + { + let inbound_payments_lock = self.inbound_payments.lock().unwrap(); + if let Some(payment_info) = inbound_payments_lock.get(&payment_hash) { + return Some((*payment_info).clone()); + } + } + + None + } +} + +async fn connect_peer_if_necessary( + pubkey: PublicKey, peer_addr: SocketAddr, peer_manager: Arc, + logger: Arc, +) -> Result<(), Error> { + for (node_pubkey, _addr) in peer_manager.get_peer_node_ids() { + if node_pubkey == pubkey { + return Ok(()); + } + } + + do_connect_peer(pubkey, peer_addr, peer_manager, logger).await +} + +async fn do_connect_peer( + pubkey: PublicKey, peer_addr: SocketAddr, peer_manager: Arc, + logger: Arc, +) -> Result<(), Error> { + log_info!(logger, "connecting to peer: {}@{}", pubkey, peer_addr); + match lightning_net_tokio::connect_outbound(Arc::clone(&peer_manager), pubkey, peer_addr).await + { + Some(connection_closed_future) => { + let mut connection_closed_future = Box::pin(connection_closed_future); + loop { + match futures::poll!(&mut connection_closed_future) { + std::task::Poll::Ready(_) => { + log_info!(logger, "peer connection closed: {}@{}", pubkey, peer_addr); + return Err(Error::ConnectionFailed); + } + std::task::Poll::Pending => {} + } + // Avoid blocking the tokio context by sleeping a bit + match peer_manager.get_peer_node_ids().iter().find(|(id, _addr)| *id == pubkey) { + Some(_) => return Ok(()), + None => tokio::time::sleep(Duration::from_millis(10)).await, + } + } + } + None => { + log_error!(logger, "failed to connect to peer: {}@{}", pubkey, peer_addr); + Err(Error::ConnectionFailed) + } + } +} diff --git a/src/logger.rs b/src/logger.rs index 317f294b4..6ae4cc4bd 100644 --- a/src/logger.rs +++ b/src/logger.rs @@ -1,6 +1,7 @@ pub(crate) use lightning::util::logger::Logger; use lightning::util::logger::Record; use lightning::util::ser::Writer; +pub(crate) use lightning::{log_error, log_info, log_trace}; use chrono::Utc; @@ -39,74 +40,3 @@ impl Logger for FilesystemLogger { .unwrap(); } } - -macro_rules! log_internal { - ($logger: expr, $lvl:expr, $($arg:tt)+) => ( - $logger.log(&lightning::util::logger::Record::new($lvl, format_args!($($arg)+), module_path!(), file!(), line!())) - ); -} -pub(crate) use log_internal; - -macro_rules! log_given_level { - ($logger: expr, $lvl:expr, $($arg:tt)+) => ( - match $lvl { - #[cfg(not(any(feature = "max_level_off")))] - lightning::util::logger::Level::Error => log_internal!($logger, $lvl, $($arg)*), - #[cfg(not(any(feature = "max_level_off", feature = "max_level_error")))] - lightning::util::logger::Level::Warn => log_internal!($logger, $lvl, $($arg)*), - #[cfg(not(any(feature = "max_level_off", feature = "max_level_error", feature = "max_level_warn")))] - lightning::util::logger::Level::Info => log_internal!($logger, $lvl, $($arg)*), - #[cfg(not(any(feature = "max_level_off", feature = "max_level_error", feature = "max_level_warn", feature = "max_level_info")))] - lightning::util::logger::Level::Debug => log_internal!($logger, $lvl, $($arg)*), - #[cfg(not(any(feature = "max_level_off", feature = "max_level_error", feature = "max_level_warn", feature = "max_level_info", feature = "max_level_debug")))] - lightning::util::logger::Level::Trace => log_internal!($logger, $lvl, $($arg)*), - #[cfg(not(any(feature = "max_level_off", feature = "max_level_error", feature = "max_level_warn", feature = "max_level_info", feature = "max_level_debug", feature = "max_level_trace")))] - lightning::util::logger::Level::Gossip => log_internal!($logger, $lvl, $($arg)*), - - #[cfg(any(feature = "max_level_off", feature = "max_level_error", feature = "max_level_warn", feature = "max_level_info", feature = "max_level_debug", feature = "max_level_trace"))] - _ => { - // The level is disabled at compile-time - }, - } - ); -} -pub(crate) use log_given_level; - -#[allow(unused_macros)] -macro_rules! log_error { - ($logger: expr, $($arg:tt)*) => ( - log_given_level!($logger, lightning::util::logger::Level::Error, $($arg)*) - ) -} -pub(crate) use log_error; - -#[allow(unused_macros)] -macro_rules! log_warn { - ($logger: expr, $($arg:tt)*) => ( - log_given_level!($logger, lightning::util::logger::Level::Warn, $($arg)*) - ) -} -pub(crate) use log_warn; - -#[allow(unused_macros)] -macro_rules! log_info { - ($logger: expr, $($arg:tt)*) => ( - log_given_level!($logger, lightning::util::logger::Level::Info, $($arg)*) - ) -} -pub(crate) use log_info; - -#[allow(unused_macros)] -macro_rules! log_debug { - ($logger: expr, $($arg:tt)*) => ( - log_given_level!($logger, lightning::util::logger::Level::Debug, $($arg)*) - ) -} - -#[allow(unused_macros)] -macro_rules! log_trace { - ($logger: expr, $($arg:tt)*) => ( - log_given_level!($logger, lightning::util::logger::Level::Trace, $($arg)*) - ) -} -pub(crate) use log_trace; diff --git a/src/peer_store.rs b/src/peer_store.rs new file mode 100644 index 000000000..6147dee81 --- /dev/null +++ b/src/peer_store.rs @@ -0,0 +1,243 @@ +use crate::hex_utils; +use crate::Error; + +use lightning::util::persist::KVStorePersister; +use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer}; + +use bitcoin::secp256k1::PublicKey; + +use std::collections::HashMap; +use std::convert::TryFrom; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs}; +use std::sync::{Arc, RwLock}; + +/// The peer information will be persisted under this key. +pub(crate) const PEER_INFO_PERSISTENCE_KEY: &str = "peers"; + +pub(crate) struct PeerInfoStorage { + peers: RwLock>, + persister: Arc, +} + +impl PeerInfoStorage { + pub(crate) fn new(persister: Arc) -> Self { + let peers = RwLock::new(HashMap::new()); + Self { peers, persister } + } + + pub(crate) fn add_peer(&self, peer_info: PeerInfo) -> Result<(), Error> { + let mut locked_peers = self.peers.write().unwrap(); + + locked_peers.insert(peer_info.pubkey, peer_info); + + self.persister + .persist(PEER_INFO_PERSISTENCE_KEY, &PeerInfoStorageSerWrapper(&*locked_peers)) + .map_err(|_| Error::PersistenceFailed)?; + + Ok(()) + } + + pub(crate) fn remove_peer(&self, peer_pubkey: &PublicKey) -> Result<(), Error> { + let mut locked_peers = self.peers.write().unwrap(); + + locked_peers.remove(peer_pubkey); + + self.persister + .persist(PEER_INFO_PERSISTENCE_KEY, &PeerInfoStorageSerWrapper(&*locked_peers)) + .map_err(|_| Error::PersistenceFailed)?; + + Ok(()) + } + + pub(crate) fn list_peers(&self) -> Vec { + self.peers.read().unwrap().values().cloned().collect() + } + + pub(crate) fn get_peer(&self, peer_pubkey: &PublicKey) -> Option { + self.peers.read().unwrap().get(peer_pubkey).cloned() + } +} + +impl ReadableArgs> for PeerInfoStorage { + #[inline] + fn read( + reader: &mut R, persister: Arc, + ) -> Result { + let read_peers: PeerInfoStorageDeserWrapper = Readable::read(reader)?; + let peers: RwLock> = RwLock::new(read_peers.0); + Ok(Self { peers, persister }) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct PeerInfoStorageDeserWrapper(HashMap); + +impl Readable for PeerInfoStorageDeserWrapper { + fn read( + reader: &mut R, + ) -> Result { + let len: u16 = Readable::read(reader)?; + let mut peers = HashMap::with_capacity(len as usize); + for _ in 0..len { + let k: PublicKey = Readable::read(reader)?; + let v: PeerInfo = Readable::read(reader)?; + peers.insert(k, v); + } + Ok(Self(peers)) + } +} + +pub(crate) struct PeerInfoStorageSerWrapper<'a>(&'a HashMap); + +impl Writeable for PeerInfoStorageSerWrapper<'_> { + fn write(&self, writer: &mut W) -> Result<(), lightning::io::Error> { + (self.0.len() as u16).write(writer)?; + for (k, v) in self.0.iter() { + k.write(writer)?; + v.write(writer)?; + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct PeerInfo { + pub pubkey: PublicKey, + pub address: SocketAddr, +} + +impl Readable for PeerInfo { + fn read( + reader: &mut R, + ) -> Result { + let pubkey = Readable::read(reader)?; + + let ip_type: u8 = Readable::read(reader)?; + + let ip_addr = if ip_type == 0 { + let v4bytes: u32 = Readable::read(reader)?; + let v4addr = Ipv4Addr::from(v4bytes); + IpAddr::from(v4addr) + } else { + let v6bytes: u128 = Readable::read(reader)?; + let v6addr = Ipv6Addr::from(v6bytes); + IpAddr::from(v6addr) + }; + + let port: u16 = Readable::read(reader)?; + + let address = SocketAddr::new(ip_addr, port); + + Ok(PeerInfo { pubkey, address }) + } +} + +impl Writeable for PeerInfo { + fn write(&self, writer: &mut W) -> Result<(), lightning::io::Error> { + self.pubkey.write(writer)?; + + match self.address.ip() { + IpAddr::V4(v4addr) => { + 0u8.write(writer)?; + u32::from(v4addr).write(writer)?; + } + IpAddr::V6(v6addr) => { + 1u8.write(writer)?; + u128::from(v6addr).write(writer)?; + } + } + + self.address.port().write(writer)?; + + Ok(()) + } +} + +impl TryFrom for PeerInfo { + type Error = Error; + + fn try_from(peer_pubkey_and_ip_addr: String) -> Result { + if let Some((pubkey_str, peer_str)) = peer_pubkey_and_ip_addr.split_once('@') { + if let Some(pubkey) = hex_utils::to_compressed_pubkey(pubkey_str) { + if let Some(peer_addr) = + peer_str.to_socket_addrs().ok().and_then(|mut r| r.next()).map(|pa| pa) + { + return Ok(PeerInfo { pubkey, address: peer_addr }); + } + } + } + Err(Error::PeerInfoParseFailed) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::test_utils::TestPersister; + use proptest::prelude::*; + use std::str::FromStr; + + #[test] + fn peer_info_persistence() { + let persister = Arc::new(TestPersister::new()); + let peer_store = PeerInfoStorage::new(Arc::clone(&persister)); + + let pubkey = PublicKey::from_str( + "0276607124ebe6a6c9338517b6f485825b27c2dcc0b9fc2aa6a4c0df91194e5993", + ) + .unwrap(); + let address: SocketAddr = "127.0.0.1:9738".parse().unwrap(); + let expected_peer_info = PeerInfo { pubkey, address }; + peer_store.add_peer(expected_peer_info.clone()).unwrap(); + assert!(persister.get_and_clear_did_persist()); + + // Check we can read back what we persisted. + let persisted_bytes = persister.get_persisted_bytes(PEER_INFO_PERSISTENCE_KEY).unwrap(); + let deser_peer_store = + PeerInfoStorage::read(&mut &persisted_bytes[..], Arc::clone(&persister)).unwrap(); + + let peers = deser_peer_store.list_peers(); + assert_eq!(peers.len(), 1); + assert_eq!(peers[0], expected_peer_info); + assert_eq!(deser_peer_store.get_peer(&pubkey), Some(expected_peer_info)); + assert!(!persister.get_and_clear_did_persist()); + } + + #[test] + fn peer_info_parsing() { + let valid_peer_info_str = + "0276607124ebe6a6c9338517b6f485825b27c2dcc0b9fc2aa6a4c0df91194e5993@127.0.0.1:9738" + .to_string(); + + let pubkey = PublicKey::from_str( + "0276607124ebe6a6c9338517b6f485825b27c2dcc0b9fc2aa6a4c0df91194e5993", + ) + .unwrap(); + let address: SocketAddr = "127.0.0.1:9738".parse().unwrap(); + let expected_peer_info = PeerInfo { pubkey, address }; + + assert_eq!(Ok(expected_peer_info), PeerInfo::try_from(valid_peer_info_str)); + + let invalid_peer_info_str1 = + "02-76607124-ebe6a6c9338517b6f485825b27c2dcc0b9fc2aa6a4c0df91194e5993@127.0.0.1:9738" + .to_string(); + assert_eq!(Err(Error::PeerInfoParseFailed), PeerInfo::try_from(invalid_peer_info_str1)); + + let invalid_peer_info_str2 = + "0276607124ebe6a6c9338517b6f485825b27c2dcc0b9fc2aa6a4c0df91194e5993@333.0.0.1:9738" + .to_string(); + assert_eq!(Err(Error::PeerInfoParseFailed), PeerInfo::try_from(invalid_peer_info_str2)); + + let invalid_peer_info_str3 = + "0276607124ebe6a6c9338517b6f485825b27c2dcc0b9fc2aa6a4c0df91194e5993@127.0.0.19738" + .to_string(); + assert_eq!(Err(Error::PeerInfoParseFailed), PeerInfo::try_from(invalid_peer_info_str3)); + } + + proptest! { + #[test] + fn peer_info_parsing_doesnt_crash(s in "\\PC*") { + let _ = PeerInfo::try_from(s.to_string()); + } + } +} diff --git a/src/test_utils.rs b/src/test_utils.rs deleted file mode 100644 index 737d679aa..000000000 --- a/src/test_utils.rs +++ /dev/null @@ -1,26 +0,0 @@ -use lightning::util::persist::KVStorePersister; -use lightning::util::ser::Writeable; - -use std::sync::atomic::{AtomicBool, Ordering}; - -pub(crate) struct TestPersister { - pending_persist: AtomicBool, -} - -impl TestPersister { - pub fn new() -> Self { - let pending_persist = AtomicBool::new(false); - Self { pending_persist } - } - - pub fn get_and_clear_pending_persist(&self) -> bool { - self.pending_persist.swap(false, Ordering::SeqCst) - } -} - -impl KVStorePersister for TestPersister { - fn persist(&self, _key: &str, _object: &W) -> std::io::Result<()> { - self.pending_persist.store(true, Ordering::SeqCst); - Ok(()) - } -} diff --git a/src/tests/functional_tests.rs b/src/tests/functional_tests.rs new file mode 100644 index 000000000..e83741cd8 --- /dev/null +++ b/src/tests/functional_tests.rs @@ -0,0 +1,378 @@ +use crate::tests::test_utils::expect_event; +use crate::{Builder, Config, Error, Event}; + +use bitcoin::{Address, Amount, OutPoint, Txid}; +use bitcoind::bitcoincore_rpc::RpcApi; +use electrsd::bitcoind::bitcoincore_rpc::bitcoincore_rpc_json::AddressType; +use electrsd::{bitcoind, bitcoind::BitcoinD, ElectrsD}; +use electrum_client::ElectrumApi; + +use once_cell::sync::OnceCell; +use rand::distributions::Alphanumeric; +use rand::{thread_rng, Rng}; + +use std::env; +use std::sync::Mutex; +use std::time::Duration; + +static BITCOIND: OnceCell = OnceCell::new(); +static ELECTRSD: OnceCell = OnceCell::new(); +static PREMINE: OnceCell<()> = OnceCell::new(); +static MINER_LOCK: Mutex<()> = Mutex::new(()); + +fn get_bitcoind() -> &'static BitcoinD { + BITCOIND.get_or_init(|| { + let bitcoind_exe = + env::var("BITCOIND_EXE").ok().or_else(|| bitcoind::downloaded_exe_path().ok()).expect( + "you need to provide an env var BITCOIND_EXE or specify a bitcoind version feature", + ); + let mut conf = bitcoind::Conf::default(); + conf.network = "regtest"; + BitcoinD::with_conf(bitcoind_exe, &conf).unwrap() + }) +} + +fn get_electrsd() -> &'static ElectrsD { + ELECTRSD.get_or_init(|| { + let bitcoind = get_bitcoind(); + let electrs_exe = + env::var("ELECTRS_EXE").ok().or_else(electrsd::downloaded_exe_path).expect( + "you need to provide env var ELECTRS_EXE or specify an electrsd version feature", + ); + let mut conf = electrsd::Conf::default(); + conf.http_enabled = true; + conf.network = "regtest"; + ElectrsD::with_conf(electrs_exe, &bitcoind, &conf).unwrap() + }) +} + +fn generate_blocks_and_wait(num: usize) { + let _miner = MINER_LOCK.lock().unwrap(); + let cur_height = get_bitcoind().client.get_block_count().unwrap(); + let address = + get_bitcoind().client.get_new_address(Some("test"), Some(AddressType::Legacy)).unwrap(); + let _block_hashes = get_bitcoind().client.generate_to_address(num as u64, &address).unwrap(); + wait_for_block(cur_height as usize + num); +} + +fn wait_for_block(min_height: usize) { + let mut header = get_electrsd().client.block_headers_subscribe().unwrap(); + loop { + if header.height >= min_height { + break; + } + header = exponential_backoff_poll(|| { + get_electrsd().trigger().unwrap(); + get_electrsd().client.ping().unwrap(); + get_electrsd().client.block_headers_pop().unwrap() + }); + } +} + +fn wait_for_tx(txid: Txid) { + let mut tx_res = get_electrsd().client.transaction_get(&txid); + loop { + if tx_res.is_ok() { + break; + } + tx_res = exponential_backoff_poll(|| { + get_electrsd().trigger().unwrap(); + get_electrsd().client.ping().unwrap(); + Some(get_electrsd().client.transaction_get(&txid)) + }); + } +} + +fn wait_for_outpoint_spend(outpoint: OutPoint) { + let tx = get_electrsd().client.transaction_get(&outpoint.txid).unwrap(); + let txout_script = tx.output.get(outpoint.vout as usize).unwrap().clone().script_pubkey; + let mut is_spent = !get_electrsd().client.script_get_history(&txout_script).unwrap().is_empty(); + loop { + if is_spent { + break; + } + + is_spent = exponential_backoff_poll(|| { + get_electrsd().trigger().unwrap(); + get_electrsd().client.ping().unwrap(); + Some(!get_electrsd().client.script_get_history(&txout_script).unwrap().is_empty()) + }); + } +} + +fn exponential_backoff_poll(mut poll: F) -> T +where + F: FnMut() -> Option, +{ + let mut delay = Duration::from_millis(64); + let mut tries = 0; + loop { + match poll() { + Some(data) => break data, + None if delay.as_millis() < 512 => { + delay = delay.mul_f32(2.0); + } + + None => {} + } + assert!(tries < 10, "Reached max tries."); + tries += 1; + std::thread::sleep(delay); + } +} + +fn premine_and_distribute_funds(addrs: Vec
, amount: Amount) { + PREMINE.get_or_init(|| { + generate_blocks_and_wait(101); + }); + + for addr in addrs { + let txid = get_bitcoind() + .client + .send_to_address(&addr, amount, None, None, None, None, None, None) + .unwrap(); + wait_for_tx(txid); + } + + generate_blocks_and_wait(1); +} + +fn rand_config() -> Config { + let mut config = Config::default(); + + let esplora_url = get_electrsd().esplora_url.as_ref().unwrap(); + + println!("Setting esplora server URL: {}", esplora_url); + config.esplora_server_url = format!("http://{}", esplora_url); + + let mut rng = thread_rng(); + let rand_dir: String = (0..7).map(|_| rng.sample(Alphanumeric) as char).collect(); + let rand_path = format!("/tmp/{}", rand_dir); + println!("Setting random LDK storage dir: {}", rand_dir); + config.storage_dir_path = rand_path; + + let rand_port: u16 = rng.gen_range(5000..8000); + println!("Setting random LDK listening port: {}", rand_port); + let listening_address = format!("127.0.0.1:{}", rand_port); + config.listening_address = Some(listening_address); + + config +} + +#[test] +fn channel_full_cycle() { + println!("== Node A =="); + let config_a = rand_config(); + let node_a = Builder::from_config(config_a).build(); + node_a.start().unwrap(); + let addr_a = node_a.new_funding_address().unwrap(); + + println!("\n== Node B =="); + let config_b = rand_config(); + let node_b = Builder::from_config(config_b).build(); + node_b.start().unwrap(); + let addr_b = node_b.new_funding_address().unwrap(); + + premine_and_distribute_funds(vec![addr_a, addr_b], Amount::from_sat(100000)); + node_a.sync_wallets().unwrap(); + node_b.sync_wallets().unwrap(); + assert_eq!(node_a.on_chain_balance().unwrap().get_spendable(), 100000); + assert_eq!(node_b.on_chain_balance().unwrap().get_spendable(), 100000); + + println!("\nA -- connect_open_channel -> B"); + let node_b_addr = format!("{}@{}", node_b.node_id(), node_b.listening_address().unwrap()); + node_a.connect_open_channel(&node_b_addr, 50000, true).unwrap(); + + let funding_txo = loop { + let details = node_a.list_channels(); + + if details.is_empty() || details[0].funding_txo.is_none() { + std::thread::sleep(Duration::from_secs(1)); + } else { + break details[0].funding_txo.unwrap(); + } + }; + + wait_for_tx(funding_txo.txid); + + println!("\n .. generating blocks, syncing wallets .. "); + generate_blocks_and_wait(6); + node_a.sync_wallets().unwrap(); + node_b.sync_wallets().unwrap(); + + let node_a_balance = node_a.on_chain_balance().unwrap(); + assert!(node_a_balance.get_spendable() < 50000); + assert!(node_a_balance.get_spendable() > 40000); + assert_eq!(node_b.on_chain_balance().unwrap().get_spendable(), 100000); + + expect_event!(node_a, ChannelReady); + + let channel_id = match node_b.next_event() { + ref e @ Event::ChannelReady { channel_id, .. } => { + println!("{} got event {:?}", std::stringify!(node_b), e); + node_b.event_handled(); + channel_id + } + ref e => { + panic!("{} got unexpected event!: {:?}", std::stringify!(node_b), e); + } + }; + + println!("\nB receive_payment"); + let invoice = node_b.receive_payment(1000000, &"asdf", 9217).unwrap(); + + println!("\nA send_payment"); + node_a.send_payment(invoice).unwrap(); + + expect_event!(node_a, PaymentSuccessful); + expect_event!(node_b, PaymentReceived); + + // Test under-/overpayment + let invoice_amount = 1000000; + let invoice = node_b.receive_payment(invoice_amount, &"asdf", 9217).unwrap(); + + let underpaid_amount = invoice_amount - 1; + assert_eq!( + Err(Error::InvalidAmount), + node_a.send_payment_using_amount(invoice, underpaid_amount) + ); + + let invoice = node_b.receive_payment(invoice_amount, &"asdf", 9217).unwrap(); + let overpaid_amount = invoice_amount + 100; + node_a.send_payment_using_amount(invoice, overpaid_amount).unwrap(); + expect_event!(node_a, PaymentSuccessful); + let received_amount = match node_b.next_event() { + ref e @ Event::PaymentReceived { amount_msat, .. } => { + println!("{} got event {:?}", std::stringify!(node_b), e); + node_b.event_handled(); + amount_msat + } + ref e => { + panic!("{} got unexpected event!: {:?}", std::stringify!(node_b), e); + } + }; + assert_eq!(received_amount, overpaid_amount); + + // Test "zero-amount" invoice payment + let variable_amount_invoice = node_b.receive_variable_amount_payment(&"asdf", 9217).unwrap(); + let determined_amount = 1234567; + assert_eq!(Err(Error::InvalidInvoice), node_a.send_payment(variable_amount_invoice.clone())); + node_a.send_payment_using_amount(variable_amount_invoice, determined_amount).unwrap(); + + expect_event!(node_a, PaymentSuccessful); + let received_amount = match node_b.next_event() { + ref e @ Event::PaymentReceived { amount_msat, .. } => { + println!("{} got event {:?}", std::stringify!(node_b), e); + node_b.event_handled(); + amount_msat + } + ref e => { + panic!("{} got unexpected event!: {:?}", std::stringify!(node_b), e); + } + }; + assert_eq!(received_amount, determined_amount); + + node_b.close_channel(&channel_id, &node_a.node_id()).unwrap(); + expect_event!(node_a, ChannelClosed); + expect_event!(node_b, ChannelClosed); + + wait_for_outpoint_spend(funding_txo.into_bitcoin_outpoint()); + + generate_blocks_and_wait(1); + node_a.sync_wallets().unwrap(); + node_b.sync_wallets().unwrap(); + + assert!(node_a.on_chain_balance().unwrap().get_spendable() > 90000); + assert_eq!(node_b.on_chain_balance().unwrap().get_spendable(), 103234); + + node_a.stop().unwrap(); + println!("\nA stopped"); + node_b.stop().unwrap(); + println!("\nB stopped"); +} + +#[test] +fn channel_open_fails_when_funds_insufficient() { + println!("== Node A =="); + let config_a = rand_config(); + let node_a = Builder::from_config(config_a).build(); + node_a.start().unwrap(); + let addr_a = node_a.new_funding_address().unwrap(); + + println!("\n== Node B =="); + let config_b = rand_config(); + let node_b = Builder::from_config(config_b).build(); + node_b.start().unwrap(); + let addr_b = node_b.new_funding_address().unwrap(); + + premine_and_distribute_funds(vec![addr_a, addr_b], Amount::from_sat(100000)); + node_a.sync_wallets().unwrap(); + node_b.sync_wallets().unwrap(); + assert_eq!(node_a.on_chain_balance().unwrap().get_spendable(), 100000); + assert_eq!(node_b.on_chain_balance().unwrap().get_spendable(), 100000); + + println!("\nA -- connect_open_channel -> B"); + let node_b_addr = format!("{}@{}", node_b.node_id(), node_b.listening_address().unwrap()); + assert_eq!( + Err(Error::InsufficientFunds), + node_a.connect_open_channel(&node_b_addr, 120000, true) + ); +} + +#[test] +fn connect_to_public_testnet_esplora() { + let mut config = rand_config(); + config.esplora_server_url = "https://blockstream.info/testnet/api".to_string(); + config.network = bitcoin::Network::Testnet; + let node = Builder::from_config(config).build(); + node.start().unwrap(); + node.sync_wallets().unwrap(); + node.stop().unwrap(); +} + +#[test] +fn start_stop_reinit() { + let config = rand_config(); + let node = Builder::from_config(config.clone()).build(); + let expected_node_id = node.node_id(); + + let funding_address = node.new_funding_address().unwrap(); + let expected_amount = Amount::from_sat(100000); + + premine_and_distribute_funds(vec![funding_address], expected_amount); + assert_eq!(node.on_chain_balance().unwrap().get_total(), 0); + + node.start().unwrap(); + assert_eq!(node.start(), Err(Error::AlreadyRunning)); + + node.sync_wallets().unwrap(); + assert_eq!(node.on_chain_balance().unwrap().get_spendable(), expected_amount.to_sat()); + + node.stop().unwrap(); + assert_eq!(node.stop(), Err(Error::NotRunning)); + + node.start().unwrap(); + assert_eq!(node.start(), Err(Error::AlreadyRunning)); + + node.stop().unwrap(); + assert_eq!(node.stop(), Err(Error::NotRunning)); + drop(node); + + let reinitialized_node = Builder::from_config(config).build(); + assert_eq!(reinitialized_node.node_id(), expected_node_id); + + reinitialized_node.start().unwrap(); + + assert_eq!( + reinitialized_node.on_chain_balance().unwrap().get_spendable(), + expected_amount.to_sat() + ); + + reinitialized_node.sync_wallets().unwrap(); + assert_eq!( + reinitialized_node.on_chain_balance().unwrap().get_spendable(), + expected_amount.to_sat() + ); + + reinitialized_node.stop().unwrap(); +} diff --git a/src/tests/mod.rs b/src/tests/mod.rs new file mode 100644 index 000000000..5c32fa2af --- /dev/null +++ b/src/tests/mod.rs @@ -0,0 +1,2 @@ +pub mod functional_tests; +pub mod test_utils; diff --git a/src/tests/test_utils.rs b/src/tests/test_utils.rs new file mode 100644 index 000000000..b4b832d45 --- /dev/null +++ b/src/tests/test_utils.rs @@ -0,0 +1,55 @@ +use lightning::util::persist::KVStorePersister; +use lightning::util::ser::Writeable; + +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Mutex; + +macro_rules! expect_event { + ($node: expr, $event_type: ident) => {{ + match $node.next_event() { + ref e @ Event::$event_type { .. } => { + println!("{} got event {:?}", std::stringify!($node), e); + $node.event_handled(); + } + ref e => { + panic!("{} got unexpected event!: {:?}", std::stringify!($node), e); + } + } + }}; +} + +pub(crate) use expect_event; + +pub(crate) struct TestPersister { + persisted_bytes: Mutex>>, + did_persist: AtomicBool, +} + +impl TestPersister { + pub fn new() -> Self { + let persisted_bytes = Mutex::new(HashMap::new()); + let did_persist = AtomicBool::new(false); + Self { persisted_bytes, did_persist } + } + + pub fn get_persisted_bytes(&self, key: &str) -> Option> { + let persisted_bytes_lock = self.persisted_bytes.lock().unwrap(); + persisted_bytes_lock.get(key).cloned() + } + + pub fn get_and_clear_did_persist(&self) -> bool { + self.did_persist.swap(false, Ordering::SeqCst) + } +} + +impl KVStorePersister for TestPersister { + fn persist(&self, key: &str, object: &W) -> std::io::Result<()> { + let mut persisted_bytes_lock = self.persisted_bytes.lock().unwrap(); + let mut bytes = Vec::new(); + object.write(&mut bytes)?; + persisted_bytes_lock.insert(key.to_owned(), bytes); + self.did_persist.store(true, Ordering::SeqCst); + Ok(()) + } +} diff --git a/src/types.rs b/src/types.rs new file mode 100644 index 000000000..deba8dd3e --- /dev/null +++ b/src/types.rs @@ -0,0 +1,95 @@ +use crate::logger::FilesystemLogger; +use crate::wallet::{Wallet, WalletKeysManager}; + +use lightning::chain::chainmonitor; +use lightning::chain::keysinterface::InMemorySigner; +use lightning::ln::peer_handler::IgnoringMessageHandler; +use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret}; +use lightning::routing::gossip; +use lightning::routing::gossip::P2PGossipSync; +use lightning::routing::router::DefaultRouter; +use lightning::routing::scoring::ProbabilisticScorer; +use lightning::routing::utxo::UtxoLookup; +use lightning_net_tokio::SocketDescriptor; +use lightning_persister::FilesystemPersister; +use lightning_transaction_sync::EsploraSyncClient; + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +// Structs wrapping the particular information which should easily be +// understandable, parseable, and transformable, i.e., we'll try to avoid +// exposing too many technical detail here. +/// Represents a payment. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PaymentInfo { + /// The pre-image used by the payment. + pub preimage: Option, + /// The secret used by the payment. + pub secret: Option, + /// The status of the payment. + pub status: PaymentStatus, + /// The amount transferred. + pub amount_msat: Option, +} + +/// Represents the current status of a payment. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum PaymentStatus { + /// The payment is still pending. + Pending, + /// The payment suceeded. + Succeeded, + /// The payment failed. + Failed, +} + +pub(crate) type ChainMonitor = chainmonitor::ChainMonitor< + InMemorySigner, + Arc>>, + Arc>, + Arc>, + Arc, + Arc, +>; + +pub(crate) type PeerManager = lightning::ln::peer_handler::PeerManager< + SocketDescriptor, + Arc, + Arc, + Arc, + Arc, + IgnoringMessageHandler, + Arc>, +>; + +pub(crate) type ChannelManager = lightning::ln::channelmanager::ChannelManager< + Arc, + Arc>, + Arc>, + Arc>, + Arc>, + Arc>, + Arc, + Arc, +>; + +pub(crate) type KeysManager = WalletKeysManager; + +pub(crate) type Router = + DefaultRouter, Arc, Arc>>; +pub(crate) type Scorer = ProbabilisticScorer, Arc>; + +pub(crate) type GossipSync = + P2PGossipSync, Arc, Arc>; + +pub(crate) type NetworkGraph = gossip::NetworkGraph>; + +pub(crate) type PaymentInfoStorage = Mutex>; + +pub(crate) type OnionMessenger = lightning::onion_message::OnionMessenger< + Arc>, + Arc>, + Arc, + IgnoringMessageHandler, +>; diff --git a/src/wallet.rs b/src/wallet.rs index dab6cdca2..beb8861c6 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -1,6 +1,4 @@ -use crate::logger::{ - log_error, log_given_level, log_internal, log_trace, FilesystemLogger, Logger, -}; +use crate::logger::{log_error, log_info, log_trace, FilesystemLogger, Logger}; use crate::Error; @@ -12,7 +10,7 @@ use lightning::chain::keysinterface::{ EntropySource, InMemorySigner, KeyMaterial, KeysManager, NodeSigner, Recipient, SignerProvider, SpendableOutputDescriptor, }; -use lightning::ln::msgs::DecodeError; +use lightning::ln::msgs::{DecodeError, UnsignedGossipMessage}; use lightning::ln::script::ShutdownScript; use bdk::blockchain::{Blockchain, EsploraBlockchain}; @@ -22,12 +20,13 @@ use bdk::{FeeRate, SignOptions, SyncOptions}; use bitcoin::bech32::u5; use bitcoin::secp256k1::ecdh::SharedSecret; -use bitcoin::secp256k1::ecdsa::RecoverableSignature; -use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey, Signing}; +use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature}; +use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, Signing}; use bitcoin::{Script, Transaction, TxOut}; use std::collections::HashMap; -use std::sync::{Arc, Mutex, RwLock}; +use std::sync::{Arc, Condvar, Mutex, RwLock}; +use std::time::Duration; pub struct Wallet where @@ -40,6 +39,7 @@ where // A cache storing the most recently retrieved fee rate estimations. fee_rate_cache: RwLock>, tokio_runtime: RwLock>>, + sync_lock: (Mutex<()>, Condvar), logger: Arc, } @@ -53,10 +53,24 @@ where let inner = Mutex::new(wallet); let fee_rate_cache = RwLock::new(HashMap::new()); let tokio_runtime = RwLock::new(None); - Self { blockchain, inner, fee_rate_cache, tokio_runtime, logger } + let sync_lock = (Mutex::new(()), Condvar::new()); + Self { blockchain, inner, fee_rate_cache, tokio_runtime, sync_lock, logger } } pub(crate) async fn sync(&self) -> Result<(), Error> { + let (lock, cvar) = &self.sync_lock; + + let guard = match lock.try_lock() { + Ok(guard) => guard, + Err(_) => { + log_info!(self.logger, "Sync in progress, skipping."); + let guard = cvar.wait(lock.lock().unwrap()); + drop(guard); + cvar.notify_all(); + return Ok(()); + } + }; + match self.update_fee_estimates().await { Ok(()) => (), Err(e) => { @@ -66,13 +80,39 @@ where } let sync_options = SyncOptions { progress: None }; - match self.inner.lock().unwrap().sync(&self.blockchain, sync_options).await { + let wallet_lock = self.inner.lock().unwrap(); + let res = match wallet_lock.sync(&self.blockchain, sync_options).await { Ok(()) => Ok(()), - Err(e) => { - log_error!(self.logger, "Wallet sync error: {}", e); - Err(From::from(e)) - } - } + Err(e) => match e { + bdk::Error::Esplora(ref be) => match **be { + bdk::blockchain::esplora::EsploraError::Reqwest(_) => { + tokio::time::sleep(Duration::from_secs(1)).await; + log_error!( + self.logger, + "Sync failed due to HTTP connection error, retrying: {}", + e + ); + let sync_options = SyncOptions { progress: None }; + wallet_lock + .sync(&self.blockchain, sync_options) + .await + .map_err(|e| From::from(e)) + } + _ => { + log_error!(self.logger, "Sync failed due to Esplora error: {}", e); + Err(From::from(e)) + } + }, + _ => { + log_error!(self.logger, "Wallet sync error: {}", e); + Err(From::from(e)) + } + }, + }; + + drop(guard); + cvar.notify_all(); + res } pub(crate) fn set_runtime(&self, tokio_runtime: Arc) { @@ -105,7 +145,8 @@ where locked_fee_rate_cache.insert(target, rate); log_trace!( self.logger, - "Fee rate estimation updated: {} sats/kwu", + "Fee rate estimation updated for {:?}: {} sats/kwu", + target, rate.fee_wu(1000) ); } @@ -139,12 +180,20 @@ where } Err(err) => { log_error!(self.logger, "Failed to create funding transaction: {}", err); - Err(err)? + return Err(err.into()); } }; - if !locked_wallet.sign(&mut psbt, SignOptions::default())? { - return Err(Error::FundingTxCreationFailed); + match locked_wallet.sign(&mut psbt, SignOptions::default()) { + Ok(finalized) => { + if !finalized { + return Err(Error::FundingTxCreationFailed); + } + } + Err(err) => { + log_error!(self.logger, "Failed to create funding transaction: {}", err); + return Err(err.into()); + } } Ok(psbt.extract_tx()) @@ -155,7 +204,6 @@ where Ok(address_info.address) } - #[cfg(any(test))] pub(crate) fn get_balance(&self) -> Result { Ok(self.inner.lock().unwrap().get_balance()?) } @@ -194,7 +242,7 @@ where let locked_runtime = self.tokio_runtime.read().unwrap(); if locked_runtime.as_ref().is_none() { log_error!(self.logger, "Failed to broadcast transaction: No runtime."); - unreachable!("Failed to broadcast transaction: No runtime."); + return; } let res = tokio::task::block_in_place(move || { @@ -263,10 +311,6 @@ impl NodeSigner for WalletKeysManager where D: BatchDatabase, { - fn get_node_secret(&self, recipient: Recipient) -> Result { - self.inner.get_node_secret(recipient) - } - fn get_node_id(&self, recipient: Recipient) -> Result { self.inner.get_node_id(recipient) } @@ -286,6 +330,10 @@ where ) -> Result { self.inner.sign_invoice(hrp_bytes, invoice_data, recipient) } + + fn sign_gossip_message(&self, msg: UnsignedGossipMessage<'_>) -> Result { + self.inner.sign_gossip_message(msg) + } } impl EntropySource for WalletKeysManager