ldk_node/config.rs
1// This file is Copyright its original authors, visible in version control history.
2//
3// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
6// accordance with one or both of these licenses.
7
8//! Objects for configuring the node.
9
10use crate::logger::LogLevel;
11use crate::payment::SendingParameters;
12
13use lightning::ln::msgs::SocketAddress;
14use lightning::routing::gossip::NodeAlias;
15use lightning::util::config::ChannelConfig as LdkChannelConfig;
16use lightning::util::config::MaxDustHTLCExposure as LdkMaxDustHTLCExposure;
17use lightning::util::config::UserConfig;
18
19use bitcoin::secp256k1::PublicKey;
20use bitcoin::Network;
21
22use std::fmt;
23use std::time::Duration;
24
25// Config defaults
26const DEFAULT_NETWORK: Network = Network::Bitcoin;
27const DEFAULT_BDK_WALLET_SYNC_INTERVAL_SECS: u64 = 80;
28const DEFAULT_LDK_WALLET_SYNC_INTERVAL_SECS: u64 = 30;
29const DEFAULT_FEE_RATE_CACHE_UPDATE_INTERVAL_SECS: u64 = 60 * 10;
30const DEFAULT_PROBING_LIQUIDITY_LIMIT_MULTIPLIER: u64 = 3;
31const DEFAULT_ANCHOR_PER_CHANNEL_RESERVE_SATS: u64 = 25_000;
32
33/// The default log level.
34pub const DEFAULT_LOG_LEVEL: LogLevel = LogLevel::Debug;
35
36/// The default log file name.
37pub const DEFAULT_LOG_FILENAME: &'static str = "ldk_node.log";
38
39/// The default storage directory.
40pub const DEFAULT_STORAGE_DIR_PATH: &str = "/tmp/ldk_node";
41
42// The 'stop gap' parameter used by BDK's wallet sync. This seems to configure the threshold
43// number of derivation indexes after which BDK stops looking for new scripts belonging to the wallet.
44pub(crate) const BDK_CLIENT_STOP_GAP: usize = 20;
45
46// The number of concurrent requests made against the API provider.
47pub(crate) const BDK_CLIENT_CONCURRENCY: usize = 4;
48
49// The timeout after which we abandon retrying failed payments.
50pub(crate) const LDK_PAYMENT_RETRY_TIMEOUT: Duration = Duration::from_secs(10);
51
52// The interval (in block height) after which we retry archiving fully resolved channel monitors.
53pub(crate) const RESOLVED_CHANNEL_MONITOR_ARCHIVAL_INTERVAL: u32 = 6;
54
55// The time in-between peer reconnection attempts.
56pub(crate) const PEER_RECONNECTION_INTERVAL: Duration = Duration::from_secs(60);
57
58// The time in-between RGS sync attempts.
59pub(crate) const RGS_SYNC_INTERVAL: Duration = Duration::from_secs(60 * 60);
60
61// The time in-between node announcement broadcast attempts.
62pub(crate) const NODE_ANN_BCAST_INTERVAL: Duration = Duration::from_secs(60 * 60);
63
64// The lower limit which we apply to any configured wallet sync intervals.
65pub(crate) const WALLET_SYNC_INTERVAL_MINIMUM_SECS: u64 = 10;
66
67// The timeout after which we abort a wallet syncing operation.
68pub(crate) const BDK_WALLET_SYNC_TIMEOUT_SECS: u64 = 20;
69
70// The timeout after which we abort a wallet syncing operation.
71pub(crate) const LDK_WALLET_SYNC_TIMEOUT_SECS: u64 = 10;
72
73// The timeout after which we give up waiting on LDK's event handler to exit on shutdown.
74pub(crate) const LDK_EVENT_HANDLER_SHUTDOWN_TIMEOUT_SECS: u64 = 30;
75
76// The timeout after which we give up waiting on a background task to exit on shutdown.
77pub(crate) const BACKGROUND_TASK_SHUTDOWN_TIMEOUT_SECS: u64 = 5;
78
79// The timeout after which we abort a fee rate cache update operation.
80pub(crate) const FEE_RATE_CACHE_UPDATE_TIMEOUT_SECS: u64 = 5;
81
82// The timeout after which we abort a transaction broadcast operation.
83pub(crate) const TX_BROADCAST_TIMEOUT_SECS: u64 = 5;
84
85// The timeout after which we abort a RGS sync operation.
86pub(crate) const RGS_SYNC_TIMEOUT_SECS: u64 = 5;
87
88/// The length in bytes of our wallets' keys seed.
89pub const WALLET_KEYS_SEED_LEN: usize = 64;
90
91#[derive(Debug, Clone)]
92/// Represents the configuration of an [`Node`] instance.
93///
94/// ### Defaults
95///
96/// | Parameter | Value |
97/// |----------------------------------------|--------------------|
98/// | `storage_dir_path` | /tmp/ldk_node/ |
99/// | `log_dir_path` | None |
100/// | `network` | Bitcoin |
101/// | `listening_addresses` | None |
102/// | `node_alias` | None |
103/// | `default_cltv_expiry_delta` | 144 |
104/// | `onchain_wallet_sync_interval_secs` | 80 |
105/// | `wallet_sync_interval_secs` | 30 |
106/// | `fee_rate_cache_update_interval_secs` | 600 |
107/// | `trusted_peers_0conf` | [] |
108/// | `probing_liquidity_limit_multiplier` | 3 |
109/// | `log_level` | Debug |
110/// | `anchor_channels_config` | Some(..) |
111/// | `sending_parameters` | None |
112///
113/// See [`AnchorChannelsConfig`] and [`SendingParameters`] for more information regarding their
114/// respective default values.
115///
116/// [`Node`]: crate::Node
117pub struct Config {
118 /// The path where the underlying LDK and BDK persist their data.
119 pub storage_dir_path: String,
120 /// The used Bitcoin network.
121 pub network: Network,
122 /// The addresses on which the node will listen for incoming connections.
123 ///
124 /// **Note**: We will only allow opening and accepting public channels if the `node_alias` and the
125 /// `listening_addresses` are set.
126 pub listening_addresses: Option<Vec<SocketAddress>>,
127 /// The addresses which the node will announce to the gossip network that it accepts connections on.
128 ///
129 /// **Note**: If unset, the [`listening_addresses`] will be used as the list of addresses to announce.
130 ///
131 /// [`listening_addresses`]: Config::listening_addresses
132 pub announcement_addresses: Option<Vec<SocketAddress>>,
133 /// The node alias that will be used when broadcasting announcements to the gossip network.
134 ///
135 /// The provided alias must be a valid UTF-8 string and no longer than 32 bytes in total.
136 ///
137 /// **Note**: We will only allow opening and accepting public channels if the `node_alias` and the
138 /// `listening_addresses` are set.
139 pub node_alias: Option<NodeAlias>,
140 /// A list of peers that we allow to establish zero confirmation channels to us.
141 ///
142 /// **Note:** Allowing payments via zero-confirmation channels is potentially insecure if the
143 /// funding transaction ends up never being confirmed on-chain. Zero-confirmation channels
144 /// should therefore only be accepted from trusted peers.
145 pub trusted_peers_0conf: Vec<PublicKey>,
146 /// The liquidity factor by which we filter the outgoing channels used for sending probes.
147 ///
148 /// Channels with available liquidity less than the required amount times this value won't be
149 /// used to send pre-flight probes.
150 pub probing_liquidity_limit_multiplier: u64,
151 /// Configuration options pertaining to Anchor channels, i.e., channels for which the
152 /// `option_anchors_zero_fee_htlc_tx` channel type is negotiated.
153 ///
154 /// Please refer to [`AnchorChannelsConfig`] for further information on Anchor channels.
155 ///
156 /// If set to `Some`, we'll try to open new channels with Anchors enabled, i.e., new channels
157 /// will be negotiated with the `option_anchors_zero_fee_htlc_tx` channel type if supported by
158 /// the counterparty. Note that this won't prevent us from opening non-Anchor channels if the
159 /// counterparty doesn't support `option_anchors_zero_fee_htlc_tx`. If set to `None`, new
160 /// channels will be negotiated with the legacy `option_static_remotekey` channel type only.
161 ///
162 /// **Note:** If set to `None` *after* some Anchor channels have already been
163 /// opened, no dedicated emergency on-chain reserve will be maintained for these channels,
164 /// which can be dangerous if only insufficient funds are available at the time of channel
165 /// closure. We *will* however still try to get the Anchor spending transactions confirmed
166 /// on-chain with the funds available.
167 pub anchor_channels_config: Option<AnchorChannelsConfig>,
168 /// Configuration options for payment routing and pathfinding.
169 ///
170 /// Setting the `SendingParameters` provides flexibility to customize how payments are routed,
171 /// including setting limits on routing fees, CLTV expiry, and channel utilization.
172 ///
173 /// **Note:** If unset, default parameters will be used, and you will be able to override the
174 /// parameters on a per-payment basis in the corresponding method calls.
175 pub sending_parameters: Option<SendingParameters>,
176}
177
178impl Default for Config {
179 fn default() -> Self {
180 Self {
181 storage_dir_path: DEFAULT_STORAGE_DIR_PATH.to_string(),
182 network: DEFAULT_NETWORK,
183 listening_addresses: None,
184 announcement_addresses: None,
185 trusted_peers_0conf: Vec::new(),
186 probing_liquidity_limit_multiplier: DEFAULT_PROBING_LIQUIDITY_LIMIT_MULTIPLIER,
187 anchor_channels_config: Some(AnchorChannelsConfig::default()),
188 sending_parameters: None,
189 node_alias: None,
190 }
191 }
192}
193
194/// Configuration options pertaining to 'Anchor' channels, i.e., channels for which the
195/// `option_anchors_zero_fee_htlc_tx` channel type is negotiated.
196///
197/// Prior to the introduction of Anchor channels, the on-chain fees paying for the transactions
198/// issued on channel closure were pre-determined and locked-in at the time of the channel
199/// opening. This required to estimate what fee rate would be sufficient to still have the
200/// closing transactions be spendable on-chain (i.e., not be considered dust). This legacy
201/// design of pre-anchor channels proved inadequate in the unpredictable, often turbulent, fee
202/// markets we experience today.
203///
204/// In contrast, Anchor channels allow to determine an adequate fee rate *at the time of channel
205/// closure*, making them much more robust in the face of fee spikes. In turn, they require to
206/// maintain a reserve of on-chain funds to have the channel closure transactions confirmed
207/// on-chain, at least if the channel counterparty can't be trusted to do this for us.
208///
209/// See [BOLT 3] for more technical details on Anchor channels.
210///
211///
212/// ### Defaults
213///
214/// | Parameter | Value |
215/// |----------------------------|--------|
216/// | `trusted_peers_no_reserve` | [] |
217/// | `per_channel_reserve_sats` | 25000 |
218///
219///
220/// [BOLT 3]: https://github.com/lightning/bolts/blob/master/03-transactions.md#htlc-timeout-and-htlc-success-transactions
221#[derive(Debug, Clone)]
222pub struct AnchorChannelsConfig {
223 /// A list of peers that we trust to get the required channel closing transactions confirmed
224 /// on-chain.
225 ///
226 /// Channels with these peers won't count towards the retained on-chain reserve and we won't
227 /// take any action to get the required channel closing transactions confirmed ourselves.
228 ///
229 /// **Note:** Trusting the channel counterparty to take the necessary actions to get the
230 /// required Anchor spending transactions confirmed on-chain is potentially insecure
231 /// as the channel may not be closed if they refuse to do so.
232 pub trusted_peers_no_reserve: Vec<PublicKey>,
233 /// The amount of satoshis per anchors-negotiated channel with an untrusted peer that we keep
234 /// as an emergency reserve in our on-chain wallet.
235 ///
236 /// This allows for having the required Anchor output spending and HTLC transactions confirmed
237 /// when the channel is closed.
238 ///
239 /// If the channel peer is not marked as trusted via
240 /// [`AnchorChannelsConfig::trusted_peers_no_reserve`], we will always try to spend the Anchor
241 /// outputs with *any* on-chain funds available, i.e., the total reserve value as well as any
242 /// spendable funds available in the on-chain wallet. Therefore, this per-channel multiplier is
243 /// really a emergency reserve that we maintain at all time to reduce reduce the risk of
244 /// insufficient funds at time of a channel closure. To this end, we will refuse to open
245 /// outbound or accept inbound channels if we don't have sufficient on-chain funds available to
246 /// cover the additional reserve requirement.
247 ///
248 /// **Note:** Depending on the fee market at the time of closure, this reserve amount might or
249 /// might not suffice to successfully spend the Anchor output and have the HTLC transactions
250 /// confirmed on-chain, i.e., you may want to adjust this value accordingly.
251 pub per_channel_reserve_sats: u64,
252}
253
254impl Default for AnchorChannelsConfig {
255 fn default() -> Self {
256 Self {
257 trusted_peers_no_reserve: Vec::new(),
258 per_channel_reserve_sats: DEFAULT_ANCHOR_PER_CHANNEL_RESERVE_SATS,
259 }
260 }
261}
262
263/// Returns a [`Config`] object populated with default values.
264///
265/// See the documentation of [`Config`] for more information on the used defaults.
266///
267/// This is mostly meant for use in bindings, in Rust this is synonymous with
268/// [`Config::default()`].
269pub fn default_config() -> Config {
270 Config::default()
271}
272
273#[derive(Debug, PartialEq)]
274pub(crate) enum AnnounceError {
275 MissingNodeAlias,
276 MissingListeningAddresses,
277 MissingAliasAndAddresses,
278}
279
280impl fmt::Display for AnnounceError {
281 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282 match self {
283 AnnounceError::MissingNodeAlias => write!(f, "Node alias is not configured"),
284 AnnounceError::MissingListeningAddresses => {
285 write!(f, "Listening addresses are not configured")
286 },
287 AnnounceError::MissingAliasAndAddresses => {
288 write!(f, "Node alias and listening addresses are not configured")
289 },
290 }
291 }
292}
293
294pub(crate) fn may_announce_channel(config: &Config) -> Result<(), AnnounceError> {
295 let has_listening_addresses =
296 config.listening_addresses.as_ref().map_or(false, |addrs| !addrs.is_empty());
297
298 match (config.node_alias.is_some(), has_listening_addresses) {
299 (true, true) => Ok(()),
300 (true, false) => Err(AnnounceError::MissingListeningAddresses),
301 (false, true) => Err(AnnounceError::MissingNodeAlias),
302 (false, false) => Err(AnnounceError::MissingAliasAndAddresses),
303 }
304}
305
306pub(crate) fn default_user_config(config: &Config) -> UserConfig {
307 // Initialize the default config values.
308 //
309 // Note that methods such as Node::open_channel and Node::open_announced_channel might override
310 // some of the values set here, e.g. the ChannelHandshakeConfig, meaning these default values
311 // will mostly be relevant for inbound channels.
312 let mut user_config = UserConfig::default();
313 user_config.channel_handshake_limits.force_announced_channel_preference = false;
314 user_config.manually_accept_inbound_channels = true;
315 user_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx =
316 config.anchor_channels_config.is_some();
317
318 if may_announce_channel(config).is_err() {
319 user_config.accept_forwards_to_priv_channels = false;
320 user_config.channel_handshake_config.announce_for_forwarding = false;
321 user_config.channel_handshake_limits.force_announced_channel_preference = true;
322 }
323
324 user_config
325}
326
327/// Options related to background syncing the Lightning and on-chain wallets.
328///
329/// ### Defaults
330///
331/// | Parameter | Value |
332/// |----------------------------------------|--------------------|
333/// | `onchain_wallet_sync_interval_secs` | 80 |
334/// | `lightning_wallet_sync_interval_secs` | 30 |
335/// | `fee_rate_cache_update_interval_secs` | 600 |
336#[derive(Debug, Copy, Clone, PartialEq, Eq)]
337pub struct BackgroundSyncConfig {
338 /// The time in-between background sync attempts of the onchain wallet, in seconds.
339 ///
340 /// **Note:** A minimum of 10 seconds is enforced when background syncing is enabled.
341 pub onchain_wallet_sync_interval_secs: u64,
342
343 /// The time in-between background sync attempts of the LDK wallet, in seconds.
344 ///
345 /// **Note:** A minimum of 10 seconds is enforced when background syncing is enabled.
346 pub lightning_wallet_sync_interval_secs: u64,
347
348 /// The time in-between background update attempts to our fee rate cache, in seconds.
349 ///
350 /// **Note:** A minimum of 10 seconds is enforced when background syncing is enabled.
351 pub fee_rate_cache_update_interval_secs: u64,
352}
353
354impl Default for BackgroundSyncConfig {
355 fn default() -> Self {
356 Self {
357 onchain_wallet_sync_interval_secs: DEFAULT_BDK_WALLET_SYNC_INTERVAL_SECS,
358 lightning_wallet_sync_interval_secs: DEFAULT_LDK_WALLET_SYNC_INTERVAL_SECS,
359 fee_rate_cache_update_interval_secs: DEFAULT_FEE_RATE_CACHE_UPDATE_INTERVAL_SECS,
360 }
361 }
362}
363
364/// Configuration for syncing with an Esplora backend.
365///
366/// Background syncing is enabled by default, using the default values specified in
367/// [`BackgroundSyncConfig`].
368#[derive(Debug, Copy, Clone, PartialEq, Eq)]
369pub struct EsploraSyncConfig {
370 /// Background sync configuration.
371 ///
372 /// If set to `None`, background syncing will be disabled. Users will need to manually
373 /// sync via [`Node::sync_wallets`] for the wallets and fee rate updates.
374 ///
375 /// [`Node::sync_wallets`]: crate::Node::sync_wallets
376 pub background_sync_config: Option<BackgroundSyncConfig>,
377}
378
379impl Default for EsploraSyncConfig {
380 fn default() -> Self {
381 Self { background_sync_config: Some(BackgroundSyncConfig::default()) }
382 }
383}
384
385/// Configuration for syncing with an Electrum backend.
386///
387/// Background syncing is enabled by default, using the default values specified in
388/// [`BackgroundSyncConfig`].
389#[derive(Debug, Copy, Clone, PartialEq, Eq)]
390pub struct ElectrumSyncConfig {
391 /// Background sync configuration.
392 ///
393 /// If set to `None`, background syncing will be disabled. Users will need to manually
394 /// sync via [`Node::sync_wallets`] for the wallets and fee rate updates.
395 ///
396 /// [`Node::sync_wallets`]: crate::Node::sync_wallets
397 pub background_sync_config: Option<BackgroundSyncConfig>,
398}
399
400impl Default for ElectrumSyncConfig {
401 fn default() -> Self {
402 Self { background_sync_config: Some(BackgroundSyncConfig::default()) }
403 }
404}
405
406/// Options which apply on a per-channel basis and may change at runtime or based on negotiation
407/// with our counterparty.
408#[derive(Copy, Clone, Debug, PartialEq, Eq)]
409pub struct ChannelConfig {
410 /// Amount (in millionths of a satoshi) charged per satoshi for payments forwarded outbound
411 /// over the channel.
412 /// This may be allowed to change at runtime in a later update, however doing so must result in
413 /// update messages sent to notify all nodes of our updated relay fee.
414 ///
415 /// Please refer to [`LdkChannelConfig`] for further details.
416 pub forwarding_fee_proportional_millionths: u32,
417 /// Amount (in milli-satoshi) charged for payments forwarded outbound over the channel, in
418 /// excess of [`ChannelConfig::forwarding_fee_proportional_millionths`].
419 /// This may be allowed to change at runtime in a later update, however doing so must result in
420 /// update messages sent to notify all nodes of our updated relay fee.
421 ///
422 /// Please refer to [`LdkChannelConfig`] for further details.
423 pub forwarding_fee_base_msat: u32,
424 /// The difference in the CLTV value between incoming HTLCs and an outbound HTLC forwarded over
425 /// the channel this config applies to.
426 ///
427 /// Please refer to [`LdkChannelConfig`] for further details.
428 pub cltv_expiry_delta: u16,
429 /// Limit our total exposure to potential loss to on-chain fees on close, including in-flight
430 /// HTLCs which are burned to fees as they are too small to claim on-chain and fees on
431 /// commitment transaction(s) broadcasted by our counterparty in excess of our own fee estimate.
432 ///
433 /// Please refer to [`LdkChannelConfig`] for further details.
434 pub max_dust_htlc_exposure: MaxDustHTLCExposure,
435 /// The additional fee we're willing to pay to avoid waiting for the counterparty's
436 /// `to_self_delay` to reclaim funds.
437 ///
438 /// Please refer to [`LdkChannelConfig`] for further details.
439 pub force_close_avoidance_max_fee_satoshis: u64,
440 /// If set, allows this channel's counterparty to skim an additional fee off this node's inbound
441 /// HTLCs. Useful for liquidity providers to offload on-chain channel costs to end users.
442 ///
443 /// Please refer to [`LdkChannelConfig`] for further details.
444 pub accept_underpaying_htlcs: bool,
445}
446
447impl From<LdkChannelConfig> for ChannelConfig {
448 fn from(value: LdkChannelConfig) -> Self {
449 Self {
450 forwarding_fee_proportional_millionths: value.forwarding_fee_proportional_millionths,
451 forwarding_fee_base_msat: value.forwarding_fee_base_msat,
452 cltv_expiry_delta: value.cltv_expiry_delta,
453 max_dust_htlc_exposure: value.max_dust_htlc_exposure.into(),
454 force_close_avoidance_max_fee_satoshis: value.force_close_avoidance_max_fee_satoshis,
455 accept_underpaying_htlcs: value.accept_underpaying_htlcs,
456 }
457 }
458}
459
460impl From<ChannelConfig> for LdkChannelConfig {
461 fn from(value: ChannelConfig) -> Self {
462 Self {
463 forwarding_fee_proportional_millionths: value.forwarding_fee_proportional_millionths,
464 forwarding_fee_base_msat: value.forwarding_fee_base_msat,
465 cltv_expiry_delta: value.cltv_expiry_delta,
466 max_dust_htlc_exposure: value.max_dust_htlc_exposure.into(),
467 force_close_avoidance_max_fee_satoshis: value.force_close_avoidance_max_fee_satoshis,
468 accept_underpaying_htlcs: value.accept_underpaying_htlcs,
469 }
470 }
471}
472
473impl Default for ChannelConfig {
474 fn default() -> Self {
475 LdkChannelConfig::default().into()
476 }
477}
478
479/// Options for how to set the max dust exposure allowed on a channel.
480///
481/// See [`LdkChannelConfig::max_dust_htlc_exposure`] for details.
482#[derive(Copy, Clone, Debug, PartialEq, Eq)]
483pub enum MaxDustHTLCExposure {
484 /// This sets a fixed limit on the total dust exposure in millisatoshis.
485 ///
486 /// Please refer to [`LdkMaxDustHTLCExposure`] for further details.
487 FixedLimit {
488 /// The fixed limit, in millisatoshis.
489 limit_msat: u64,
490 },
491 /// This sets a multiplier on the feerate to determine the maximum allowed dust exposure.
492 ///
493 /// Please refer to [`LdkMaxDustHTLCExposure`] for further details.
494 FeeRateMultiplier {
495 /// The applied fee rate multiplier.
496 multiplier: u64,
497 },
498}
499
500impl From<LdkMaxDustHTLCExposure> for MaxDustHTLCExposure {
501 fn from(value: LdkMaxDustHTLCExposure) -> Self {
502 match value {
503 LdkMaxDustHTLCExposure::FixedLimitMsat(limit_msat) => Self::FixedLimit { limit_msat },
504 LdkMaxDustHTLCExposure::FeeRateMultiplier(multiplier) => {
505 Self::FeeRateMultiplier { multiplier }
506 },
507 }
508 }
509}
510
511impl From<MaxDustHTLCExposure> for LdkMaxDustHTLCExposure {
512 fn from(value: MaxDustHTLCExposure) -> Self {
513 match value {
514 MaxDustHTLCExposure::FixedLimit { limit_msat } => Self::FixedLimitMsat(limit_msat),
515 MaxDustHTLCExposure::FeeRateMultiplier { multiplier } => {
516 Self::FeeRateMultiplier(multiplier)
517 },
518 }
519 }
520}
521
522#[cfg(test)]
523mod tests {
524 use std::str::FromStr;
525
526 use super::may_announce_channel;
527 use super::AnnounceError;
528 use super::Config;
529 use super::NodeAlias;
530 use super::SocketAddress;
531
532 #[test]
533 fn node_announce_channel() {
534 // Default configuration with node alias and listening addresses unset
535 let mut node_config = Config::default();
536 assert_eq!(
537 may_announce_channel(&node_config),
538 Err(AnnounceError::MissingAliasAndAddresses)
539 );
540
541 // Set node alias with listening addresses unset
542 let alias_frm_str = |alias: &str| {
543 let mut bytes = [0u8; 32];
544 bytes[..alias.as_bytes().len()].copy_from_slice(alias.as_bytes());
545 NodeAlias(bytes)
546 };
547 node_config.node_alias = Some(alias_frm_str("LDK_Node"));
548 assert_eq!(
549 may_announce_channel(&node_config),
550 Err(AnnounceError::MissingListeningAddresses)
551 );
552
553 // Set announcement addresses with listening addresses unset
554 let announcement_address = SocketAddress::from_str("123.45.67.89:9735")
555 .expect("Socket address conversion failed.");
556 node_config.announcement_addresses = Some(vec![announcement_address]);
557 assert_eq!(
558 may_announce_channel(&node_config),
559 Err(AnnounceError::MissingListeningAddresses)
560 );
561
562 // Set node alias with an empty list of listening addresses
563 node_config.listening_addresses = Some(vec![]);
564 assert_eq!(
565 may_announce_channel(&node_config),
566 Err(AnnounceError::MissingListeningAddresses)
567 );
568
569 // Set node alias with a non-empty list of listening addresses
570 let socket_address =
571 SocketAddress::from_str("localhost:8000").expect("Socket address conversion failed.");
572 if let Some(ref mut addresses) = node_config.listening_addresses {
573 addresses.push(socket_address);
574 }
575 assert!(may_announce_channel(&node_config).is_ok());
576 }
577}