1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
//! Bootstrap node discovery and connection logic.
//!
//! This module handles initial connection to bootstrap nodes with
//! retry logic and peer cache integration.
use crate::error::{NetworkError, NetworkResult};
use crate::network::NetworkNode;
use std::net::SocketAddr;
use std::time::Duration;
use tokio::time::{sleep, timeout};
/// Bootstrap configuration for connecting to initial peers.
///
/// Controls retry behavior and connection strategy for bootstrap nodes.
#[derive(Debug, Clone)]
pub struct BootstrapConfig {
/// Number of retry attempts for each bootstrap node.
pub max_retries: u32,
/// Backoff multiplier for exponential backoff (default 2.0).
pub backoff_multiplier: f64,
/// Initial backoff duration.
pub initial_backoff: Duration,
/// Maximum backoff duration.
pub max_backoff: Duration,
/// Per-attempt dial timeout (issue #123). Bounds each `connect_addr`
/// call so a black-holed bootstrap address fails fast and the retry
/// loop rotates to the next peer instead of stalling indefinitely.
/// Mirrors the timeout wrapper applied at every `connect_addr` /
/// `connect_cached_peer` call site in `lib.rs`.
pub dial_timeout: Duration,
}
impl Default for BootstrapConfig {
fn default() -> Self {
Self {
max_retries: 3,
backoff_multiplier: 2.0,
initial_backoff: Duration::from_millis(100),
max_backoff: Duration::from_secs(5),
dial_timeout: Duration::from_secs(10),
}
}
}
/// Bootstrap node connector with retry logic.
///
/// Handles discovery and connection to bootstrap nodes with exponential backoff.
pub struct BootstrapConnector {
config: BootstrapConfig,
}
impl BootstrapConnector {
/// Create a new bootstrap connector with default configuration.
pub fn new() -> Self {
Self {
config: BootstrapConfig::default(),
}
}
/// Create a bootstrap connector with custom configuration.
///
/// # Arguments
///
/// * `config` - Bootstrap configuration with retry parameters.
pub fn with_config(config: BootstrapConfig) -> Self {
Self { config }
}
/// Connect to a bootstrap node with exponential backoff retry.
///
/// # Arguments
///
/// * `node` - The network node to use for connection.
/// * `addr` - Address of the bootstrap node.
///
/// # Returns
///
/// Ok with the peer ID on success.
///
/// # Errors
///
/// Returns error if all retry attempts fail.
pub async fn connect_with_retry(
&self,
node: &NetworkNode,
addr: SocketAddr,
) -> NetworkResult<()> {
let mut backoff = self.config.initial_backoff;
let mut attempt = 0;
loop {
// Issue #123: bound the dial. `connect_addr` has no reliable
// internal timeout (every lib.rs call site wraps it), so without
// this a single black-holed bootstrap address would stall the
// retry loop — the backoff `sleep` below only runs after a
// *returned* error. A timeout is treated as a retryable failure
// so the existing capped backoff proceeds to the next
// attempt/peer unchanged.
match timeout(self.config.dial_timeout, node.connect_addr(addr)).await {
Ok(Ok(_peer_id)) => {
return Ok(());
}
Ok(Err(e)) => {
attempt += 1;
if attempt >= self.config.max_retries {
return Err(NetworkError::ConnectionFailed(format!(
"Bootstrap connection to {addr} failed after {attempt} attempts: {e}"
)));
}
tracing::debug!(
target: "x0x::bootstrap",
%addr,
attempt,
error = %e,
"bootstrap dial failed; backing off"
);
}
Err(_elapsed) => {
attempt += 1;
if attempt >= self.config.max_retries {
return Err(NetworkError::ConnectionFailed(format!(
"Bootstrap connection to {addr} timed out after {attempt} attempts \
(dial timeout {:?})",
self.config.dial_timeout
)));
}
tracing::warn!(
target: "x0x::bootstrap",
%addr,
attempt,
dial_timeout = ?self.config.dial_timeout,
"bootstrap dial timed out; backing off and retrying"
);
}
}
// Apply exponential backoff (shared by both retryable outcomes).
sleep(backoff).await;
backoff = std::cmp::min(
Duration::from_secs_f64(backoff.as_secs_f64() * self.config.backoff_multiplier),
self.config.max_backoff,
);
}
}
/// Connect to multiple bootstrap addresses in parallel.
///
/// # Arguments
///
/// * `node` - The network node to use.
/// * `addrs` - Bootstrap addresses to connect to.
///
/// # Returns
///
/// Number of successful connections.
pub async fn connect_multiple(&self, node: &NetworkNode, addrs: &[SocketAddr]) -> usize {
let handles: Vec<_> = addrs
.iter()
.map(|&addr| {
let node_clone = node.clone();
let config = self.config.clone();
tokio::spawn(async move {
let connector = BootstrapConnector::with_config(config);
connector
.connect_with_retry(&node_clone, addr)
.await
.is_ok()
})
})
.collect();
futures::future::join_all(handles)
.await
.into_iter()
.filter(|r| matches!(r, Ok(true)))
.count()
}
}
impl Default for BootstrapConnector {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_bootstrap_config_default() {
let config = BootstrapConfig::default();
assert_eq!(config.max_retries, 3);
assert_eq!(config.backoff_multiplier, 2.0);
assert_eq!(config.initial_backoff, Duration::from_millis(100));
assert_eq!(config.max_backoff, Duration::from_secs(5));
assert_eq!(config.dial_timeout, Duration::from_secs(10));
}
#[test]
fn test_bootstrap_config_custom() {
let config = BootstrapConfig {
max_retries: 5,
backoff_multiplier: 1.5,
initial_backoff: Duration::from_millis(50),
max_backoff: Duration::from_secs(10),
dial_timeout: Duration::from_secs(10),
};
assert_eq!(config.max_retries, 5);
assert_eq!(config.backoff_multiplier, 1.5);
}
#[test]
fn test_bootstrap_connector_new() {
let connector = BootstrapConnector::new();
assert_eq!(connector.config.max_retries, 3);
}
#[test]
fn test_bootstrap_connector_with_config() {
let config = BootstrapConfig {
max_retries: 2,
backoff_multiplier: 2.0,
initial_backoff: Duration::from_millis(100),
max_backoff: Duration::from_secs(5),
dial_timeout: Duration::from_secs(10),
};
let connector = BootstrapConnector::with_config(config.clone());
assert_eq!(connector.config.max_retries, 2);
}
#[test]
fn test_bootstrap_connector_default() {
let connector = BootstrapConnector::default();
assert_eq!(connector.config.max_retries, 3);
}
#[test]
fn test_exponential_backoff_calculation() {
let config = BootstrapConfig {
max_retries: 3,
backoff_multiplier: 2.0,
initial_backoff: Duration::from_millis(100),
max_backoff: Duration::from_secs(5),
dial_timeout: Duration::from_secs(10),
};
let mut backoff = config.initial_backoff;
assert_eq!(backoff, Duration::from_millis(100));
// First retry: 100ms * 2 = 200ms
backoff = Duration::from_secs_f64(backoff.as_secs_f64() * config.backoff_multiplier);
assert_eq!(backoff, Duration::from_millis(200));
// Second retry: 200ms * 2 = 400ms
backoff = Duration::from_secs_f64(backoff.as_secs_f64() * config.backoff_multiplier);
assert_eq!(backoff, Duration::from_millis(400));
// Third retry: 400ms * 2 = 800ms
backoff = Duration::from_secs_f64(backoff.as_secs_f64() * config.backoff_multiplier);
assert_eq!(backoff, Duration::from_millis(800));
}
#[test]
fn test_max_backoff_clamping() {
let config = BootstrapConfig {
max_retries: 5,
backoff_multiplier: 2.0,
initial_backoff: Duration::from_millis(1000),
max_backoff: Duration::from_secs(5),
dial_timeout: Duration::from_secs(10),
};
let mut backoff = config.initial_backoff;
// Keep applying backoff multiplier
for _ in 0..5 {
backoff = std::cmp::min(
Duration::from_secs_f64(backoff.as_secs_f64() * config.backoff_multiplier),
config.max_backoff,
);
}
// Should never exceed max_backoff
assert!(backoff <= config.max_backoff);
}
}