From 2734dd8ff8da6fe8e7ba8007338cd84f18b6c166 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Mon, 19 Feb 2024 15:29:48 +0100 Subject: [PATCH] Move `Config` and associated `const`s to `config.rs` ... as we're about to add a bunch more stuff, it improves readability to split these out to their own module. --- src/builder.rs | 10 ++-- src/config.rs | 135 ++++++++++++++++++++++++++++++++++++++++++ src/io/utils.rs | 2 +- src/lib.rs | 141 ++++---------------------------------------- src/uniffi_types.rs | 2 +- 5 files changed, 153 insertions(+), 137 deletions(-) create mode 100644 src/config.rs diff --git a/src/builder.rs b/src/builder.rs index 29230c4a0..75c5bc9db 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -1,3 +1,7 @@ +use crate::config::{ + Config, BDK_CLIENT_CONCURRENCY, BDK_CLIENT_STOP_GAP, DEFAULT_ESPLORA_SERVER_URL, + WALLET_KEYS_SEED_LEN, +}; use crate::event::EventQueue; use crate::fee_estimator::OnchainFeeEstimator; use crate::gossip::GossipSource; @@ -15,11 +19,7 @@ use crate::types::{ OnionMessenger, PeerManager, }; use crate::wallet::Wallet; -use crate::LogLevel; -use crate::{ - Config, Node, BDK_CLIENT_CONCURRENCY, BDK_CLIENT_STOP_GAP, DEFAULT_ESPLORA_SERVER_URL, - WALLET_KEYS_SEED_LEN, -}; +use crate::{LogLevel, Node}; use lightning::chain::{chainmonitor, BestBlock, Watch}; use lightning::ln::channelmanager::{self, ChainParameters, ChannelManagerReadArgs}; diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 000000000..945d712c9 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,135 @@ +use std::time::Duration; + +use lightning::ln::msgs::SocketAddress; +use lightning::util::logger::Level as LogLevel; + +use bitcoin::secp256k1::PublicKey; +use bitcoin::Network; + +// Config defaults +const DEFAULT_STORAGE_DIR_PATH: &str = "/tmp/ldk_node/"; +const DEFAULT_NETWORK: Network = Network::Bitcoin; +const DEFAULT_CLTV_EXPIRY_DELTA: u32 = 144; +const DEFAULT_BDK_WALLET_SYNC_INTERVAL_SECS: u64 = 80; +const DEFAULT_LDK_WALLET_SYNC_INTERVAL_SECS: u64 = 30; +const DEFAULT_FEE_RATE_CACHE_UPDATE_INTERVAL_SECS: u64 = 60 * 10; +const DEFAULT_PROBING_LIQUIDITY_LIMIT_MULTIPLIER: u64 = 3; +const DEFAULT_LOG_LEVEL: LogLevel = LogLevel::Debug; + +// The 'stop gap' parameter used by BDK's wallet sync. This seems to configure the threshold +// number of derivation indexes after which BDK stops looking for new scripts belonging to the wallet. +pub(crate) const BDK_CLIENT_STOP_GAP: usize = 20; + +// The number of concurrent requests made against the API provider. +pub(crate) const BDK_CLIENT_CONCURRENCY: u8 = 4; + +// The default Esplora server we're using. +pub(crate) const DEFAULT_ESPLORA_SERVER_URL: &str = "https://blockstream.info/api"; + +// The timeout after which we abandon retrying failed payments. +pub(crate) const LDK_PAYMENT_RETRY_TIMEOUT: Duration = Duration::from_secs(10); + +// The time in-between peer reconnection attempts. +pub(crate) const PEER_RECONNECTION_INTERVAL: Duration = Duration::from_secs(10); + +// The time in-between RGS sync attempts. +pub(crate) const RGS_SYNC_INTERVAL: Duration = Duration::from_secs(60 * 60); + +// The time in-between node announcement broadcast attempts. +pub(crate) const NODE_ANN_BCAST_INTERVAL: Duration = Duration::from_secs(60 * 60); + +// The lower limit which we apply to any configured wallet sync intervals. +pub(crate) const WALLET_SYNC_INTERVAL_MINIMUM_SECS: u64 = 10; + +// The length in bytes of our wallets' keys seed. +pub(crate) const WALLET_KEYS_SEED_LEN: usize = 64; + +#[derive(Debug, Clone)] +/// Represents the configuration of an [`Node`] instance. +/// +/// ### Defaults +/// +/// | Parameter | Value | +/// |----------------------------------------|--------------------| +/// | `storage_dir_path` | /tmp/ldk_node/ | +/// | `log_dir_path` | None | +/// | `network` | Bitcoin | +/// | `listening_addresses` | None | +/// | `default_cltv_expiry_delta` | 144 | +/// | `onchain_wallet_sync_interval_secs` | 80 | +/// | `wallet_sync_interval_secs` | 30 | +/// | `fee_rate_cache_update_interval_secs` | 600 | +/// | `trusted_peers_0conf` | [] | +/// | `probing_liquidity_limit_multiplier` | 3 | +/// | `log_level` | Debug | +/// +/// [`Node`]: crate::Node +pub struct Config { + /// The path where the underlying LDK and BDK persist their data. + pub storage_dir_path: String, + /// The path where logs are stored. + /// + /// If set to `None`, logs can be found in the `logs` subdirectory in [`Config::storage_dir_path`]. + pub log_dir_path: Option, + /// The used Bitcoin network. + pub network: Network, + /// The addresses on which the node will listen for incoming connections. + pub listening_addresses: Option>, + /// The default CLTV expiry delta to be used for payments. + pub default_cltv_expiry_delta: u32, + /// The time in-between background sync attempts of the onchain wallet, in seconds. + /// + /// **Note:** A minimum of 10 seconds is always enforced. + pub onchain_wallet_sync_interval_secs: u64, + /// The time in-between background sync attempts of the LDK wallet, in seconds. + /// + /// **Note:** A minimum of 10 seconds is always enforced. + pub wallet_sync_interval_secs: u64, + /// The time in-between background update attempts to our fee rate cache, in seconds. + /// + /// **Note:** A minimum of 10 seconds is always enforced. + pub fee_rate_cache_update_interval_secs: u64, + /// A list of peers that we allow to establish zero confirmation channels to us. + /// + /// **Note:** Allowing payments via zero-confirmation channels is potentially insecure if the + /// funding transaction ends up never being confirmed on-chain. Zero-confirmation channels + /// should therefore only be accepted from trusted peers. + pub trusted_peers_0conf: Vec, + /// The liquidity factor by which we filter the outgoing channels used for sending probes. + /// + /// Channels with available liquidity less than the required amount times this value won't be + /// used to send pre-flight probes. + pub probing_liquidity_limit_multiplier: u64, + /// The level at which we log messages. + /// + /// Any messages below this level will be excluded from the logs. + pub log_level: LogLevel, +} + +impl Default for Config { + fn default() -> Self { + Self { + storage_dir_path: DEFAULT_STORAGE_DIR_PATH.to_string(), + log_dir_path: None, + network: DEFAULT_NETWORK, + listening_addresses: None, + default_cltv_expiry_delta: DEFAULT_CLTV_EXPIRY_DELTA, + onchain_wallet_sync_interval_secs: DEFAULT_BDK_WALLET_SYNC_INTERVAL_SECS, + wallet_sync_interval_secs: DEFAULT_LDK_WALLET_SYNC_INTERVAL_SECS, + fee_rate_cache_update_interval_secs: DEFAULT_FEE_RATE_CACHE_UPDATE_INTERVAL_SECS, + trusted_peers_0conf: Vec::new(), + probing_liquidity_limit_multiplier: DEFAULT_PROBING_LIQUIDITY_LIMIT_MULTIPLIER, + log_level: DEFAULT_LOG_LEVEL, + } + } +} + +/// Returns a [`Config`] object populated with default values. +/// +/// See the documentation of [`Config`] for more information on the used defaults. +/// +/// This is mostly meant for use in bindings, in Rust this is synonymous with +/// [`Config::default()`]. +pub fn default_config() -> Config { + Config::default() +} diff --git a/src/io/utils.rs b/src/io/utils.rs index 603b3344e..f486dda8b 100644 --- a/src/io/utils.rs +++ b/src/io/utils.rs @@ -1,5 +1,5 @@ use super::*; -use crate::WALLET_KEYS_SEED_LEN; +use crate::config::WALLET_KEYS_SEED_LEN; use crate::logger::log_error; use crate::peer_store::PeerStore; diff --git a/src/lib.rs b/src/lib.rs index 32ca4147f..d0b6e9993 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -77,6 +77,7 @@ mod balance; mod builder; +mod config; mod error; mod event; mod fee_estimator; @@ -101,6 +102,7 @@ pub use lightning; pub use lightning_invoice; pub use balance::{BalanceDetails, LightningBalance, PendingSweepBalance}; +pub use config::{default_config, Config}; pub use error::Error as NodeError; use error::Error; @@ -118,6 +120,10 @@ pub use builder::BuildError; #[cfg(not(feature = "uniffi"))] pub use builder::NodeBuilder as Builder; +use config::{ + LDK_PAYMENT_RETRY_TIMEOUT, NODE_ANN_BCAST_INTERVAL, PEER_RECONNECTION_INTERVAL, + RGS_SYNC_INTERVAL, WALLET_SYNC_INTERVAL_MINIMUM_SECS, +}; use event::{EventHandler, EventQueue}; use gossip::GossipSource; use liquidity::LiquiditySource; @@ -155,7 +161,7 @@ use bitcoin::hashes::sha256::Hash as Sha256; use bitcoin::hashes::Hash; use bitcoin::secp256k1::PublicKey; -use bitcoin::{Address, Network, Txid}; +use bitcoin::{Address, Txid}; use rand::Rng; @@ -167,133 +173,6 @@ use std::time::{Duration, Instant, SystemTime}; #[cfg(feature = "uniffi")] uniffi::include_scaffolding!("ldk_node"); -// Config defaults -const DEFAULT_STORAGE_DIR_PATH: &str = "/tmp/ldk_node/"; -const DEFAULT_NETWORK: Network = Network::Bitcoin; -const DEFAULT_CLTV_EXPIRY_DELTA: u32 = 144; -const DEFAULT_BDK_WALLET_SYNC_INTERVAL_SECS: u64 = 80; -const DEFAULT_LDK_WALLET_SYNC_INTERVAL_SECS: u64 = 30; -const DEFAULT_FEE_RATE_CACHE_UPDATE_INTERVAL_SECS: u64 = 60 * 10; -const DEFAULT_PROBING_LIQUIDITY_LIMIT_MULTIPLIER: u64 = 3; -const DEFAULT_LOG_LEVEL: LogLevel = LogLevel::Debug; - -// The 'stop gap' parameter used by BDK's wallet sync. This seems to configure the threshold -// number of derivation indexes after which BDK stops looking for new 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 = 4; - -// The default Esplora server we're using. -const DEFAULT_ESPLORA_SERVER_URL: &str = "https://blockstream.info/api"; - -// 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 time in-between RGS sync attempts. -const RGS_SYNC_INTERVAL: Duration = Duration::from_secs(60 * 60); - -// The time in-between node announcement broadcast attempts. -const NODE_ANN_BCAST_INTERVAL: Duration = Duration::from_secs(60 * 60); - -// The lower limit which we apply to any configured wallet sync intervals. -const WALLET_SYNC_INTERVAL_MINIMUM_SECS: u64 = 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. -/// -/// ### Defaults -/// -/// | Parameter | Value | -/// |----------------------------------------|--------------------| -/// | `storage_dir_path` | /tmp/ldk_node/ | -/// | `log_dir_path` | None | -/// | `network` | Bitcoin | -/// | `listening_addresses` | None | -/// | `default_cltv_expiry_delta` | 144 | -/// | `onchain_wallet_sync_interval_secs` | 80 | -/// | `wallet_sync_interval_secs` | 30 | -/// | `fee_rate_cache_update_interval_secs` | 600 | -/// | `trusted_peers_0conf` | [] | -/// | `probing_liquidity_limit_multiplier` | 3 | -/// | `log_level` | Debug | -/// -pub struct Config { - /// The path where the underlying LDK and BDK persist their data. - pub storage_dir_path: String, - /// The path where logs are stored. - /// - /// If set to `None`, logs can be found in the `logs` subdirectory in [`Config::storage_dir_path`]. - pub log_dir_path: Option, - /// The used Bitcoin network. - pub network: Network, - /// The addresses on which the node will listen for incoming connections. - pub listening_addresses: Option>, - /// The default CLTV expiry delta to be used for payments. - pub default_cltv_expiry_delta: u32, - /// The time in-between background sync attempts of the onchain wallet, in seconds. - /// - /// **Note:** A minimum of 10 seconds is always enforced. - pub onchain_wallet_sync_interval_secs: u64, - /// The time in-between background sync attempts of the LDK wallet, in seconds. - /// - /// **Note:** A minimum of 10 seconds is always enforced. - pub wallet_sync_interval_secs: u64, - /// The time in-between background update attempts to our fee rate cache, in seconds. - /// - /// **Note:** A minimum of 10 seconds is always enforced. - pub fee_rate_cache_update_interval_secs: u64, - /// A list of peers that we allow to establish zero confirmation channels to us. - /// - /// **Note:** Allowing payments via zero-confirmation channels is potentially insecure if the - /// funding transaction ends up never being confirmed on-chain. Zero-confirmation channels - /// should therefore only be accepted from trusted peers. - pub trusted_peers_0conf: Vec, - /// The liquidity factor by which we filter the outgoing channels used for sending probes. - /// - /// Channels with available liquidity less than the required amount times this value won't be - /// used to send pre-flight probes. - pub probing_liquidity_limit_multiplier: u64, - /// The level at which we log messages. - /// - /// Any messages below this level will be excluded from the logs. - pub log_level: LogLevel, -} - -impl Default for Config { - fn default() -> Self { - Self { - storage_dir_path: DEFAULT_STORAGE_DIR_PATH.to_string(), - log_dir_path: None, - network: DEFAULT_NETWORK, - listening_addresses: None, - default_cltv_expiry_delta: DEFAULT_CLTV_EXPIRY_DELTA, - onchain_wallet_sync_interval_secs: DEFAULT_BDK_WALLET_SYNC_INTERVAL_SECS, - wallet_sync_interval_secs: DEFAULT_LDK_WALLET_SYNC_INTERVAL_SECS, - fee_rate_cache_update_interval_secs: DEFAULT_FEE_RATE_CACHE_UPDATE_INTERVAL_SECS, - trusted_peers_0conf: Vec::new(), - probing_liquidity_limit_multiplier: DEFAULT_PROBING_LIQUIDITY_LIMIT_MULTIPLIER, - log_level: DEFAULT_LOG_LEVEL, - } - } -} - -/// Returns a [`Config`] object populated with default values. -/// -/// See the documentation of [`Config`] for more information on the used defaults. -/// -/// This is mostly meant for use in bindings, in Rust this is synonymous with -/// [`Config::default()`]. -pub fn default_config() -> Config { - Config::default() -} - /// The main interface object of LDK Node, wrapping the necessary LDK and BDK functionalities. /// /// Needs to be initialized and instantiated through [`Builder::build`]. @@ -369,8 +248,10 @@ impl Node { let wallet = Arc::clone(&self.wallet); let sync_logger = Arc::clone(&self.logger); let mut stop_sync = self.stop_receiver.clone(); - let onchain_wallet_sync_interval_secs = - self.config.onchain_wallet_sync_interval_secs.max(WALLET_SYNC_INTERVAL_MINIMUM_SECS); + let onchain_wallet_sync_interval_secs = self + .config + .onchain_wallet_sync_interval_secs + .max(config::WALLET_SYNC_INTERVAL_MINIMUM_SECS); std::thread::spawn(move || { tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on( async move { diff --git a/src/uniffi_types.rs b/src/uniffi_types.rs index 81eeaaa7a..7c6343b84 100644 --- a/src/uniffi_types.rs +++ b/src/uniffi_types.rs @@ -3,7 +3,7 @@ pub use lightning::ln::ChannelId; pub use lightning::ln::PaymentSecret; pub use lightning::util::string::UntrustedString; -pub use bitcoin::{BlockHash, OutPoint}; +pub use bitcoin::{BlockHash, Network, OutPoint}; pub use bip39::Mnemonic;