Skip to content

Commit 5843e3e

Browse files
committed
Refactor may_announce_channel to return AnnounceError
This error type can provide more context to callers about why the node configuration does not support channel announcements.
1 parent 59454d3 commit 5843e3e

File tree

4 files changed

+97
-41
lines changed

4 files changed

+97
-41
lines changed

src/builder.rs

+20-4
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@
77

88
use crate::chain::{ChainSource, DEFAULT_ESPLORA_SERVER_URL};
99
use crate::config::{
10-
default_user_config, Config, EsploraSyncConfig, DEFAULT_LOG_FILENAME, DEFAULT_LOG_LEVEL,
11-
WALLET_KEYS_SEED_LEN,
10+
default_user_config, may_announce_channel, AnnounceError, Config, EsploraSyncConfig,
11+
DEFAULT_LOG_FILENAME, DEFAULT_LOG_LEVEL, WALLET_KEYS_SEED_LEN,
1212
};
1313

1414
use crate::connection::ConnectionManager;
@@ -32,8 +32,7 @@ use crate::types::{
3232
};
3333
use crate::wallet::persist::KVStoreWalletPersister;
3434
use crate::wallet::Wallet;
35-
use crate::Node;
36-
use crate::{io, NodeMetrics};
35+
use crate::{io, Node, NodeMetrics};
3736

