Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -325,7 +325,6 @@ enum NodeError {

dictionary NodeStatus {
boolean is_running;
boolean is_listening;
BestBlock current_best_block;
u64? latest_lightning_wallet_sync_timestamp;
u64? latest_onchain_wallet_sync_timestamp;
Expand Down
3 changes: 0 additions & 3 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,6 @@ use std::collections::HashMap;
use std::convert::TryInto;
use std::default::Default;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex, Once, RwLock};
use std::time::SystemTime;
use std::{fmt, fs};
Expand DownExpand Up@@ -1133,7 +1132,6 @@ fn build_with_store_internal(
}

// Initialize the status fields.
let is_listening = Arc::new(AtomicBool::new(false));
let node_metrics = match read_node_metrics(Arc::clone(&kv_store), Arc::clone(&logger)) {
Ok(metrics) => Arc::new(RwLock::new(metrics)),
Err(e) => {
Expand DownExpand Up@@ -1734,7 +1732,6 @@ fn build_with_store_internal(
peer_store,
payment_store,
is_running,
is_listening,
node_metrics,
om_mailbox,
async_payments_role,
Expand Down
96 changes: 52 additions & 44 deletions src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,7 +101,6 @@ mod wallet;

use std::default::Default;
use std::net::ToSocketAddrs;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

Expand DownExpand Up@@ -189,7 +188,6 @@ pub struct Node {
peer_store: Arc<PeerStore<Arc<Logger>>>,
payment_store: Arc<PaymentStore>,
is_running: Arc<RwLock<bool>>,
is_listening: Arc<AtomicBool>,
Comment thread
joostjager marked this conversation as resolved.
node_metrics: Arc<RwLock<NodeMetrics>>,
om_mailbox: Option<Arc<OnionMessageMailbox>>,
async_payments_role: Option<AsyncPaymentsRole>,
Expand DownExpand Up@@ -293,9 +291,7 @@ impl Node {
if let Some(listening_addresses) = &self.config.listening_addresses {
// Setup networking
let peer_manager_connection_handler = Arc::clone(&self.peer_manager);
let mut stop_listen = self.stop_sender.subscribe();
let listening_logger = Arc::clone(&self.logger);
let listening_indicator = Arc::clone(&self.is_listening);

let mut bind_addrs = Vec::with_capacity(listening_addresses.len());

Expand All@@ -313,45 +309,62 @@ impl Node {
bind_addrs.extend(resolved_address);
}

self.runtime.spawn_cancellable_background_task(async move {
{
let listener =
tokio::net::TcpListener::bind(&*bind_addrs).await
.unwrap_or_else(|e| {
log_error!(listening_logger, "Failed to bind to listen addresses/ports - is something else already listening on it?: {}", e);
panic!(
"Failed to bind to listen address/port - is something else already listening on it?",
);
});

listening_indicator.store(true, Ordering::Release);

loop {
let peer_mgr = Arc::clone(&peer_manager_connection_handler);
tokio::select! {
_ = stop_listen.changed() => {
log_debug!(
listening_logger,
"Stopping listening to inbound connections."
let logger = Arc::clone(&listening_logger);
let listeners = self.runtime.block_on(async move {

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to block if we want to return an error.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, I see the point. I guess we need to if we want to abort on error for now, but we'll probably make start async soonish anyways.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternative is to use non-tokio binds here.

let mut listeners = Vec::new();

// Try to bind to all addresses
for addr in &*bind_addrs {
match tokio::net::TcpListener::bind(addr).await {
Ok(listener) => {
log_trace!(logger, "Listener bound to {}", addr);
listeners.push(listener);
},
Err(e) => {
log_error!(
logger,
"Failed to bind to {}: {} - is something else already listening?",
addr,
e
);
break;
}
res = listener.accept() => {
let tcp_stream = res.unwrap().0;
tokio::spawn(async move {
lightning_net_tokio::setup_inbound(
Arc::clone(&peer_mgr),
tcp_stream.into_std().unwrap(),
)
.await;
});
}
return Err(Error::InvalidSocketAddress);
},
}
}
}

listening_indicator.store(false, Ordering::Release);
});
Ok(listeners)
})?;

for listener in listeners {
let logger = Arc::clone(&listening_logger);
let peer_mgr = Arc::clone(&peer_manager_connection_handler);
let mut stop_listen = self.stop_sender.subscribe();
let runtime = Arc::clone(&self.runtime);
self.runtime.spawn_cancellable_background_task(async move {
loop {
tokio::select! {
_ = stop_listen.changed() => {
log_debug!(
logger,
"Stopping listening to inbound connections."
);
break;
}
res = listener.accept() => {
let tcp_stream = res.unwrap().0;
let peer_mgr = Arc::clone(&peer_mgr);
runtime.spawn_cancellable_background_task(async move {
lightning_net_tokio::setup_inbound(
Arc::clone(&peer_mgr),
tcp_stream.into_std().unwrap(),
)
.await;
});
}
}
}
});
}
}

// Regularly reconnect to persisted peers.
Expand DownExpand Up@@ -666,7 +679,6 @@ impl Node {
/// Returns the status of the [`Node`].
pub fn status(&self) -> NodeStatus {
let is_running = *self.is_running.read().unwrap();
let is_listening = self.is_listening.load(Ordering::Acquire);
let current_best_block = self.channel_manager.current_best_block().into();
let locked_node_metrics = self.node_metrics.read().unwrap();
let latest_lightning_wallet_sync_timestamp =
Expand All@@ -684,7 +696,6 @@ impl Node {

NodeStatus {
is_running,
is_listening,
current_best_block,
latest_lightning_wallet_sync_timestamp,
latest_onchain_wallet_sync_timestamp,
Expand DownExpand Up@@ -1495,9 +1506,6 @@ impl Drop for Node {
pub struct NodeStatus {
/// Indicates whether the [`Node`] is running.
pub is_running: bool,
/// Indicates whether the [`Node`] is listening for incoming connections on the addresses
/// configured via [`Config::listening_addresses`].
pub is_listening: bool,
/// The best block to which our Lightning wallet is currently synced.
pub current_best_block: BestBlock,
/// The timestamp, in seconds since start of the UNIX epoch, when we last successfully synced
Expand Down
2 changes: 1 addition & 1 deletion tests/common/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -195,7 +195,7 @@ pub(crate) fn random_storage_path() -> PathBuf {

pub(crate) fn random_port() -> u16 {
let mut rng = thread_rng();
rng.gen_range(5000..65535)
rng.gen_range(5000..32768)
}

pub(crate) fn random_listening_addresses() -> Vec<SocketAddress> {
Expand Down
24 changes: 15 additions & 9 deletions tests/integration_tests_rust.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -817,6 +817,21 @@ fn sign_verify_msg() {
assert!(node.verify_signature(msg, sig.as_str(), &pkey));
}

#[test]
fn connection_multi_listen() {
let (_bitcoind, electrsd) = setup_bitcoind_and_electrsd();
let chain_source = TestChainSource::Esplora(&electrsd);
let (node_a, node_b) = setup_two_nodes(&chain_source, false, false, false);

let node_id_b = node_b.node_id();

let node_addrs_b = node_b.listening_addresses().unwrap();
for node_addr_b in &node_addrs_b {
node_a.connect(node_id_b, node_addr_b.clone(), false).unwrap();
node_a.disconnect(node_id_b).unwrap();
}
}

#[test]
fn connection_restart_behavior() {
do_connection_restart_behavior(true);
Expand All@@ -832,11 +847,6 @@ fn do_connection_restart_behavior(persist: bool) {
let node_id_b = node_b.node_id();

let node_addr_b = node_b.listening_addresses().unwrap().first().unwrap().clone();

while !node_b.status().is_listening {
std::thread::sleep(std::time::Duration::from_millis(10));
}

node_a.connect(node_id_b, node_addr_b, persist).unwrap();

let peer_details_a = node_a.list_peers().first().unwrap().clone();
Expand DownExpand Up@@ -886,10 +896,6 @@ fn concurrent_connections_succeed() {
let node_id_b = node_b.node_id();
let node_addr_b = node_b.listening_addresses().unwrap().first().unwrap().clone();

while !node_b.status().is_listening {
std::thread::sleep(std::time::Duration::from_millis(10));
}

let mut handles = Vec::new();
for _ in 0..10 {
let thread_node = Arc::clone(&node_a);
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Listen on all provided addresses by joostjager · Pull Request #644 · lightningdevkit/ldk-node · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -325,7 +325,6 @@ enum NodeError {

dictionary NodeStatus {
boolean is_running;
boolean is_listening;
BestBlock current_best_block;
u64? latest_lightning_wallet_sync_timestamp;
u64? latest_onchain_wallet_sync_timestamp;
Expand Down
3 changes: 0 additions & 3 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,6 @@ use std::collections::HashMap;
use std::convert::TryInto;
use std::default::Default;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex, Once, RwLock};
use std::time::SystemTime;
use std::{fmt, fs};
Expand DownExpand Up@@ -1133,7 +1132,6 @@ fn build_with_store_internal(
}

// Initialize the status fields.
let is_listening = Arc::new(AtomicBool::new(false));
let node_metrics = match read_node_metrics(Arc::clone(&kv_store), Arc::clone(&logger)) {
Ok(metrics) => Arc::new(RwLock::new(metrics)),
Err(e) => {
Expand DownExpand Up@@ -1734,7 +1732,6 @@ fn build_with_store_internal(
peer_store,
payment_store,
is_running,
is_listening,
node_metrics,
om_mailbox,
async_payments_role,
Expand Down
96 changes: 52 additions & 44 deletions src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,7 +101,6 @@ mod wallet;

use std::default::Default;
use std::net::ToSocketAddrs;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

Expand DownExpand Up@@ -189,7 +188,6 @@ pub struct Node {
peer_store: Arc<PeerStore<Arc<Logger>>>,
payment_store: Arc<PaymentStore>,
is_running: Arc<RwLock<bool>>,
is_listening: Arc<AtomicBool>,
Comment thread
joostjager marked this conversation as resolved.
node_metrics: Arc<RwLock<NodeMetrics>>,
om_mailbox: Option<Arc<OnionMessageMailbox>>,
async_payments_role: Option<AsyncPaymentsRole>,
Expand DownExpand Up@@ -293,9 +291,7 @@ impl Node {
if let Some(listening_addresses) = &self.config.listening_addresses {
// Setup networking
let peer_manager_connection_handler = Arc::clone(&self.peer_manager);
let mut stop_listen = self.stop_sender.subscribe();
let listening_logger = Arc::clone(&self.logger);
let listening_indicator = Arc::clone(&self.is_listening);

let mut bind_addrs = Vec::with_capacity(listening_addresses.len());

Expand All@@ -313,45 +309,62 @@ impl Node {
bind_addrs.extend(resolved_address);
}

self.runtime.spawn_cancellable_background_task(async move {
{
let listener =
tokio::net::TcpListener::bind(&*bind_addrs).await
.unwrap_or_else(|e| {
log_error!(listening_logger, "Failed to bind to listen addresses/ports - is something else already listening on it?: {}", e);
panic!(
"Failed to bind to listen address/port - is something else already listening on it?",
);
});

listening_indicator.store(true, Ordering::Release);

loop {
let peer_mgr = Arc::clone(&peer_manager_connection_handler);
tokio::select! {
_ = stop_listen.changed() => {
log_debug!(
listening_logger,
"Stopping listening to inbound connections."
let logger = Arc::clone(&listening_logger);
let listeners = self.runtime.block_on(async move {

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to block if we want to return an error.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, I see the point. I guess we need to if we want to abort on error for now, but we'll probably make start async soonish anyways.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternative is to use non-tokio binds here.

let mut listeners = Vec::new();

// Try to bind to all addresses
for addr in &*bind_addrs {
match tokio::net::TcpListener::bind(addr).await {
Ok(listener) => {
log_trace!(logger, "Listener bound to {}", addr);
listeners.push(listener);
},
Err(e) => {
log_error!(
logger,
"Failed to bind to {}: {} - is something else already listening?",
addr,
e
);
break;
}
res = listener.accept() => {
let tcp_stream = res.unwrap().0;
tokio::spawn(async move {
lightning_net_tokio::setup_inbound(
Arc::clone(&peer_mgr),
tcp_stream.into_std().unwrap(),
)
.await;
});
}
return Err(Error::InvalidSocketAddress);
},
}
}
}

listening_indicator.store(false, Ordering::Release);
});
Ok(listeners)
})?;

for listener in listeners {
let logger = Arc::clone(&listening_logger);
let peer_mgr = Arc::clone(&peer_manager_connection_handler);
let mut stop_listen = self.stop_sender.subscribe();
let runtime = Arc::clone(&self.runtime);
self.runtime.spawn_cancellable_background_task(async move {
loop {
tokio::select! {
_ = stop_listen.changed() => {
log_debug!(
logger,
"Stopping listening to inbound connections."
);
break;
}
res = listener.accept() => {
let tcp_stream = res.unwrap().0;
let peer_mgr = Arc::clone(&peer_mgr);
runtime.spawn_cancellable_background_task(async move {
lightning_net_tokio::setup_inbound(
Arc::clone(&peer_mgr),
tcp_stream.into_std().unwrap(),
)
.await;
});
}
}
}
});
}
}

// Regularly reconnect to persisted peers.
Expand DownExpand Up@@ -666,7 +679,6 @@ impl Node {
/// Returns the status of the [`Node`].
pub fn status(&self) -> NodeStatus {
let is_running = *self.is_running.read().unwrap();
let is_listening = self.is_listening.load(Ordering::Acquire);
let current_best_block = self.channel_manager.current_best_block().into();
let locked_node_metrics = self.node_metrics.read().unwrap();
let latest_lightning_wallet_sync_timestamp =
Expand All@@ -684,7 +696,6 @@ impl Node {

NodeStatus {
is_running,
is_listening,
current_best_block,
latest_lightning_wallet_sync_timestamp,
latest_onchain_wallet_sync_timestamp,
Expand DownExpand Up@@ -1495,9 +1506,6 @@ impl Drop for Node {
pub struct NodeStatus {
/// Indicates whether the [`Node`] is running.
pub is_running: bool,
/// Indicates whether the [`Node`] is listening for incoming connections on the addresses
/// configured via [`Config::listening_addresses`].
pub is_listening: bool,
/// The best block to which our Lightning wallet is currently synced.
pub current_best_block: BestBlock,
/// The timestamp, in seconds since start of the UNIX epoch, when we last successfully synced
Expand Down
2 changes: 1 addition & 1 deletion tests/common/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -195,7 +195,7 @@ pub(crate) fn random_storage_path() -> PathBuf {

pub(crate) fn random_port() -> u16 {
let mut rng = thread_rng();
rng.gen_range(5000..65535)
rng.gen_range(5000..32768)
}

pub(crate) fn random_listening_addresses() -> Vec<SocketAddress> {
Expand Down
24 changes: 15 additions & 9 deletions tests/integration_tests_rust.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -817,6 +817,21 @@ fn sign_verify_msg() {
assert!(node.verify_signature(msg, sig.as_str(), &pkey));
}

#[test]
fn connection_multi_listen() {
let (_bitcoind, electrsd) = setup_bitcoind_and_electrsd();
let chain_source = TestChainSource::Esplora(&electrsd);
let (node_a, node_b) = setup_two_nodes(&chain_source, false, false, false);

let node_id_b = node_b.node_id();

let node_addrs_b = node_b.listening_addresses().unwrap();
for node_addr_b in &node_addrs_b {
node_a.connect(node_id_b, node_addr_b.clone(), false).unwrap();
node_a.disconnect(node_id_b).unwrap();
}
}

#[test]
fn connection_restart_behavior() {
do_connection_restart_behavior(true);
Expand All@@ -832,11 +847,6 @@ fn do_connection_restart_behavior(persist: bool) {
let node_id_b = node_b.node_id();

let node_addr_b = node_b.listening_addresses().unwrap().first().unwrap().clone();

while !node_b.status().is_listening {
std::thread::sleep(std::time::Duration::from_millis(10));
}

node_a.connect(node_id_b, node_addr_b, persist).unwrap();

let peer_details_a = node_a.list_peers().first().unwrap().clone();
Expand DownExpand Up@@ -886,10 +896,6 @@ fn concurrent_connections_succeed() {
let node_id_b = node_b.node_id();
let node_addr_b = node_b.listening_addresses().unwrap().first().unwrap().clone();

while !node_b.status().is_listening {
std::thread::sleep(std::time::Duration::from_millis(10));
}

let mut handles = Vec::new();
for _ in 0..10 {
let thread_node = Arc::clone(&node_a);
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Listen on all provided addresses by joostjager · Pull Request #644 · lightningdevkit/ldk-node · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -325,7 +325,6 @@ enum NodeError {

dictionary NodeStatus {
boolean is_running;
boolean is_listening;
BestBlock current_best_block;
u64? latest_lightning_wallet_sync_timestamp;
u64? latest_onchain_wallet_sync_timestamp;
Expand Down
3 changes: 0 additions & 3 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,6 @@ use std::collections::HashMap;
use std::convert::TryInto;
use std::default::Default;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex, Once, RwLock};
use std::time::SystemTime;
use std::{fmt, fs};
Expand DownExpand Up@@ -1133,7 +1132,6 @@ fn build_with_store_internal(
}

// Initialize the status fields.
let is_listening = Arc::new(AtomicBool::new(false));
let node_metrics = match read_node_metrics(Arc::clone(&kv_store), Arc::clone(&logger)) {
Ok(metrics) => Arc::new(RwLock::new(metrics)),
Err(e) => {
Expand DownExpand Up@@ -1734,7 +1732,6 @@ fn build_with_store_internal(
peer_store,
payment_store,
is_running,
is_listening,
node_metrics,
om_mailbox,
async_payments_role,
Expand Down
96 changes: 52 additions & 44 deletions src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,7 +101,6 @@ mod wallet;

use std::default::Default;
use std::net::ToSocketAddrs;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

Expand DownExpand Up@@ -189,7 +188,6 @@ pub struct Node {
peer_store: Arc<PeerStore<Arc<Logger>>>,
payment_store: Arc<PaymentStore>,
is_running: Arc<RwLock<bool>>,
is_listening: Arc<AtomicBool>,
Comment thread
joostjager marked this conversation as resolved.
node_metrics: Arc<RwLock<NodeMetrics>>,
om_mailbox: Option<Arc<OnionMessageMailbox>>,
async_payments_role: Option<AsyncPaymentsRole>,
Expand DownExpand Up@@ -293,9 +291,7 @@ impl Node {
if let Some(listening_addresses) = &self.config.listening_addresses {
// Setup networking
let peer_manager_connection_handler = Arc::clone(&self.peer_manager);
let mut stop_listen = self.stop_sender.subscribe();
let listening_logger = Arc::clone(&self.logger);
let listening_indicator = Arc::clone(&self.is_listening);

let mut bind_addrs = Vec::with_capacity(listening_addresses.len());

Expand All@@ -313,45 +309,62 @@ impl Node {
bind_addrs.extend(resolved_address);
}

self.runtime.spawn_cancellable_background_task(async move {
{
let listener =
tokio::net::TcpListener::bind(&*bind_addrs).await
.unwrap_or_else(|e| {
log_error!(listening_logger, "Failed to bind to listen addresses/ports - is something else already listening on it?: {}", e);
panic!(
"Failed to bind to listen address/port - is something else already listening on it?",
);
});

listening_indicator.store(true, Ordering::Release);

loop {
let peer_mgr = Arc::clone(&peer_manager_connection_handler);
tokio::select! {
_ = stop_listen.changed() => {
log_debug!(
listening_logger,
"Stopping listening to inbound connections."
let logger = Arc::clone(&listening_logger);
let listeners = self.runtime.block_on(async move {

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to block if we want to return an error.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, I see the point. I guess we need to if we want to abort on error for now, but we'll probably make start async soonish anyways.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternative is to use non-tokio binds here.

let mut listeners = Vec::new();

// Try to bind to all addresses
for addr in &*bind_addrs {
match tokio::net::TcpListener::bind(addr).await {
Ok(listener) => {
log_trace!(logger, "Listener bound to {}", addr);
listeners.push(listener);
},
Err(e) => {
log_error!(
logger,
"Failed to bind to {}: {} - is something else already listening?",
addr,
e
);
break;
}
res = listener.accept() => {
let tcp_stream = res.unwrap().0;
tokio::spawn(async move {
lightning_net_tokio::setup_inbound(
Arc::clone(&peer_mgr),
tcp_stream.into_std().unwrap(),
)
.await;
});
}
return Err(Error::InvalidSocketAddress);
},
}
}
}

listening_indicator.store(false, Ordering::Release);
});
Ok(listeners)
})?;

for listener in listeners {
let logger = Arc::clone(&listening_logger);
let peer_mgr = Arc::clone(&peer_manager_connection_handler);
let mut stop_listen = self.stop_sender.subscribe();
let runtime = Arc::clone(&self.runtime);
self.runtime.spawn_cancellable_background_task(async move {
loop {
tokio::select! {
_ = stop_listen.changed() => {
log_debug!(
logger,
"Stopping listening to inbound connections."
);
break;
}
res = listener.accept() => {
let tcp_stream = res.unwrap().0;
let peer_mgr = Arc::clone(&peer_mgr);
runtime.spawn_cancellable_background_task(async move {
lightning_net_tokio::setup_inbound(
Arc::clone(&peer_mgr),
tcp_stream.into_std().unwrap(),
)
.await;
});
}
}
}
});
}
}

// Regularly reconnect to persisted peers.
Expand DownExpand Up@@ -666,7 +679,6 @@ impl Node {
/// Returns the status of the [`Node`].
pub fn status(&self) -> NodeStatus {
let is_running = *self.is_running.read().unwrap();
let is_listening = self.is_listening.load(Ordering::Acquire);
let current_best_block = self.channel_manager.current_best_block().into();
let locked_node_metrics = self.node_metrics.read().unwrap();
let latest_lightning_wallet_sync_timestamp =
Expand All@@ -684,7 +696,6 @@ impl Node {

NodeStatus {
is_running,
is_listening,
current_best_block,
latest_lightning_wallet_sync_timestamp,
latest_onchain_wallet_sync_timestamp,
Expand DownExpand Up@@ -1495,9 +1506,6 @@ impl Drop for Node {
pub struct NodeStatus {
/// Indicates whether the [`Node`] is running.
pub is_running: bool,
/// Indicates whether the [`Node`] is listening for incoming connections on the addresses
/// configured via [`Config::listening_addresses`].
pub is_listening: bool,
/// The best block to which our Lightning wallet is currently synced.
pub current_best_block: BestBlock,
/// The timestamp, in seconds since start of the UNIX epoch, when we last successfully synced
Expand Down
2 changes: 1 addition & 1 deletion tests/common/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -195,7 +195,7 @@ pub(crate) fn random_storage_path() -> PathBuf {

pub(crate) fn random_port() -> u16 {
let mut rng = thread_rng();
rng.gen_range(5000..65535)
rng.gen_range(5000..32768)
}

pub(crate) fn random_listening_addresses() -> Vec<SocketAddress> {
Expand Down
24 changes: 15 additions & 9 deletions tests/integration_tests_rust.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -817,6 +817,21 @@ fn sign_verify_msg() {
assert!(node.verify_signature(msg, sig.as_str(), &pkey));
}

#[test]
fn connection_multi_listen() {
let (_bitcoind, electrsd) = setup_bitcoind_and_electrsd();
let chain_source = TestChainSource::Esplora(&electrsd);
let (node_a, node_b) = setup_two_nodes(&chain_source, false, false, false);

let node_id_b = node_b.node_id();

let node_addrs_b = node_b.listening_addresses().unwrap();
for node_addr_b in &node_addrs_b {
node_a.connect(node_id_b, node_addr_b.clone(), false).unwrap();
node_a.disconnect(node_id_b).unwrap();
}
}

#[test]
fn connection_restart_behavior() {
do_connection_restart_behavior(true);
Expand All@@ -832,11 +847,6 @@ fn do_connection_restart_behavior(persist: bool) {
let node_id_b = node_b.node_id();

let node_addr_b = node_b.listening_addresses().unwrap().first().unwrap().clone();

while !node_b.status().is_listening {
std::thread::sleep(std::time::Duration::from_millis(10));
}

node_a.connect(node_id_b, node_addr_b, persist).unwrap();

let peer_details_a = node_a.list_peers().first().unwrap().clone();
Expand DownExpand Up@@ -886,10 +896,6 @@ fn concurrent_connections_succeed() {
let node_id_b = node_b.node_id();
let node_addr_b = node_b.listening_addresses().unwrap().first().unwrap().clone();

while !node_b.status().is_listening {
std::thread::sleep(std::time::Duration::from_millis(10));
}

let mut handles = Vec::new();
for _ in 0..10 {
let thread_node = Arc::clone(&node_a);
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Listen on all provided addresses by joostjager · Pull Request #644 · lightningdevkit/ldk-node · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -325,7 +325,6 @@ enum NodeError {

dictionary NodeStatus {
boolean is_running;
boolean is_listening;
BestBlock current_best_block;
u64? latest_lightning_wallet_sync_timestamp;
u64? latest_onchain_wallet_sync_timestamp;
Expand Down
3 changes: 0 additions & 3 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,6 @@ use std::collections::HashMap;
use std::convert::TryInto;
use std::default::Default;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex, Once, RwLock};
use std::time::SystemTime;
use std::{fmt, fs};
Expand DownExpand Up@@ -1133,7 +1132,6 @@ fn build_with_store_internal(
}

// Initialize the status fields.
let is_listening = Arc::new(AtomicBool::new(false));
let node_metrics = match read_node_metrics(Arc::clone(&kv_store), Arc::clone(&logger)) {
Ok(metrics) => Arc::new(RwLock::new(metrics)),
Err(e) => {
Expand DownExpand Up@@ -1734,7 +1732,6 @@ fn build_with_store_internal(
peer_store,
payment_store,
is_running,
is_listening,
node_metrics,
om_mailbox,
async_payments_role,
Expand Down
96 changes: 52 additions & 44 deletions src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,7 +101,6 @@ mod wallet;

use std::default::Default;
use std::net::ToSocketAddrs;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

Expand DownExpand Up@@ -189,7 +188,6 @@ pub struct Node {
peer_store: Arc<PeerStore<Arc<Logger>>>,
payment_store: Arc<PaymentStore>,
is_running: Arc<RwLock<bool>>,
is_listening: Arc<AtomicBool>,
Comment thread
joostjager marked this conversation as resolved.
node_metrics: Arc<RwLock<NodeMetrics>>,
om_mailbox: Option<Arc<OnionMessageMailbox>>,
async_payments_role: Option<AsyncPaymentsRole>,
Expand DownExpand Up@@ -293,9 +291,7 @@ impl Node {
if let Some(listening_addresses) = &self.config.listening_addresses {
// Setup networking
let peer_manager_connection_handler = Arc::clone(&self.peer_manager);
let mut stop_listen = self.stop_sender.subscribe();
let listening_logger = Arc::clone(&self.logger);
let listening_indicator = Arc::clone(&self.is_listening);

let mut bind_addrs = Vec::with_capacity(listening_addresses.len());

Expand All@@ -313,45 +309,62 @@ impl Node {
bind_addrs.extend(resolved_address);
}

self.runtime.spawn_cancellable_background_task(async move {
{
let listener =
tokio::net::TcpListener::bind(&*bind_addrs).await
.unwrap_or_else(|e| {
log_error!(listening_logger, "Failed to bind to listen addresses/ports - is something else already listening on it?: {}", e);
panic!(
"Failed to bind to listen address/port - is something else already listening on it?",
);
});

listening_indicator.store(true, Ordering::Release);

loop {
let peer_mgr = Arc::clone(&peer_manager_connection_handler);
tokio::select! {
_ = stop_listen.changed() => {
log_debug!(
listening_logger,
"Stopping listening to inbound connections."
let logger = Arc::clone(&listening_logger);
let listeners = self.runtime.block_on(async move {

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to block if we want to return an error.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, I see the point. I guess we need to if we want to abort on error for now, but we'll probably make start async soonish anyways.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternative is to use non-tokio binds here.

let mut listeners = Vec::new();

// Try to bind to all addresses
for addr in &*bind_addrs {
match tokio::net::TcpListener::bind(addr).await {
Ok(listener) => {
log_trace!(logger, "Listener bound to {}", addr);
listeners.push(listener);
},
Err(e) => {
log_error!(
logger,
"Failed to bind to {}: {} - is something else already listening?",
addr,
e
);
break;
}
res = listener.accept() => {
let tcp_stream = res.unwrap().0;
tokio::spawn(async move {
lightning_net_tokio::setup_inbound(
Arc::clone(&peer_mgr),
tcp_stream.into_std().unwrap(),
)
.await;
});
}
return Err(Error::InvalidSocketAddress);
},
}
}
}

listening_indicator.store(false, Ordering::Release);
});
Ok(listeners)
})?;

for listener in listeners {
let logger = Arc::clone(&listening_logger);
let peer_mgr = Arc::clone(&peer_manager_connection_handler);
let mut stop_listen = self.stop_sender.subscribe();
let runtime = Arc::clone(&self.runtime);
self.runtime.spawn_cancellable_background_task(async move {
loop {
tokio::select! {
_ = stop_listen.changed() => {
log_debug!(
logger,
"Stopping listening to inbound connections."
);
break;
}
res = listener.accept() => {
let tcp_stream = res.unwrap().0;
let peer_mgr = Arc::clone(&peer_mgr);
runtime.spawn_cancellable_background_task(async move {
lightning_net_tokio::setup_inbound(
Arc::clone(&peer_mgr),
tcp_stream.into_std().unwrap(),
)
.await;
});
}
}
}
});
}
}

// Regularly reconnect to persisted peers.
Expand DownExpand Up@@ -666,7 +679,6 @@ impl Node {
/// Returns the status of the [`Node`].
pub fn status(&self) -> NodeStatus {
let is_running = *self.is_running.read().unwrap();
let is_listening = self.is_listening.load(Ordering::Acquire);
let current_best_block = self.channel_manager.current_best_block().into();
let locked_node_metrics = self.node_metrics.read().unwrap();
let latest_lightning_wallet_sync_timestamp =
Expand All@@ -684,7 +696,6 @@ impl Node {

NodeStatus {
is_running,
is_listening,
current_best_block,
latest_lightning_wallet_sync_timestamp,
latest_onchain_wallet_sync_timestamp,
Expand DownExpand Up@@ -1495,9 +1506,6 @@ impl Drop for Node {
pub struct NodeStatus {
/// Indicates whether the [`Node`] is running.
pub is_running: bool,
/// Indicates whether the [`Node`] is listening for incoming connections on the addresses
/// configured via [`Config::listening_addresses`].
pub is_listening: bool,
/// The best block to which our Lightning wallet is currently synced.
pub current_best_block: BestBlock,
/// The timestamp, in seconds since start of the UNIX epoch, when we last successfully synced
Expand Down
2 changes: 1 addition & 1 deletion tests/common/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -195,7 +195,7 @@ pub(crate) fn random_storage_path() -> PathBuf {

pub(crate) fn random_port() -> u16 {
let mut rng = thread_rng();
rng.gen_range(5000..65535)
rng.gen_range(5000..32768)
}

pub(crate) fn random_listening_addresses() -> Vec<SocketAddress> {
Expand Down
24 changes: 15 additions & 9 deletions tests/integration_tests_rust.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -817,6 +817,21 @@ fn sign_verify_msg() {
assert!(node.verify_signature(msg, sig.as_str(), &pkey));
}

#[test]
fn connection_multi_listen() {
let (_bitcoind, electrsd) = setup_bitcoind_and_electrsd();
let chain_source = TestChainSource::Esplora(&electrsd);
let (node_a, node_b) = setup_two_nodes(&chain_source, false, false, false);

let node_id_b = node_b.node_id();

let node_addrs_b = node_b.listening_addresses().unwrap();
for node_addr_b in &node_addrs_b {
node_a.connect(node_id_b, node_addr_b.clone(), false).unwrap();
node_a.disconnect(node_id_b).unwrap();
}
}

#[test]
fn connection_restart_behavior() {
do_connection_restart_behavior(true);
Expand All@@ -832,11 +847,6 @@ fn do_connection_restart_behavior(persist: bool) {
let node_id_b = node_b.node_id();

let node_addr_b = node_b.listening_addresses().unwrap().first().unwrap().clone();

while !node_b.status().is_listening {
std::thread::sleep(std::time::Duration::from_millis(10));
}

node_a.connect(node_id_b, node_addr_b, persist).unwrap();

let peer_details_a = node_a.list_peers().first().unwrap().clone();
Expand DownExpand Up@@ -886,10 +896,6 @@ fn concurrent_connections_succeed() {
let node_id_b = node_b.node_id();
let node_addr_b = node_b.listening_addresses().unwrap().first().unwrap().clone();

while !node_b.status().is_listening {
std::thread::sleep(std::time::Duration::from_millis(10));
}

let mut handles = Vec::new();
for _ in 0..10 {
let thread_node = Arc::clone(&node_a);
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' Listen on all provided addresses by joostjager · Pull Request #644 · lightningdevkit/ldk-node · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -325,7 +325,6 @@ enum NodeError {

dictionary NodeStatus {
boolean is_running;
boolean is_listening;
BestBlock current_best_block;
u64? latest_lightning_wallet_sync_timestamp;
u64? latest_onchain_wallet_sync_timestamp;
Expand Down
3 changes: 0 additions & 3 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,6 @@ use std::collections::HashMap;
use std::convert::TryInto;
use std::default::Default;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex, Once, RwLock};
use std::time::SystemTime;
use std::{fmt, fs};
Expand DownExpand Up@@ -1133,7 +1132,6 @@ fn build_with_store_internal(
}

// Initialize the status fields.
let is_listening = Arc::new(AtomicBool::new(false));
let node_metrics = match read_node_metrics(Arc::clone(&kv_store), Arc::clone(&logger)) {
Ok(metrics) => Arc::new(RwLock::new(metrics)),
Err(e) => {
Expand DownExpand Up@@ -1734,7 +1732,6 @@ fn build_with_store_internal(
peer_store,
payment_store,
is_running,
is_listening,
node_metrics,
om_mailbox,
async_payments_role,
Expand Down
96 changes: 52 additions & 44 deletions src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,7 +101,6 @@ mod wallet;

use std::default::Default;
use std::net::ToSocketAddrs;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

Expand DownExpand Up@@ -189,7 +188,6 @@ pub struct Node {
peer_store: Arc<PeerStore<Arc<Logger>>>,
payment_store: Arc<PaymentStore>,
is_running: Arc<RwLock<bool>>,
is_listening: Arc<AtomicBool>,
Comment thread
joostjager marked this conversation as resolved.
node_metrics: Arc<RwLock<NodeMetrics>>,
om_mailbox: Option<Arc<OnionMessageMailbox>>,
async_payments_role: Option<AsyncPaymentsRole>,
Expand DownExpand Up@@ -293,9 +291,7 @@ impl Node {
if let Some(listening_addresses) = &self.config.listening_addresses {
// Setup networking
let peer_manager_connection_handler = Arc::clone(&self.peer_manager);
let mut stop_listen = self.stop_sender.subscribe();
let listening_logger = Arc::clone(&self.logger);
let listening_indicator = Arc::clone(&self.is_listening);

let mut bind_addrs = Vec::with_capacity(listening_addresses.len());

Expand All@@ -313,45 +309,62 @@ impl Node {
bind_addrs.extend(resolved_address);
}

self.runtime.spawn_cancellable_background_task(async move {
{
let listener =
tokio::net::TcpListener::bind(&*bind_addrs).await
.unwrap_or_else(|e| {
log_error!(listening_logger, "Failed to bind to listen addresses/ports - is something else already listening on it?: {}", e);
panic!(
"Failed to bind to listen address/port - is something else already listening on it?",
);
});

listening_indicator.store(true, Ordering::Release);

loop {
let peer_mgr = Arc::clone(&peer_manager_connection_handler);
tokio::select! {
_ = stop_listen.changed() => {
log_debug!(
listening_logger,
"Stopping listening to inbound connections."
let logger = Arc::clone(&listening_logger);
let listeners = self.runtime.block_on(async move {

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to block if we want to return an error.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, I see the point. I guess we need to if we want to abort on error for now, but we'll probably make start async soonish anyways.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternative is to use non-tokio binds here.

let mut listeners = Vec::new();

// Try to bind to all addresses
for addr in &*bind_addrs {
match tokio::net::TcpListener::bind(addr).await {
Ok(listener) => {
log_trace!(logger, "Listener bound to {}", addr);
listeners.push(listener);
},
Err(e) => {
log_error!(
logger,
"Failed to bind to {}: {} - is something else already listening?",
addr,
e
);
break;
}
res = listener.accept() => {
let tcp_stream = res.unwrap().0;
tokio::spawn(async move {
lightning_net_tokio::setup_inbound(
Arc::clone(&peer_mgr),
tcp_stream.into_std().unwrap(),
)
.await;
});
}
return Err(Error::InvalidSocketAddress);
},
}
}
}

listening_indicator.store(false, Ordering::Release);
});
Ok(listeners)
})?;

for listener in listeners {
let logger = Arc::clone(&listening_logger);
let peer_mgr = Arc::clone(&peer_manager_connection_handler);
let mut stop_listen = self.stop_sender.subscribe();
let runtime = Arc::clone(&self.runtime);
self.runtime.spawn_cancellable_background_task(async move {
loop {
tokio::select! {
_ = stop_listen.changed() => {
log_debug!(
logger,
"Stopping listening to inbound connections."
);
break;
}
res = listener.accept() => {
let tcp_stream = res.unwrap().0;
let peer_mgr = Arc::clone(&peer_mgr);
runtime.spawn_cancellable_background_task(async move {
lightning_net_tokio::setup_inbound(
Arc::clone(&peer_mgr),
tcp_stream.into_std().unwrap(),
)
.await;
});
}
}
}
});
}
}

// Regularly reconnect to persisted peers.
Expand DownExpand Up@@ -666,7 +679,6 @@ impl Node {
/// Returns the status of the [`Node`].
pub fn status(&self) -> NodeStatus {
let is_running = *self.is_running.read().unwrap();
let is_listening = self.is_listening.load(Ordering::Acquire);
let current_best_block = self.channel_manager.current_best_block().into();
let locked_node_metrics = self.node_metrics.read().unwrap();
let latest_lightning_wallet_sync_timestamp =
Expand All@@ -684,7 +696,6 @@ impl Node {

NodeStatus {
is_running,
is_listening,
current_best_block,
latest_lightning_wallet_sync_timestamp,
latest_onchain_wallet_sync_timestamp,
Expand DownExpand Up@@ -1495,9 +1506,6 @@ impl Drop for Node {
pub struct NodeStatus {
/// Indicates whether the [`Node`] is running.
pub is_running: bool,
/// Indicates whether the [`Node`] is listening for incoming connections on the addresses
/// configured via [`Config::listening_addresses`].
pub is_listening: bool,
/// The best block to which our Lightning wallet is currently synced.
pub current_best_block: BestBlock,
/// The timestamp, in seconds since start of the UNIX epoch, when we last successfully synced
Expand Down
2 changes: 1 addition & 1 deletion tests/common/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -195,7 +195,7 @@ pub(crate) fn random_storage_path() -> PathBuf {

pub(crate) fn random_port() -> u16 {
let mut rng = thread_rng();
rng.gen_range(5000..65535)
rng.gen_range(5000..32768)
}

pub(crate) fn random_listening_addresses() -> Vec<SocketAddress> {
Expand Down
24 changes: 15 additions & 9 deletions tests/integration_tests_rust.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -817,6 +817,21 @@ fn sign_verify_msg() {
assert!(node.verify_signature(msg, sig.as_str(), &pkey));
}

#[test]
fn connection_multi_listen() {
let (_bitcoind, electrsd) = setup_bitcoind_and_electrsd();
let chain_source = TestChainSource::Esplora(&electrsd);
let (node_a, node_b) = setup_two_nodes(&chain_source, false, false, false);

let node_id_b = node_b.node_id();

let node_addrs_b = node_b.listening_addresses().unwrap();
for node_addr_b in &node_addrs_b {
node_a.connect(node_id_b, node_addr_b.clone(), false).unwrap();
node_a.disconnect(node_id_b).unwrap();
}
}

#[test]
fn connection_restart_behavior() {
do_connection_restart_behavior(true);
Expand All@@ -832,11 +847,6 @@ fn do_connection_restart_behavior(persist: bool) {
let node_id_b = node_b.node_id();

let node_addr_b = node_b.listening_addresses().unwrap().first().unwrap().clone();

while !node_b.status().is_listening {
std::thread::sleep(std::time::Duration::from_millis(10));
}

node_a.connect(node_id_b, node_addr_b, persist).unwrap();

let peer_details_a = node_a.list_peers().first().unwrap().clone();
Expand DownExpand Up@@ -886,10 +896,6 @@ fn concurrent_connections_succeed() {
let node_id_b = node_b.node_id();
let node_addr_b = node_b.listening_addresses().unwrap().first().unwrap().clone();

while !node_b.status().is_listening {
std::thread::sleep(std::time::Duration::from_millis(10));
}

let mut handles = Vec::new();
for _ in 0..10 {
let thread_node = Arc::clone(&node_a);
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Listen on all provided addresses by joostjager · Pull Request #644 · lightningdevkit/ldk-node · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -325,7 +325,6 @@ enum NodeError {

dictionary NodeStatus {
boolean is_running;
boolean is_listening;
BestBlock current_best_block;
u64? latest_lightning_wallet_sync_timestamp;
u64? latest_onchain_wallet_sync_timestamp;
Expand Down
3 changes: 0 additions & 3 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,6 @@ use std::collections::HashMap;
use std::convert::TryInto;
use std::default::Default;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex, Once, RwLock};
use std::time::SystemTime;
use std::{fmt, fs};
Expand DownExpand Up@@ -1133,7 +1132,6 @@ fn build_with_store_internal(
}

// Initialize the status fields.
let is_listening = Arc::new(AtomicBool::new(false));
let node_metrics = match read_node_metrics(Arc::clone(&kv_store), Arc::clone(&logger)) {
Ok(metrics) => Arc::new(RwLock::new(metrics)),
Err(e) => {
Expand DownExpand Up@@ -1734,7 +1732,6 @@ fn build_with_store_internal(
peer_store,
payment_store,
is_running,
is_listening,
node_metrics,
om_mailbox,
async_payments_role,
Expand Down
96 changes: 52 additions & 44 deletions src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,7 +101,6 @@ mod wallet;

use std::default::Default;
use std::net::ToSocketAddrs;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

Expand DownExpand Up@@ -189,7 +188,6 @@ pub struct Node {
peer_store: Arc<PeerStore<Arc<Logger>>>,
payment_store: Arc<PaymentStore>,
is_running: Arc<RwLock<bool>>,
is_listening: Arc<AtomicBool>,
Comment thread
joostjager marked this conversation as resolved.
node_metrics: Arc<RwLock<NodeMetrics>>,
om_mailbox: Option<Arc<OnionMessageMailbox>>,
async_payments_role: Option<AsyncPaymentsRole>,
Expand DownExpand Up@@ -293,9 +291,7 @@ impl Node {
if let Some(listening_addresses) = &self.config.listening_addresses {
// Setup networking
let peer_manager_connection_handler = Arc::clone(&self.peer_manager);
let mut stop_listen = self.stop_sender.subscribe();
let listening_logger = Arc::clone(&self.logger);
let listening_indicator = Arc::clone(&self.is_listening);

let mut bind_addrs = Vec::with_capacity(listening_addresses.len());

Expand All@@ -313,45 +309,62 @@ impl Node {
bind_addrs.extend(resolved_address);
}

self.runtime.spawn_cancellable_background_task(async move {
{
let listener =
tokio::net::TcpListener::bind(&*bind_addrs).await
.unwrap_or_else(|e| {
log_error!(listening_logger, "Failed to bind to listen addresses/ports - is something else already listening on it?: {}", e);
panic!(
"Failed to bind to listen address/port - is something else already listening on it?",
);
});

listening_indicator.store(true, Ordering::Release);

loop {
let peer_mgr = Arc::clone(&peer_manager_connection_handler);
tokio::select! {
_ = stop_listen.changed() => {
log_debug!(
listening_logger,
"Stopping listening to inbound connections."
let logger = Arc::clone(&listening_logger);
let listeners = self.runtime.block_on(async move {

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to block if we want to return an error.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, I see the point. I guess we need to if we want to abort on error for now, but we'll probably make start async soonish anyways.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternative is to use non-tokio binds here.

let mut listeners = Vec::new();

// Try to bind to all addresses
for addr in &*bind_addrs {
match tokio::net::TcpListener::bind(addr).await {
Ok(listener) => {
log_trace!(logger, "Listener bound to {}", addr);
listeners.push(listener);
},
Err(e) => {
log_error!(
logger,
"Failed to bind to {}: {} - is something else already listening?",
addr,
e
);
break;
}
res = listener.accept() => {
let tcp_stream = res.unwrap().0;
tokio::spawn(async move {
lightning_net_tokio::setup_inbound(
Arc::clone(&peer_mgr),
tcp_stream.into_std().unwrap(),
)
.await;
});
}
return Err(Error::InvalidSocketAddress);
},
}
}
}

listening_indicator.store(false, Ordering::Release);
});
Ok(listeners)
})?;

for listener in listeners {
let logger = Arc::clone(&listening_logger);
let peer_mgr = Arc::clone(&peer_manager_connection_handler);
let mut stop_listen = self.stop_sender.subscribe();
let runtime = Arc::clone(&self.runtime);
self.runtime.spawn_cancellable_background_task(async move {
loop {
tokio::select! {
_ = stop_listen.changed() => {
log_debug!(
logger,
"Stopping listening to inbound connections."
);
break;
}
res = listener.accept() => {
let tcp_stream = res.unwrap().0;
let peer_mgr = Arc::clone(&peer_mgr);
runtime.spawn_cancellable_background_task(async move {
lightning_net_tokio::setup_inbound(
Arc::clone(&peer_mgr),
tcp_stream.into_std().unwrap(),
)
.await;
});
}
}
}
});
}
}

// Regularly reconnect to persisted peers.
Expand DownExpand Up@@ -666,7 +679,6 @@ impl Node {
/// Returns the status of the [`Node`].
pub fn status(&self) -> NodeStatus {
let is_running = *self.is_running.read().unwrap();
let is_listening = self.is_listening.load(Ordering::Acquire);
let current_best_block = self.channel_manager.current_best_block().into();
let locked_node_metrics = self.node_metrics.read().unwrap();
let latest_lightning_wallet_sync_timestamp =
Expand All@@ -684,7 +696,6 @@ impl Node {

NodeStatus {
is_running,
is_listening,
current_best_block,
latest_lightning_wallet_sync_timestamp,
latest_onchain_wallet_sync_timestamp,
Expand DownExpand Up@@ -1495,9 +1506,6 @@ impl Drop for Node {
pub struct NodeStatus {
/// Indicates whether the [`Node`] is running.
pub is_running: bool,
/// Indicates whether the [`Node`] is listening for incoming connections on the addresses
/// configured via [`Config::listening_addresses`].
pub is_listening: bool,
/// The best block to which our Lightning wallet is currently synced.
pub current_best_block: BestBlock,
/// The timestamp, in seconds since start of the UNIX epoch, when we last successfully synced
Expand Down
2 changes: 1 addition & 1 deletion tests/common/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -195,7 +195,7 @@ pub(crate) fn random_storage_path() -> PathBuf {

pub(crate) fn random_port() -> u16 {
let mut rng = thread_rng();
rng.gen_range(5000..65535)
rng.gen_range(5000..32768)
}

pub(crate) fn random_listening_addresses() -> Vec<SocketAddress> {
Expand Down
24 changes: 15 additions & 9 deletions tests/integration_tests_rust.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -817,6 +817,21 @@ fn sign_verify_msg() {
assert!(node.verify_signature(msg, sig.as_str(), &pkey));
}

#[test]
fn connection_multi_listen() {
let (_bitcoind, electrsd) = setup_bitcoind_and_electrsd();
let chain_source = TestChainSource::Esplora(&electrsd);
let (node_a, node_b) = setup_two_nodes(&chain_source, false, false, false);

let node_id_b = node_b.node_id();

let node_addrs_b = node_b.listening_addresses().unwrap();
for node_addr_b in &node_addrs_b {
node_a.connect(node_id_b, node_addr_b.clone(), false).unwrap();
node_a.disconnect(node_id_b).unwrap();
}
}

#[test]
fn connection_restart_behavior() {
do_connection_restart_behavior(true);
Expand All@@ -832,11 +847,6 @@ fn do_connection_restart_behavior(persist: bool) {
let node_id_b = node_b.node_id();

let node_addr_b = node_b.listening_addresses().unwrap().first().unwrap().clone();

while !node_b.status().is_listening {
std::thread::sleep(std::time::Duration::from_millis(10));
}

node_a.connect(node_id_b, node_addr_b, persist).unwrap();

let peer_details_a = node_a.list_peers().first().unwrap().clone();
Expand DownExpand Up@@ -886,10 +896,6 @@ fn concurrent_connections_succeed() {
let node_id_b = node_b.node_id();
let node_addr_b = node_b.listening_addresses().unwrap().first().unwrap().clone();

while !node_b.status().is_listening {
std::thread::sleep(std::time::Duration::from_millis(10));
}

let mut handles = Vec::new();
for _ in 0..10 {
let thread_node = Arc::clone(&node_a);
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); Listen on all provided addresses by joostjager · Pull Request #644 · lightningdevkit/ldk-node · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -325,7 +325,6 @@ enum NodeError {

dictionary NodeStatus {
boolean is_running;
boolean is_listening;
BestBlock current_best_block;
u64? latest_lightning_wallet_sync_timestamp;
u64? latest_onchain_wallet_sync_timestamp;
Expand Down
3 changes: 0 additions & 3 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,6 @@ use std::collections::HashMap;
use std::convert::TryInto;
use std::default::Default;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex, Once, RwLock};
use std::time::SystemTime;
use std::{fmt, fs};
Expand DownExpand Up@@ -1133,7 +1132,6 @@ fn build_with_store_internal(
}

// Initialize the status fields.
let is_listening = Arc::new(AtomicBool::new(false));
let node_metrics = match read_node_metrics(Arc::clone(&kv_store), Arc::clone(&logger)) {
Ok(metrics) => Arc::new(RwLock::new(metrics)),
Err(e) => {
Expand DownExpand Up@@ -1734,7 +1732,6 @@ fn build_with_store_internal(
peer_store,
payment_store,
is_running,
is_listening,
node_metrics,
om_mailbox,
async_payments_role,
Expand Down
96 changes: 52 additions & 44 deletions src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -101,7 +101,6 @@ mod wallet;

use std::default::Default;
use std::net::ToSocketAddrs;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

Expand DownExpand Up@@ -189,7 +188,6 @@ pub struct Node {
peer_store: Arc<PeerStore<Arc<Logger>>>,
payment_store: Arc<PaymentStore>,
is_running: Arc<RwLock<bool>>,
is_listening: Arc<AtomicBool>,
Comment thread
joostjager marked this conversation as resolved.
node_metrics: Arc<RwLock<NodeMetrics>>,
om_mailbox: Option<Arc<OnionMessageMailbox>>,
async_payments_role: Option<AsyncPaymentsRole>,
Expand DownExpand Up@@ -293,9 +291,7 @@ impl Node {
if let Some(listening_addresses) = &self.config.listening_addresses {
// Setup networking
let peer_manager_connection_handler = Arc::clone(&self.peer_manager);
let mut stop_listen = self.stop_sender.subscribe();
let listening_logger = Arc::clone(&self.logger);
let listening_indicator = Arc::clone(&self.is_listening);

let mut bind_addrs = Vec::with_capacity(listening_addresses.len());

Expand All@@ -313,45 +309,62 @@ impl Node {
bind_addrs.extend(resolved_address);
}

self.runtime.spawn_cancellable_background_task(async move {
{
let listener =
tokio::net::TcpListener::bind(&*bind_addrs).await
.unwrap_or_else(|e| {
log_error!(listening_logger, "Failed to bind to listen addresses/ports - is something else already listening on it?: {}", e);
panic!(
"Failed to bind to listen address/port - is something else already listening on it?",
);
});

listening_indicator.store(true, Ordering::Release);

loop {
let peer_mgr = Arc::clone(&peer_manager_connection_handler);
tokio::select! {
_ = stop_listen.changed() => {
log_debug!(
listening_logger,
"Stopping listening to inbound connections."
let logger = Arc::clone(&listening_logger);
let listeners = self.runtime.block_on(async move {

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to block if we want to return an error.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, I see the point. I guess we need to if we want to abort on error for now, but we'll probably make start async soonish anyways.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternative is to use non-tokio binds here.

let mut listeners = Vec::new();

// Try to bind to all addresses
for addr in &*bind_addrs {
match tokio::net::TcpListener::bind(addr).await {
Ok(listener) => {
log_trace!(logger, "Listener bound to {}", addr);
listeners.push(listener);
},
Err(e) => {
log_error!(
logger,
"Failed to bind to {}: {} - is something else already listening?",
addr,
e
);
break;
}
res = listener.accept() => {
let tcp_stream = res.unwrap().0;
tokio::spawn(async move {
lightning_net_tokio::setup_inbound(
Arc::clone(&peer_mgr),
tcp_stream.into_std().unwrap(),
)
.await;
});
}
return Err(Error::InvalidSocketAddress);
},
}
}
}

listening_indicator.store(false, Ordering::Release);
});
Ok(listeners)
})?;

for listener in listeners {
let logger = Arc::clone(&listening_logger);
let peer_mgr = Arc::clone(&peer_manager_connection_handler);
let mut stop_listen = self.stop_sender.subscribe();
let runtime = Arc::clone(&self.runtime);
self.runtime.spawn_cancellable_background_task(async move {
loop {
tokio::select! {
_ = stop_listen.changed() => {
log_debug!(
logger,
"Stopping listening to inbound connections."
);
break;
}
res = listener.accept() => {
let tcp_stream = res.unwrap().0;
let peer_mgr = Arc::clone(&peer_mgr);
runtime.spawn_cancellable_background_task(async move {
lightning_net_tokio::setup_inbound(
Arc::clone(&peer_mgr),
tcp_stream.into_std().unwrap(),
)
.await;
});
}
}
}
});
}
}

// Regularly reconnect to persisted peers.
Expand DownExpand Up@@ -666,7 +679,6 @@ impl Node {
/// Returns the status of the [`Node`].
pub fn status(&self) -> NodeStatus {
let is_running = *self.is_running.read().unwrap();
let is_listening = self.is_listening.load(Ordering::Acquire);
let current_best_block = self.channel_manager.current_best_block().into();
let locked_node_metrics = self.node_metrics.read().unwrap();
let latest_lightning_wallet_sync_timestamp =
Expand All@@ -684,7 +696,6 @@ impl Node {

NodeStatus {
is_running,
is_listening,
current_best_block,
latest_lightning_wallet_sync_timestamp,
latest_onchain_wallet_sync_timestamp,
Expand DownExpand Up@@ -1495,9 +1506,6 @@ impl Drop for Node {
pub struct NodeStatus {
/// Indicates whether the [`Node`] is running.
pub is_running: bool,
/// Indicates whether the [`Node`] is listening for incoming connections on the addresses
/// configured via [`Config::listening_addresses`].
pub is_listening: bool,
/// The best block to which our Lightning wallet is currently synced.
pub current_best_block: BestBlock,
/// The timestamp, in seconds since start of the UNIX epoch, when we last successfully synced
Expand Down
2 changes: 1 addition & 1 deletion tests/common/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -195,7 +195,7 @@ pub(crate) fn random_storage_path() -> PathBuf {

pub(crate) fn random_port() -> u16 {
let mut rng = thread_rng();
rng.gen_range(5000..65535)
rng.gen_range(5000..32768)
}

pub(crate) fn random_listening_addresses() -> Vec<SocketAddress> {
Expand Down
24 changes: 15 additions & 9 deletions tests/integration_tests_rust.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -817,6 +817,21 @@ fn sign_verify_msg() {
assert!(node.verify_signature(msg, sig.as_str(), &pkey));
}

#[test]
fn connection_multi_listen() {
let (_bitcoind, electrsd) = setup_bitcoind_and_electrsd();
let chain_source = TestChainSource::Esplora(&electrsd);
let (node_a, node_b) = setup_two_nodes(&chain_source, false, false, false);

let node_id_b = node_b.node_id();

let node_addrs_b = node_b.listening_addresses().unwrap();
for node_addr_b in &node_addrs_b {
node_a.connect(node_id_b, node_addr_b.clone(), false).unwrap();
node_a.disconnect(node_id_b).unwrap();
}
}

#[test]
fn connection_restart_behavior() {
do_connection_restart_behavior(true);
Expand All@@ -832,11 +847,6 @@ fn do_connection_restart_behavior(persist: bool) {
let node_id_b = node_b.node_id();

let node_addr_b = node_b.listening_addresses().unwrap().first().unwrap().clone();

while !node_b.status().is_listening {
std::thread::sleep(std::time::Duration::from_millis(10));
}

node_a.connect(node_id_b, node_addr_b, persist).unwrap();

let peer_details_a = node_a.list_peers().first().unwrap().clone();
Expand DownExpand Up@@ -886,10 +896,6 @@ fn concurrent_connections_succeed() {
let node_id_b = node_b.node_id();
let node_addr_b = node_b.listening_addresses().unwrap().first().unwrap().clone();

while !node_b.status().is_listening {
std::thread::sleep(std::time::Duration::from_millis(10));
}

let mut handles = Vec::new();
for _ in 0..10 {
let thread_node = Arc::clone(&node_a);
Expand Down
Loading