aleph-bft 0.45.4

AlephBFT is an asynchronous and Byzantine fault tolerant consensus protocol aimed at ordering arbitrary messages (transactions). It has been designed to continuously operate even in the harshest conditions: with no bounds on message-delivery delays and in the presence of malicious actors. This makes it an excellent fit for blockchain-related applications.
Documentation
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
use crate::{
    alerts::{Alert, AlertMessage, ForkProof, ForkingNotification, Handler, Service},
    units::{ControlHash, FullUnit, PreUnit},
    Index, Indexed, Keychain as _, NodeCount, NodeIndex, NodeMap, Recipient, Round, Signable,
    Signed, Terminator, UncheckedSigned,
};
use aleph_bft_mock::{Data, Hasher64, Keychain, PartialMultisignature, Signature};
use aleph_bft_rmc::Message as RmcMessage;
use futures::{
    channel::{mpsc, oneshot},
    FutureExt, StreamExt,
};
use futures_timer::Delay;
use log::trace;
use std::{
    collections::{HashMap, HashSet},
    hash::Hash,
    time::Duration,
};

type TestMessage = AlertMessage<Hasher64, Data, Signature, PartialMultisignature>;
type TestAlert = Alert<Hasher64, Data, Signature>;
type TestNotification = ForkingNotification<Hasher64, Data, Signature>;
type TestForkProof = ForkProof<Hasher64, Data, Signature>;
type TestFullUnit = FullUnit<Hasher64, Data>;

enum Input {
    Incoming(TestMessage),
    Alert(TestAlert),
}

#[derive(Debug, PartialEq, Eq, Hash)]
enum Output {
    Outgoing(TestMessage, Recipient),
    Notification(TestNotification),
}

struct Segment {
    inputs: Vec<Input>,
    expected: HashMap<Output, usize>,
    unexpected: HashSet<Output>,
}

impl Segment {
    fn new() -> Self {
        Segment {
            inputs: Vec::new(),
            expected: HashMap::new(),
            unexpected: HashSet::new(),
        }
    }

    fn check_output(&mut self, output: Output) {
        assert!(
            !self.unexpected.contains(&output),
            "Unexpected {:?} emitted by alerter.",
            output
        );
        match self.expected.get_mut(&output) {
            Some(count) => *count -= 1,
            None => trace!("Possibly unnecessary {:?} emitted by alerter.", output),
        }
        if self.expected.get(&output) == Some(&0) {
            self.expected.remove(&output);
        }
    }
}

struct TestCase {
    keychains: Vec<Keychain>,
    segments: Vec<Segment>,
}

impl TestCase {
    fn new(n_members: NodeCount) -> Self {
        let mut keychains = Vec::new();
        for i in 0..n_members.0 {
            keychains.push(Keychain::new(n_members, NodeIndex(i)))
        }
        Self {
            keychains,
            segments: vec![Segment::new()],
        }
    }

    fn keychain(&self, node: NodeIndex) -> &Keychain {
        &self.keychains[node.0]
    }

    fn unchecked_signed<T: Signable + Index>(
        &self,
        to_sign: T,
        signer: NodeIndex,
    ) -> UncheckedSigned<T, Signature> {
        Signed::sign(to_sign, self.keychain(signer)).into()
    }

    fn indexed_unchecked_signed<T: Signable>(
        &self,
        to_sign: T,
        signer: NodeIndex,
    ) -> UncheckedSigned<Indexed<T>, Signature> {
        Signed::sign_with_index(to_sign, self.keychain(signer)).into()
    }

    fn full_unit(&self, forker: NodeIndex, round: Round, variant: u32) -> TestFullUnit {
        FullUnit::new(
            PreUnit::new(
                forker,
                round,
                ControlHash::new(&NodeMap::with_size(
                    self.keychain(NodeIndex(0)).node_count(),
                )),
            ),
            Some(variant),
            0,
        )
    }

    fn unchecked_signed_unit(
        &self,
        creator: NodeIndex,
        round: Round,
        variant: u32,
    ) -> UncheckedSigned<TestFullUnit, Signature> {
        self.unchecked_signed(self.full_unit(creator, round, variant), creator)
    }

    fn fork_proof(&self, forker: NodeIndex, round: Round) -> TestForkProof {
        let u0 = self.unchecked_signed_unit(forker, round, 0);
        let u1 = self.unchecked_signed_unit(forker, round, 1);
        (u0, u1)
    }

    fn alert_with_commitment(
        &self,
        sender: NodeIndex,
        proof: TestForkProof,
        commitment: Vec<UncheckedSigned<TestFullUnit, Signature>>,
    ) -> TestAlert {
        Alert::new(sender, proof, commitment)
    }

