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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
pub(crate) mod command;
mod bootstrap;
mod comm;
mod connectivity_complaints;
mod core;
mod dispatcher;
mod enduser_registry;
mod event_stream;
mod split_barrier;
#[cfg(test)]
pub(crate) mod tests;
pub use self::event_stream::EventStream;
use self::{
comm::{Comm, ConnectionEvent},
command::Command,
core::Core,
dispatcher::Dispatcher,
};
use crate::{
crypto,
error::Result,
event::{Elders, Event, NodeElderChange},
messages::Message,
node::Node,
peer::Peer,
section::{SectionAuthorityProvider, SectionChain},
Error, TransportConfig, MIN_ADULT_AGE,
};
use bytes::Bytes;
use ed25519_dalek::{Keypair, PublicKey, Signature, Signer, KEYPAIR_LENGTH};
use itertools::Itertools;
use sn_messaging::{
client::ClientMsg, node::RoutingMsg, DestInfo, DstLocation, EndUser, Itinerary, MessageType,
WireMsg,
};
use std::{collections::BTreeSet, net::SocketAddr, sync::Arc};
use tokio::{sync::mpsc, task};
use xor_name::{Prefix, XorName};
#[derive(Debug)]
pub struct Config {
pub first: bool,
pub keypair: Option<Keypair>,
pub transport_config: TransportConfig,
}
impl Default for Config {
fn default() -> Self {
Self {
first: false,
keypair: None,
transport_config: TransportConfig::default(),
}
}
}
pub struct Routing {
dispatcher: Arc<Dispatcher>,
}
impl Routing {
pub async fn new(config: Config) -> Result<(Self, EventStream)> {
let keypair = config.keypair.unwrap_or_else(|| {
crypto::gen_keypair(&Prefix::default().range_inclusive(), MIN_ADULT_AGE)
});
let node_name = crypto::name(&keypair.public);
let (event_tx, event_rx) = mpsc::unbounded_channel();
let (connection_event_tx, mut connection_event_rx) = mpsc::channel(1);
let (state, comm, backlog) = if config.first {
let keypair = crypto::gen_keypair(&Prefix::default().range_inclusive(), 255);
let node_name = crypto::name(&keypair.public);
info!("{} Starting a new network as the genesis node.", node_name);
let comm = Comm::new(config.transport_config, connection_event_tx).await?;
let node = Node::new(keypair, comm.our_connection_info());
let state = Core::first_node(node, event_tx)?;
let section = state.section();
let elders = Elders {
prefix: *section.prefix(),
key: *section.chain().last_key(),
remaining: BTreeSet::new(),
added: section.authority_provider().names(),
removed: BTreeSet::new(),
};
state.send_event(Event::EldersChanged {
elders,
self_status_change: NodeElderChange::Promoted,
});
(state, comm, vec![])
} else {
info!("{} Bootstrapping a new node.", node_name);
let (comm, bootstrap_addr) =
Comm::bootstrap(config.transport_config, connection_event_tx).await?;
let node = Node::new(keypair, comm.our_connection_info());
let (node, section, backlog) =
bootstrap::initial(node, &comm, &mut connection_event_rx, bootstrap_addr).await?;
let state = Core::new(node, section, None, event_tx);
(state, comm, backlog)
};
let dispatcher = Arc::new(Dispatcher::new(state, comm));
let event_stream = EventStream::new(event_rx);
info!("{} Bootstrapped!", node_name);
for (message, sender, dest_info) in backlog {
dispatcher
.clone()
.handle_commands(Command::HandleMessage {
message,
sender: Some(sender),
dest_info,
})
.await?;
}
let _ = task::spawn(handle_connection_events(
dispatcher.clone(),
connection_event_rx,
));
let routing = Self { dispatcher };
Ok((routing, event_stream))
}
pub async fn set_joins_allowed(&self, joins_allowed: bool) -> Result<()> {
let command = Command::SetJoinsAllowed(joins_allowed);
self.dispatcher.clone().handle_commands(command).await
}
pub async fn propose_offline(&self, name: XorName) -> Result<()> {
if !self.is_elder().await {
return Err(Error::InvalidState);
}
let command = Command::ProposeOffline(name);
self.dispatcher.clone().handle_commands(command).await
}
pub async fn age(&self) -> u8 {
self.dispatcher.core.lock().await.node().age()
}
pub async fn public_key(&self) -> PublicKey {
self.dispatcher.core.lock().await.node().keypair.public
}
pub async fn keypair_as_bytes(&self) -> [u8; KEYPAIR_LENGTH] {
self.dispatcher.core.lock().await.node().keypair.to_bytes()
}
pub async fn sign_as_node(&self, data: &[u8]) -> Signature {
self.dispatcher.core.lock().await.node().keypair.sign(data)
}
pub async fn sign_as_elder(
&self,
data: &[u8],
public_key: &bls::PublicKey,
) -> Result<bls::SignatureShare> {
self.dispatcher
.core
.lock()
.await
.sign_with_section_key_share(data, public_key)
}
pub async fn verify(&self, data: &[u8], signature: &Signature) -> bool {
self.dispatcher
.core
.lock()
.await
.node()
.keypair
.verify(data, signature)
.is_ok()
}
pub async fn name(&self) -> XorName {
self.dispatcher.core.lock().await.node().name()
}
pub fn our_connection_info(&self) -> SocketAddr {
self.dispatcher.comm.our_connection_info()
}
pub async fn section_chain(&self) -> SectionChain {
self.dispatcher.core.lock().await.section_chain().clone()
}
pub async fn our_prefix(&self) -> Prefix {
*self.dispatcher.core.lock().await.section().prefix()
}
pub async fn matches_our_prefix(&self, name: &XorName) -> bool {
self.our_prefix().await.matches(name)
}
pub async fn is_elder(&self) -> bool {
self.dispatcher.core.lock().await.is_elder()
}
pub async fn our_elders(&self) -> Vec<Peer> {
self.dispatcher
.core
.lock()
.await
.section()
.authority_provider()
.peers()
.collect()
}
pub async fn our_elders_sorted_by_distance_to(&self, name: &XorName) -> Vec<Peer> {
self.our_elders()
.await
.into_iter()
.sorted_by(|lhs, rhs| name.cmp_distance(lhs.name(), rhs.name()))
.collect()
}
pub async fn our_adults(&self) -> Vec<Peer> {
self.dispatcher
.core
.lock()
.await
.section()
.adults()
.copied()
.collect()
}
pub async fn our_adults_sorted_by_distance_to(&self, name: &XorName) -> Vec<Peer> {
self.our_adults()
.await
.into_iter()
.sorted_by(|lhs, rhs| name.cmp_distance(lhs.name(), rhs.name()))
.collect()
}
pub async fn our_section(&self) -> SectionAuthorityProvider {
self.dispatcher
.core
.lock()
.await
.section()
.authority_provider()
.clone()
}
pub async fn other_sections(&self) -> Vec<SectionAuthorityProvider> {
self.dispatcher
.core
.lock()
.await
.network()
.all()
.cloned()
.collect()
}
pub async fn section_key(&self, prefix: &Prefix) -> Option<bls::PublicKey> {
self.dispatcher
.core
.lock()
.await
.section_key(prefix)
.copied()
}
pub async fn matching_section(
&self,
name: &XorName,
) -> (Option<bls::PublicKey>, Option<SectionAuthorityProvider>) {
let state = self.dispatcher.core.lock().await;
let (key, section_auth) = state.matching_section(name);
(key.copied(), section_auth.cloned())
}
pub async fn send_message(
&self,
itinerary: Itinerary,
content: Bytes,
additional_proof_chain_key: Option<bls::PublicKey>,
) -> Result<()> {
if let DstLocation::EndUser(EndUser { socket_id, xorname }) = itinerary.dst {
if self.our_prefix().await.matches(&xorname) {
let addr = self
.dispatcher
.core
.lock()
.await
.get_socket_addr(socket_id)
.copied();
if let Some(socket_addr) = addr {
debug!("Sending client msg to {:?}", socket_addr);
return self
.send_message_to_client(socket_addr, xorname, ClientMsg::from(content)?)
.await;
} else {
debug!(
"Could not find socketaddr corresponding to socket_id {:?}",
socket_id
);
debug!("Relaying user message instead.. (Command::SendUserMessage)");
}
} else {
debug!("Relaying message with sending user message (Command::SendUserMessage)");
}
}
let command = Command::SendUserMessage {
itinerary,
content,
additional_proof_chain_key,
};
self.dispatcher.clone().handle_commands(command).await
}
async fn send_message_to_client(
&self,
recipient: SocketAddr,
user_xorname: XorName,
message: ClientMsg,
) -> Result<()> {
let command = Command::SendMessage {
recipients: vec![(user_xorname, recipient)],
delivery_group_size: 1,
message: MessageType::Client {
msg: message,
dest_info: DestInfo {
dest: user_xorname,
dest_section_pk: *self.section_chain().await.last_key(),
},
},
};
self.dispatcher.clone().handle_commands(command).await
}
pub async fn public_key_set(&self) -> Result<bls::PublicKeySet> {
self.dispatcher.core.lock().await.public_key_set()
}
pub async fn our_history(&self) -> SectionChain {
self.dispatcher.core.lock().await.section().chain().clone()
}
pub async fn our_index(&self) -> Result<usize> {
self.dispatcher.core.lock().await.our_index()
}
}
impl Drop for Routing {
fn drop(&mut self) {
self.dispatcher.terminate()
}
}
async fn handle_connection_events(
dispatcher: Arc<Dispatcher>,
mut incoming_conns: mpsc::Receiver<ConnectionEvent>,
) {
while let Some(event) = incoming_conns.recv().await {
match event {
ConnectionEvent::Received((src, bytes)) => {
trace!("New message ({} bytes) received from: {}", bytes.len(), src);
handle_message(dispatcher.clone(), bytes, src).await;
}
ConnectionEvent::Disconnected(addr) => {
trace!("Lost connection to {:?}", addr);
let _ = dispatcher
.clone()
.handle_commands(Command::HandleConnectionLost(addr))
.await;
}
}
}
}
async fn handle_message(dispatcher: Arc<Dispatcher>, bytes: Bytes, sender: SocketAddr) {
let span = {
let state = dispatcher.core.lock().await;
trace_span!("handle_message", name = %state.node().name(), %sender)
};
let _span_guard = span.enter();
let message_type = match WireMsg::deserialize(bytes) {
Ok(message_type) => message_type,
Err(error) => {
error!("Failed to deserialize message: {}", error);
return;
}
};
match message_type {
MessageType::SectionInfo { msg, dest_info } => {
let command = Command::HandleSectionInfoMsg {
sender,
message: msg,
dest_info,
};
let _ = task::spawn(dispatcher.handle_commands(command));
}
MessageType::Routing {
msg: RoutingMsg(msg_bytes),
dest_info,
} => match Message::from_bytes(Bytes::from(msg_bytes)) {
Ok(message) => {
let command = Command::HandleMessage {
message,
sender: Some(sender),
dest_info,
};
let _ = task::spawn(dispatcher.handle_commands(command));
}
Err(error) => {
error!("Failed to deserialize node message: {}", error);
}
},
MessageType::Node {
msg: _,
dest_info: _,
src_section_pk: _,
} => unimplemented!(),
MessageType::Client { msg, .. } => {
let end_user = dispatcher
.core
.lock()
.await
.get_enduser_by_addr(&sender)
.copied();
let end_user = match end_user {
Some(end_user) => {
debug!(
"Message from client {}, socket id already exists: {:?}",
sender, end_user
);
end_user
}
None => {
debug!("First message from client {}, creating a socket id", sender);
match dispatcher.core.lock().await.try_add(sender) {
Ok(end_user) => end_user,
Err(err) => {
error!(
"Failed to cache client socket address for message {:?}: {:?}",
msg, err
);
return;
}
}
}
};
let event = Event::ClientMsgReceived {
msg: Box::new(msg),
user: end_user,
};
dispatcher.send_event(event).await;
}
}
}