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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
//! Very fast networking component used for testing and simulations.
//!
//! The `InMemoryNetwork` represents a full virtual network with flawless connectivity and delivery
//! by default.
//!
//! # Setup
//!
//! The network itself is managed by a `NetworkController` that can be used to create networking
//! components for nodes. Let's demonstrate this with an example in which we
//!
//! 1. Define a fictional "shouter" component to utilize the network.
//! 2. Create an application (in the form of a reactor) that connects this shouter to an in-memory
//! network of nodes.
//! 3. Run a test that verifies everything is working.
//!
//! ```rust
//! #
//! # use std::{
//! # collections::HashMap,
//! # fmt::{self, Debug, Display, Formatter},
//! # ops::AddAssign,
//! # time::Duration,
//! # };
//! #
//! # use derive_more::From;
//! # use prometheus::Registry;
//! # use rand::{rngs::OsRng, CryptoRng, Rng};
//! #
//! # use casper_node::{
//! # components::{
//! # in_memory_network::{InMemoryNetwork, NetworkController, NodeId},
//! # Component,
//! # },
//! # effect::{
//! # announcements::NetworkAnnouncement, requests::NetworkRequest, EffectBuilder, EffectExt,
//! # Effects,
//! # },
//! # reactor::{self, wrap_effects, EventQueueHandle},
//! # testing::network::{Network, NetworkedReactor},
//! # };
//! #
//! # let mut runtime = tokio::runtime::Runtime::new().unwrap();
//! #
//! // Our network messages are just integers in this example.
//! type Message = u64;
//!
//! // When gossiping, always select exactly two nodes.
//! const TEST_GOSSIP_COUNT: usize = 2;
//!
//! // We will test with three nodes.
//! const TEST_NODE_COUNT: usize = 3;
//! # assert!(TEST_GOSSIP_COUNT < TEST_NODE_COUNT);
//!
//! /// The shouter component. Sends messages across the network and tracks incoming.
//! #[derive(Debug)]
//! struct Shouter {
//! /// Values we will gossip.
//! whispers: Vec<Message>,
//! /// Values we will broadcast.
//! shouts: Vec<Message>,
//! /// Values we received.
//! received: Vec<(NodeId, Message)>,
//! }
//!
//! impl Shouter {
//! /// Returns the totals of each message value received. Used for verification in testing.
//! fn count_messages(&self) -> HashMap<Message, usize> {
//! let mut totals = HashMap::<Message, usize>::new();
//!
//! for (_node_id, message) in &self.received {
//! totals.entry(*message).or_default().add_assign(1);
//! }
//!
//! totals
//! }
//! }
//!
//! #[derive(Debug, From)]
//! enum ShouterEvent<Message> {
//! #[from]
//! // We received a new message via the network.
//! Net(NetworkAnnouncement<Message>),
//! // Ready to send another message.
//! #[from]
//! ReadyToSend,
//! }
//!
//! impl Shouter {
//! /// Creates a new shouter.
//! fn new<REv: Send, P: 'static>(effect_builder: EffectBuilder<REv>)
//! -> (Self, Effects<ShouterEvent<P>>) {
//! (Shouter {
//! whispers: Vec::new(),
//! shouts: Vec::new(),
//! received: Vec::new(),
//! }, effect_builder.immediately().event(|_| ShouterEvent::ReadyToSend))
//! }
//! }
//!
//! // Besides its own events, the shouter is capable of receiving network messages.
//! impl<REv, R> Component<REv, R> for Shouter
//! where
//! REv: From<NetworkRequest<Message>> + Send,
//! {
//! type Event = ShouterEvent<Message>;
//!
//! fn handle_event(&mut self,
//! effect_builder: EffectBuilder<REv>,
//! _rng: &mut NodeRng,
//! event: Self::Event
//! ) -> Effects<Self::Event> {
//! match event {
//! ShouterEvent::Net(NetworkAnnouncement::MessageReceived { sender, payload }) => {
//! // Record the message we received.
//! self.received.push((sender, payload));
//! Effects::new()
//! }
//! ShouterEvent::ReadyToSend => {
//! // If we need to whisper something, do so.
//! if let Some(msg) = self.whispers.pop() {
//! return effect_builder.gossip_message(msg,
//! TEST_GOSSIP_COUNT,
//! Default::default())
//! .event(|_| ShouterEvent::ReadyToSend);
//! }
//! // Shouts get broadcast.
//! if let Some(msg) = self.shouts.pop() {
//! return effect_builder.broadcast_message(msg)
//! .event(|_| ShouterEvent::ReadyToSend);
//! }
//! Effects::new()
//! }
//! }
//! }
//! }
//!
//! /// The reactor ties the shouter component to a network.
//! #[derive(Debug)]
//! struct Reactor {
//! /// The connection to the internal network.
//! net: InMemoryNetwork<u64>,
//! /// Local shouter instance.
//! shouter: Shouter,
//! }
//!
//! /// Reactor event
//! #[derive(Debug, From)]
//! enum Event {
//! /// Asked to perform a network action.
//! #[from]
//! Request(NetworkRequest<Message>),
//! /// Event for the shouter.
//! #[from]
//! Shouter(ShouterEvent<Message>),
//! /// Notified of some network event.
//! #[from]
//! Announcement(NetworkAnnouncement<Message>)
//! };
//! #
//! # impl Display for Event {
//! # fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
//! # Debug::fmt(self, fmt)
//! # }
//! # }
//! #
//! # impl<P> Display for ShouterEvent<P>
//! # where P: Debug,
//! # {
//! # fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
//! # Debug::fmt(self, fmt)
//! # }
//! # }
//!
//! impl reactor::Reactor for Reactor {
//! type Event = Event;
//! type Config = ();
//! type Error = anyhow::Error;
//!
//! fn new<R: Rng + ?Sized>(
//! _cfg: Self::Config,
//! _registry: &Registry,
//! event_queue: EventQueueHandle<Self::Event>,
//! rng: &mut NodeRng,
//! ) -> Result<(Self, Effects<Self::Event>), anyhow::Error> {
//! let effect_builder = EffectBuilder::new(event_queue);
//! let (shouter, shouter_effect) = Shouter::new(effect_builder);
//!
//! Ok((Reactor {
//! net: NetworkController::create_node(event_queue, rng),
//! shouter,
//! }, wrap_effects(From::from, shouter_effect)))
//! }
//!
//! fn dispatch_event<R: Rng + ?Sized>(&mut self,
//! effect_builder: EffectBuilder<Event>,
//! rng: &mut NodeRng,
//! event: Event
//! ) -> Effects<Event> {
//! match event {
//! Event::Announcement(anc) => { wrap_effects(From::from,
//! self.shouter.handle_event(effect_builder, rng, anc.into())
//! )}
//! Event::Request(req) => { wrap_effects(From::from,
//! self.net.handle_event(effect_builder, rng, req.into())
//! )}
//! Event::Shouter(ev) => { wrap_effects(From::from,
//! self.shouter.handle_event(effect_builder, rng, ev)
//! )}
//! }
//! }
//! }
//!
//! impl NetworkedReactor for Reactor {
//! fn node_id(&self) -> NodeId {
//! self.net.node_id()
//! }
//! }
//!
//! // We can finally run the tests:
//!
//! # // We need to be inside a tokio runtime to execute `async` code.
//! # runtime.block_on(async move {
//! #
//! // Create a new network controller that manages the network itself. This will register the
//! // network controller on the current thread and allow initialization functions to find it.
//! NetworkController::<Message>::create_active();
//!
//! // We can now create the network of nodes, using the `testing::Network` and insert three nodes.
//! // Each node is given some data to send.
//! let mut rng = OsRng;
//! let mut net = Network::<Reactor>::new();
//! let (id1, n1) = net.add_node(&mut rng).await.unwrap();
//! n1.reactor_mut().shouter.shouts.push(1);
//! n1.reactor_mut().shouter.shouts.push(2);
//! n1.reactor_mut().shouter.whispers.push(3);
//! n1.reactor_mut().shouter.whispers.push(4);
//!
//! let (id2, n2) = net.add_node(&mut rng).await.unwrap();
//! n2.reactor_mut().shouter.shouts.push(6);
//! n2.reactor_mut().shouter.whispers.push(4);
//!
//! let (id3, n3) = net.add_node(&mut rng).await.unwrap();
//! n3.reactor_mut().shouter.whispers.push(8);
//! n3.reactor_mut().shouter.shouts.push(1);
//!
//! net.settle(&mut rng, Duration::from_secs(1)).await;
//! assert_eq!(net.nodes().len(), TEST_NODE_COUNT);
//!
//! let mut global_count = HashMap::<Message, usize>::new();
//! for node_id in &[id1, id2, id3] {
//! let totals = net.nodes()[node_id].reactor().shouter.count_messages();
//!
//! // The broadcast values should be the same for each node:
//! assert_eq!(totals[&1], 2);
//! assert_eq!(totals[&2], 1);
//! assert_eq!(totals[&6], 1);
//!
//! // Add values to global_count count.
//! for (val, count) in totals.into_iter() {
//! global_count.entry(val).or_default().add_assign(count);
//! }
//! }
//!
//! let mut expected = HashMap::new();
//! let _ = expected.insert(1, 2 * TEST_NODE_COUNT);
//! let _ = expected.insert(2, TEST_NODE_COUNT);
//! let _ = expected.insert(3, TEST_GOSSIP_COUNT);
//! let _ = expected.insert(4, 2 * TEST_GOSSIP_COUNT);
//! let _ = expected.insert(6, TEST_NODE_COUNT);
//! let _ = expected.insert(8, TEST_GOSSIP_COUNT);
//! assert_eq!(global_count, expected);
//!
//! // It's good form to remove the active network.
//! NetworkController::<Message>::remove_active();
//!
//! # }); // end of tokio::block_on
//! ```
use ;
use IteratorRandom;
use Serialize;
use ;
use ;
use TestRng;
use crate::;
use FromIncoming;
const COMPONENT_NAME: &str = "in_memory_network";
/// A network.
type Network<P> = ;
/// An in-memory network events.
pub ;
thread_local!
/// The network controller is used to control the network topology (e.g. adding and removing nodes).
pub
/// Networking component connected to an in-memory network.
pub
async