    fn alert(&self, sender: NodeIndex, proof: TestForkProof) -> TestAlert {
        self.alert_with_commitment(sender, proof, Vec::new())
    }

    fn incoming_message(&mut self, message: TestMessage) -> &mut Self {
        self.segments
            .last_mut()
            .expect("there is a segment")
            .inputs
            .push(Input::Incoming(message));
        self
    }

    fn incoming_alert(&mut self, alert: TestAlert) -> &mut Self {
        self.segments
            .last_mut()
            .expect("there is a segment")
            .inputs
            .push(Input::Alert(alert));
        self
    }

    fn outgoing_message(&mut self, message: TestMessage, recipient: Recipient) -> &mut Self {
        *self
            .segments
            .last_mut()
            .expect("there is a segment")
            .expected
            .entry(Output::Outgoing(message, recipient))
            .or_insert(0) += 1;
        self
    }

    fn outgoing_notification(&mut self, notification: TestNotification) -> &mut Self {
        *self
            .segments
            .last_mut()
            .expect("there is a segment")
            .expected
            .entry(Output::Notification(notification))
            .or_insert(0) += 1;
        self
    }

    fn unexpected_message(&mut self, message: TestMessage, recipient: Recipient) -> &mut Self {
        self.segments
            .last_mut()
            .expect("there is a segment")
            .unexpected
            .insert(Output::Outgoing(message, recipient));
        self
    }

    fn unexpected_notification(&mut self, notification: TestNotification) -> &mut Self {
        self.segments
            .last_mut()
            .expect("there is a segment")
            .unexpected
            .insert(Output::Notification(notification));
        self
    }

    fn wait(&mut self) -> &mut Self {
        self.segments.push(Segment::new());
        self
    }

    async fn test(self, keychain: Keychain) {
        let (messages_for_network, mut messages_from_alerter) = mpsc::unbounded();
        let (messages_for_alerter, messages_from_network) = mpsc::unbounded();
        let (notifications_for_units, mut notifications_from_alerter) = mpsc::unbounded();
        let (alerts_for_alerter, alerts_from_units) = mpsc::unbounded();
        let (exit_alerter_tx, exit_alerter_rx) = oneshot::channel();

        let alerter_handler = Handler::new(keychain, 0);
        let mut alerter_service = Service::new(
            keychain,
            crate::alerts::IO {
                messages_for_network,
                messages_from_network,
                notifications_for_units,
                alerts_from_units,
            },
            alerter_handler,
        );

        tokio::spawn(async move {
            alerter_service
                .run(Terminator::create_root(exit_alerter_rx, "AlephBFT-alerter"))
                .await
        });

        use Input::*;
        use Output::*;

        for mut segment in self.segments {
            for i in &segment.inputs {
                match i {
                    Incoming(message) => messages_for_alerter
                        .unbounded_send(message.clone())
                        .expect("the message channel works"),
                    Alert(alert) => alerts_for_alerter
                        .unbounded_send(alert.clone())
                        .expect("the alert channel works"),
                }
            }
            while !segment.expected.is_empty() {
                tokio::select! {
                    message = messages_from_alerter.next() => match message {
                        Some((message, recipient)) => segment.check_output(Outgoing(message, recipient)),
                        None => panic!("Message stream unexpectedly closed."),
                    },
                    notification = notifications_from_alerter.next() => match notification {
                        Some(notification) => segment.check_output(Output::Notification(notification)),
                        None => panic!("Notification stream unexpectedly closed."),
                    }
                }
                trace!("Remaining items in this segment: {:?}.", segment.expected);
            }
        }
        exit_alerter_tx
            .send(())
            .expect("exit channel shouldn't be closed");
    }

    async fn run(self, run_as: NodeIndex) {
        let keychain = *self.keychain(run_as);
        let mut timeout = Delay::new(Duration::from_millis(500)).fuse();
        futures::select! {
            _ = self.test(keychain).fuse() => {},
            _ = timeout => {
                panic!("Alerter took too long to emit expected items.");
            },
        }
    }
}

#[tokio::test]
async fn distributes_alert_from_units() {
    let n_members = NodeCount(7);
    let own_index = NodeIndex(0);
    let forker = NodeIndex(6);
    let mut test_case = TestCase::new(n_members);
    let alert = test_case.alert(own_index, test_case.fork_proof(forker, 0));
    let signed_alert = test_case.unchecked_signed(alert.clone(), own_index);
    test_case
        .incoming_alert(alert.clone())
        .outgoing_message(AlertMessage::ForkAlert(signed_alert), Recipient::Everyone);
    test_case.run(own_index).await;
}

