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
//! Bootstrap process for discovering and joining peers via DHT.
use std::{collections::HashSet, time::Duration};
use actor_helper::{Action, Actor, Handle, Receiver, act, act_ok};
use anyhow::Result;
use iroh::EndpointId;
use tokio::time::sleep;
use crate::{
GossipSender,
crypto::Record,
gossip::{GossipRecordContent, receiver::GossipReceiver},
};
/// Manages the peer discovery and joining process.
///
/// Queries DHT for bootstrap records, extracts node IDs, and progressively
/// joins peers until the local node is connected to the topic.
#[derive(Debug, Clone)]
pub struct Bootstrap {
api: Handle<BootstrapActor, anyhow::Error>,
}
#[derive(Debug)]
struct BootstrapActor {
rx: Receiver<Action<Self>>,
record_publisher: crate::crypto::RecordPublisher,
gossip_sender: GossipSender,
gossip_receiver: GossipReceiver,
}
impl Bootstrap {
/// Create a new bootstrap process for a topic.
pub async fn new(
record_publisher: crate::crypto::RecordPublisher,
gossip: iroh_gossip::net::Gossip,
) -> Result<Self> {
let gossip_topic: iroh_gossip::api::GossipTopic = gossip
.subscribe(
iroh_gossip::proto::TopicId::from(record_publisher.record_topic().hash()),
vec![],
)
.await?;
let (gossip_sender, gossip_receiver) = gossip_topic.split();
let (gossip_sender, gossip_receiver) = (
GossipSender::new(gossip_sender, gossip.clone()),
GossipReceiver::new(gossip_receiver, gossip.clone()),
);
let (api, rx) = Handle::channel();
tokio::spawn(async move {
let mut actor = BootstrapActor {
rx,
record_publisher,
gossip_sender,
gossip_receiver,
};
let _ = actor.run().await;
});
Ok(Self { api })
}
/// Start the bootstrap process.
///
/// Returns a receiver that signals completion when the node has joined the topic (has at least one neighbor).
pub async fn bootstrap(&self) -> Result<tokio::sync::oneshot::Receiver<()>> {
self.api.call(act!(actor=> actor.start_bootstrap())).await
}
/// Get the gossip sender for this topic.
pub async fn gossip_sender(&self) -> Result<GossipSender> {
self.api
.call(act_ok!(actor => async move { actor.gossip_sender.clone() }))
.await
}
/// Get the gossip receiver for this topic.
pub async fn gossip_receiver(&self) -> Result<GossipReceiver> {
self.api
.call(act_ok!(actor => async move { actor.gossip_receiver.clone() }))
.await
}
}
impl Actor<anyhow::Error> for BootstrapActor {
async fn run(&mut self) -> Result<()> {
loop {
tokio::select! {
Ok(action) = self.rx.recv_async() => {
action(self).await;
}
_ = tokio::signal::ctrl_c() => {
break;
}
}
}
Ok(())
}
}
impl BootstrapActor {
pub async fn start_bootstrap(&mut self) -> Result<tokio::sync::oneshot::Receiver<()>> {
let (sender, receiver) = tokio::sync::oneshot::channel();
tokio::spawn({
let mut last_published_unix_minute = 0;
let (gossip_sender, gossip_receiver) =
(self.gossip_sender.clone(), self.gossip_receiver.clone());
let record_publisher = self.record_publisher.clone();
async move {
tracing::debug!("Bootstrap: starting bootstrap process");
loop {
// Check if we are connected to at least one node
if gossip_receiver.is_joined().await {
tracing::debug!("Bootstrap: already joined, exiting bootstrap loop");
break;
}
// On the first try we check the prev unix minute, after that the current one
let unix_minute = crate::unix_minute(if last_published_unix_minute == 0 {
-1
} else {
0
});
// Unique, verified records for the unix minute
let mut records = record_publisher.get_records(unix_minute - 1).await;
records.extend(record_publisher.get_records(unix_minute).await);
tracing::debug!(
"Bootstrap: fetched {} records for unix_minute {}",
records.len(),
unix_minute
);
// If there are no records, invoke the publish_proc (the publishing procedure)
// continue the loop after
if records.is_empty() {
if unix_minute != last_published_unix_minute {
tracing::debug!(
"Bootstrap: no records found, publishing own record for unix_minute {}",
unix_minute
);
last_published_unix_minute = unix_minute;
let record_creator = record_publisher.clone();
let record_content = GossipRecordContent {
active_peers: [[0; 32]; 5],
last_message_hashes: [[0; 32]; 5],
};
if let Ok(record) = Record::sign(
record_publisher.record_topic().hash(),
unix_minute,
record_publisher.pub_key().to_bytes(),
record_content,
&record_publisher.signing_key(),
) {
tokio::spawn(async move {
let _ = record_creator.publish_record(record).await;
});
}
}
sleep(Duration::from_millis(100)).await;
continue;
}
// We found records
// Collect node ids from active_peers and record.node_id (of publisher)
let bootstrap_nodes = records
.iter()
.flat_map(|record| {
let mut v = vec![record.node_id()];
if let Ok(record_content) = record.content::<GossipRecordContent>() {
for peer in record_content.active_peers {
if peer != [0; 32] {
v.push(peer);
}
}
}
v
})
.filter_map(|node_id| EndpointId::from_bytes(&node_id).ok())
.collect::<HashSet<_>>();
tracing::debug!(
"Bootstrap: extracted {} potential bootstrap nodes",
bootstrap_nodes.len()
);
// Maybe in the meantime someone connected to us via one of our published records
// we don't want to disrup the gossip rotations any more then we have to
// so we check again before joining new peers
if gossip_receiver.is_joined().await {
tracing::debug!("Bootstrap: joined while processing records, exiting");
break;
}
// Instead of throwing everything into join_peers() at once we go node_id by node_id
// again to disrupt as little nodes peer neighborhoods as possible.
for node_id in bootstrap_nodes.iter() {
match gossip_sender.join_peers(vec![*node_id], None).await {
Ok(_) => {
tracing::debug!("Bootstrap: attempted to join peer {}", node_id);
sleep(Duration::from_millis(100)).await;
if gossip_receiver.is_joined().await {
tracing::debug!(
"Bootstrap: successfully joined via peer {}",
node_id
);
break;
}
}
Err(e) => {
tracing::debug!(
"Bootstrap: failed to join peer {}: {:?}",
node_id,
e
);
continue;
}
}
}
// If we are still not connected to anyone:
// give it the default iroh-gossip connection timeout before the final is_joined() check
if !gossip_receiver.is_joined().await {
tracing::debug!(
"Bootstrap: not joined yet, waiting 500ms before final check"
);
sleep(Duration::from_millis(500)).await;
}
// If we are connected: return
if gossip_receiver.is_joined().await {
tracing::debug!("Bootstrap: successfully joined after final wait");
break;
} else {
tracing::debug!("Bootstrap: still not joined after attempting all peers");
// If we are not connected: check if we should publish a record this minute
if unix_minute != last_published_unix_minute {
tracing::debug!(
"Bootstrap: publishing fallback record for unix_minute {}",
unix_minute
);
last_published_unix_minute = unix_minute;
let record_creator = record_publisher.clone();
if let Ok(record) = Record::sign(
record_publisher.record_topic().hash(),
unix_minute,
record_publisher.pub_key().to_bytes(),
GossipRecordContent {
active_peers: [[0; 32]; 5],
last_message_hashes: [[0; 32]; 5],
},
&record_publisher.signing_key(),
) {
tokio::spawn(async move {
let _ = record_creator.publish_record(record).await;
});
}
}
sleep(Duration::from_millis(100)).await;
continue;
}
}
tracing::debug!("Bootstrap: completed successfully");
let _ = sender.send(());
}
});
Ok(receiver)
}
}