3837
use lightning::chain::{chainmonitor, BestBlock, Watch};
3938
use lightning::io::Cursor;
@@ -912,6 +911,23 @@ fn build_with_store_internal(
912911
liquidity_source_config: Option<&LiquiditySourceConfig>, seed_bytes: [u8; 64],
913912
logger: Arc<Logger>, kv_store: Arc<DynStore>,
914913
) -> Result<Node, BuildError> {
914+
if let Err(err) = may_announce_channel(&config) {
915+
if config.announcement_addresses.is_some() {
916+
log_error!(logger, "Announcement addresses were set but some required configuration options for node announcement are missing: {}", err);
917+
let build_error = if matches!(err, AnnounceError::MissingNodeAlias) {
918+
BuildError::InvalidNodeAlias
919+
} else {
920+
BuildError::InvalidListeningAddresses
921+
};
922+
return Err(build_error);
923+
}
924+
925+
if config.node_alias.is_some() {
926+
log_error!(logger, "Node alias was set but some required configuration options for node announcement are missing: {}", err);
927+
return Err(BuildError::InvalidListeningAddresses);
928+
}
929+
}
930+
915931
// Initialize the status fields.
916932
let is_listening = Arc::new(AtomicBool::new(false));
917933
let node_metrics = match read_node_metrics(Arc::clone(&kv_store), Arc::clone(&logger)) {

src/config.rs

+51-9
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ use lightning::util::config::UserConfig;
1919
use bitcoin::secp256k1::PublicKey;
2020
use bitcoin::Network;
2121

22+
use std::fmt;
2223
use std::time::Duration;
2324

2425
// Config defaults
@@ -263,9 +264,37 @@ pub fn default_config() -> Config {
263264
Config::default()
264265
}
265266

266-
pub(crate) fn may_announce_channel(config: &Config) -> bool {
267-
config.node_alias.is_some()
268-
&& config.listening_addresses.as_ref().map_or(false, |addrs| !addrs.is_empty())
267+
#[derive(Debug, PartialEq)]
268+
pub(crate) enum AnnounceError {
269+
MissingNodeAlias,
270+
MissingListeningAddresses,
271+
MissingAliasAndAddresses,
272+
}
273+
274+
impl fmt::Display for AnnounceError {
275+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276+
match self {
277+
AnnounceError::MissingNodeAlias => write!(f, "Node alias is not configured"),
278+
AnnounceError::MissingListeningAddresses => {
279+
write!(f, "Listening addresses are not configured")
280+
},
281+
AnnounceError::MissingAliasAndAddresses => {
282+
write!(f, "Node alias and listening addresses are not configured")
283+
},
284+
}
285+
}
286+
}
287+
288+
pub(crate) fn may_announce_channel(config: &Config) -> Result<(), AnnounceError> {
289+
let has_listening_addresses =
290+
config.listening_addresses.as_ref().map_or(false, |addrs| !addrs.is_empty());
291+
292+
match (config.node_alias.is_some(), has_listening_addresses) {
293+
(true, true) => Ok(()),
294+
(true, false) => Err(AnnounceError::MissingListeningAddresses),
295+
(false, true) => Err(AnnounceError::MissingNodeAlias),
296+
(false, false) => Err(AnnounceError::MissingAliasAndAddresses),
297+
}
269298
}
270299

271300
pub(crate) fn default_user_config(config: &Config) -> UserConfig {
@@ -280,7 +309,7 @@ pub(crate) fn default_user_config(config: &Config) -> UserConfig {
280309
user_config.channel_handshake_config.negotiate_anchors_zero_fee_htlc_tx =
281310
config.anchor_channels_config.is_some();
282311

283-
if !may_announce_channel(config) {
312+
if may_announce_channel(config).is_err() {
284313
user_config.accept_forwards_to_priv_channels = false;
285314
user_config.channel_handshake_config.announce_for_forwarding = false;
286315
user_config.channel_handshake_limits.force_announced_channel_preference = true;
@@ -468,6 +497,7 @@ mod tests {
468497
use std::str::FromStr;
469498

470499
use super::may_announce_channel;
500+
use super::AnnounceError;
471501
use super::Config;
472502
use super::NodeAlias;
473503
use super::SocketAddress;
@@ -476,7 +506,10 @@ mod tests {
476506
fn node_announce_channel() {
477507
// Default configuration with node alias and listening addresses unset
478508
let mut node_config = Config::default();
479-
assert!(!may_announce_channel(&node_config));
509+
assert_eq!(
510+
may_announce_channel(&node_config),
511+
Err(AnnounceError::MissingAliasAndAddresses)
512+
);
480513

481514
// Set node alias with listening addresses unset
482515
let alias_frm_str = |alias: &str| {
@@ -485,24 +518,33 @@ mod tests {
485518
NodeAlias(bytes)
486519
};
487520
node_config.node_alias = Some(alias_frm_str("LDK_Node"));
488-
assert!(!may_announce_channel(&node_config));
521+
assert_eq!(
522+
may_announce_channel(&node_config),
523+
Err(AnnounceError::MissingListeningAddresses)
524+
);
489525

490526
// Set announcement addresses with listening addresses unset
491527
let announcement_address = SocketAddress::from_str("123.45.67.89:9735")
492528
.expect("Socket address conversion failed.");
493529
node_config.announcement_addresses = Some(vec![announcement_address]);
494-
assert!(!may_announce_channel(&node_config));
530+
assert_eq!(
531+
may_announce_channel(&node_config),
532+
Err(AnnounceError::MissingListeningAddresses)
533+
);
495534

496535
// Set node alias with an empty list of listening addresses
497536
node_config.listening_addresses = Some(vec![]);
498-
assert!(!may_announce_channel(&node_config));
537+
assert_eq!(
538+
may_announce_channel(&node_config),
539+
Err(AnnounceError::MissingListeningAddresses)
540+
);
499541

500542
// Set node alias with a non-empty list of listening addresses
501543
let socket_address =
502544
SocketAddress::from_str("localhost:8000").expect("Socket address conversion failed.");
503545
if let Some(ref mut addresses) = node_config.listening_addresses {
504546
addresses.push(socket_address);
505547
}
506-
assert!(may_announce_channel(&node_config));
548+
assert!(may_announce_channel(&node_config).is_ok());
507549
}
508550
}

src/event.rs

+14-16
Original file line numberDiff line numberDiff line change
@@ -1077,23 +1077,21 @@ where
10771077
is_announced,
10781078
params: _,
10791079
} => {
1080-
if is_announced && !may_announce_channel(&*self.config) {
1081-
log_error!(
1082-
self.logger,
1083-
"Rejecting inbound announced channel from peer {} as not all required details are set. Please ensure node alias and listening addresses have been configured.",
1084-
counterparty_node_id,
1085-
);
1080+
if is_announced {
1081+
if let Err(err) = may_announce_channel(&*self.config) {
1082+
log_error!(self.logger, "Rejecting inbound announced channel from peer {} due to missing configuration: {}", counterparty_node_id, err);
10861083

1087-
self.channel_manager
1088-
.force_close_without_broadcasting_txn(
1089-
&temporary_channel_id,
1090-
&counterparty_node_id,
1091-
"Channel request rejected".to_string(),
1092-
)
1093-
.unwrap_or_else(|e| {
1094-
log_error!(self.logger, "Failed to reject channel: {:?}", e)
1095-
});
1096-
return Ok(());
1084+
self.channel_manager
1085+
.force_close_without_broadcasting_txn(
1086+
&temporary_channel_id,
1087+
&counterparty_node_id,
1088+
"Channel request rejected".to_string(),
1089+
)
1090+
.unwrap_or_else(|e| {
1091+
log_error!(self.logger, "Failed to reject channel: {:?}", e)
1092+
});
1093+
return Ok(());
1094+
}
10971095
}
10981096

10991097
let anchor_channel = channel_type.requires_anchors_zero_fee_htlc_tx();

src/lib.rs

+12-12
Original file line numberDiff line numberDiff line change
@@ -414,7 +414,7 @@ impl Node {
414414
let bcast_node_metrics = Arc::clone(&self.node_metrics);
415415
let mut stop_bcast = self.stop_sender.subscribe();
416416
let node_alias = self.config.node_alias.clone();
417-
if may_announce_channel(&self.config) {
417+
if may_announce_channel(&self.config).is_ok() {
418418
runtime.spawn(async move {
419419
// We check every 30 secs whether our last broadcast is NODE_ANN_BCAST_INTERVAL away.
420420
#[cfg(not(test))]
@@ -1211,19 +1211,19 @@ impl Node {
12111211
&self, node_id: PublicKey, address: SocketAddress, channel_amount_sats: u64,
12121212
push_to_counterparty_msat: Option<u64>, channel_config: Option<ChannelConfig>,
12131213
) -> Result<UserChannelId, Error> {
1214-
if may_announce_channel(&self.config) {
1215-
self.open_channel_inner(
1216-
node_id,
1217-
address,
1218-
channel_amount_sats,
1219-
push_to_counterparty_msat,
1220-
channel_config,
1221-
true,
1222-
)
1223-
} else {
1224-
log_error!(self.logger, "Failed to open announced channel as the node hasn't been sufficiently configured to act as a forwarding node. Please make sure to configure listening addreesses and node alias");
1214+
if let Err(err) = may_announce_channel(&self.config) {
1215+
log_error!(self.logger, "Failed to open announced channel as the node hasn't been sufficiently configured to act as a forwarding node: {}", err);
12251216
return Err(Error::ChannelCreationFailed);
12261217
}
1218+
1219+
self.open_channel_inner(
1220+
node_id,
1221+
address,
1222+
channel_amount_sats,
1223+
push_to_counterparty_msat,
1224+
channel_config,
1225+
true,
1226+
)
12271227
}
12281228

12291229
/// Manually sync the LDK and BDK wallets with the current chain state and update the fee rate

0 commit comments

Comments
 (0)