#[tokio::test]
async fn reacts_to_correctly_incoming_alert() {
    let n_members = NodeCount(7);
    let own_index = NodeIndex(0);
    let alerter_index = NodeIndex(1);
    let forker = NodeIndex(6);
    let mut test_case = TestCase::new(n_members);
    let fork_proof = test_case.fork_proof(forker, 0);
    let alert = test_case.alert(alerter_index, fork_proof.clone());
    let signed_alert_hash = test_case.indexed_unchecked_signed(Signable::hash(&alert), own_index);
    let signed_alert = test_case.unchecked_signed(alert.clone(), alerter_index);
    test_case
        .incoming_message(AlertMessage::ForkAlert(signed_alert))
        .outgoing_notification(ForkingNotification::Forker(fork_proof));
    test_case.outgoing_message(
        AlertMessage::RmcMessage(own_index, RmcMessage::SignedHash(signed_alert_hash.clone())),
        Recipient::Everyone,
    );
    test_case.run(own_index).await;
}

#[tokio::test]
async fn notifies_about_finished_alert() {
    let n_members = NodeCount(7);
    let own_index = NodeIndex(0);
    let alerter_index = NodeIndex(1);
    let forker = NodeIndex(6);
    let mut test_case = TestCase::new(n_members);
    let fork_proof = test_case.fork_proof(forker, 0);
    let alert = test_case.alert(alerter_index, fork_proof.clone());
    let alert_hash = Signable::hash(&alert);
    let signed_alert = test_case.unchecked_signed(alert.clone(), alerter_index);
    test_case
        .incoming_message(AlertMessage::ForkAlert(signed_alert))
        .outgoing_notification(ForkingNotification::Forker(fork_proof))
        .wait();
    for i in 1..n_members.0 - 1 {
        let node_id = NodeIndex(i);
        let signed_alert_hash = test_case.indexed_unchecked_signed(alert_hash, node_id);
        test_case.incoming_message(AlertMessage::RmcMessage(
            node_id,
            RmcMessage::SignedHash(signed_alert_hash),
        ));
    }
    test_case.outgoing_notification(ForkingNotification::Units(Vec::new()));
    test_case.run(own_index).await;
}

#[tokio::test]
async fn asks_about_unknown_alert() {
    let n_members = NodeCount(7);
    let own_index = NodeIndex(0);
    let alerter_index = NodeIndex(1);
    let forker = NodeIndex(6);
    let mut test_case = TestCase::new(n_members);
    let fork_proof = test_case.fork_proof(forker, 0);
    let alert = test_case.alert(alerter_index, fork_proof.clone());
    let alert_hash = Signable::hash(&alert);
    let signed_alert_hash = test_case.indexed_unchecked_signed(alert_hash, alerter_index);
    test_case
        .incoming_message(AlertMessage::RmcMessage(
            alerter_index,
            RmcMessage::SignedHash(signed_alert_hash),
        ))
        .outgoing_message(
            AlertMessage::AlertRequest(own_index, alert_hash),
            Recipient::Node(alerter_index),
        );
    test_case.run(own_index).await;
}

#[tokio::test]
async fn ignores_wrong_alert() {
    let n_members = NodeCount(7);
    let own_index = NodeIndex(0);
    let alerter_index = NodeIndex(1);
    let forker = NodeIndex(6);
    let mut test_case = TestCase::new(n_members);
    let valid_unit = test_case.unchecked_signed_unit(alerter_index, 0, 0);
    let wrong_fork_proof = (valid_unit.clone(), valid_unit);
    let wrong_alert = test_case.alert(forker, wrong_fork_proof.clone());
    let signed_wrong_alert = test_case.unchecked_signed(wrong_alert.clone(), forker);
    let signed_wrong_alert_hash =
        test_case.indexed_unchecked_signed(Signable::hash(&wrong_alert), own_index);
    test_case
        .incoming_message(AlertMessage::ForkAlert(signed_wrong_alert))
        .unexpected_notification(ForkingNotification::Forker(wrong_fork_proof));
    for i in 1..n_members.0 {
        test_case.unexpected_message(
            AlertMessage::RmcMessage(
                own_index,
                RmcMessage::SignedHash(signed_wrong_alert_hash.clone()),
            ),
            Recipient::Node(NodeIndex(i)),
        );
    }
    // We also make a proper alert to actually have something to wait for.
    let fork_proof = test_case.fork_proof(forker, 0);
    let alert = test_case.alert(alerter_index, fork_proof.clone());
    let signed_alert = test_case.unchecked_signed(alert.clone(), alerter_index);
    test_case
        .incoming_message(AlertMessage::ForkAlert(signed_alert))
        .outgoing_notification(ForkingNotification::Forker(fork_proof));
    test_case.run(own_index).await;
}

#[tokio::test]
async fn responds_to_alert_queries() {
    let n_members = NodeCount(7);
    let own_index = NodeIndex(0);
    let querier = NodeIndex(1);
    let forker = NodeIndex(6);
    let mut test_case = TestCase::new(n_members);
    let alert = test_case.alert(own_index, test_case.fork_proof(forker, 0));
    let alert_hash = Signable::hash(&alert);
    let signed_alert = test_case.unchecked_signed(alert.clone(), own_index);
    let signed_alert_hash = test_case.indexed_unchecked_signed(alert_hash, own_index);
    test_case
        .incoming_alert(alert.clone())
        .outgoing_message(
            AlertMessage::ForkAlert(signed_alert.clone()),
            Recipient::Everyone,
        )
        .outgoing_message(
            AlertMessage::RmcMessage(own_index, RmcMessage::SignedHash(signed_alert_hash.clone())),
            Recipient::Everyone,
        )
        .wait()
        .incoming_message(AlertMessage::AlertRequest(querier, alert_hash))
        .outgoing_message(
            AlertMessage::ForkAlert(signed_alert.clone()),
            Recipient::Node(querier),
        );
    for i in 1..n_members.0 {
        let node_id = NodeIndex(i);
        test_case
            .incoming_message(AlertMessage::AlertRequest(node_id, alert_hash))
            .outgoing_message(
                AlertMessage::ForkAlert(signed_alert.clone()),
                Recipient::Node(node_id),
            );
    }
    test_case.run(own_index).await;
}

#[tokio::test]
async fn notifies_only_about_multisigned_alert() {
    let n_members = NodeCount(7);
    let own_index = NodeIndex(0);
    let other_honest_node = NodeIndex(1);
    let double_committer = NodeIndex(5);
    let forker = NodeIndex(6);
    let mut test_case = TestCase::new(n_members);
    let fork_proof = test_case.fork_proof(forker, 0);
    let empty_alert = test_case.alert(double_committer, fork_proof.clone());
    let empty_alert_hash = Signable::hash(&empty_alert);
    let signed_empty_alert = test_case.unchecked_signed(empty_alert.clone(), double_committer);
    let signed_empty_alert_hash =
        test_case.indexed_unchecked_signed(empty_alert_hash, double_committer);
    test_case
        .incoming_message(AlertMessage::ForkAlert(signed_empty_alert))
        .incoming_message(AlertMessage::RmcMessage(
            double_committer,
            RmcMessage::SignedHash(signed_empty_alert_hash),
        ))
        .outgoing_notification(ForkingNotification::Forker(fork_proof.clone()))
        .unexpected_notification(ForkingNotification::Units(Vec::new()))
        .wait();
    let forker_unit = fork_proof.0.clone();
    let nonempty_alert = test_case.alert_with_commitment(
        double_committer,
        fork_proof.clone(),
        vec![forker_unit.clone()],
    );
    let nonempty_alert_hash = Signable::hash(&nonempty_alert);
    let signed_nonempty_alert =
        test_case.unchecked_signed(nonempty_alert.clone(), double_committer);
    let signed_nonempty_alert_hash =
        test_case.indexed_unchecked_signed(nonempty_alert_hash, double_committer);
    let keychain = test_case.keychain(double_committer);
    let mut multisigned_nonempty_alert_hash = signed_nonempty_alert_hash
        .check(keychain)
        .expect("the signature is correct")
        .into_partially_multisigned(keychain);
    for i in 1..n_members.0 - 2 {
        let node_id = NodeIndex(i);
        let signed_nonempty_alert_hash =
            test_case.indexed_unchecked_signed(nonempty_alert_hash, node_id);
        multisigned_nonempty_alert_hash = multisigned_nonempty_alert_hash.add_signature(
            signed_nonempty_alert_hash
                .check(keychain)
                .expect("the signature is correct"),
            keychain,
        );
    }
    let unchecked_multisigned_nonempty_alert_hash =
        multisigned_nonempty_alert_hash.into_unchecked();
    test_case
        .incoming_message(AlertMessage::ForkAlert(signed_nonempty_alert))
        .incoming_message(AlertMessage::RmcMessage(
            other_honest_node,
            RmcMessage::MultisignedHash(unchecked_multisigned_nonempty_alert_hash),
        ))
        .outgoing_notification(ForkingNotification::Units(vec![forker_unit]))
        .unexpected_notification(ForkingNotification::Units(Vec::new()));
    test_case.run(own_index).await;
}