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
use std::fmt::{Debug, Display, Formatter, Result as FmtResult};

use crate::{
    alerts::Alert,
    units::{
        SignedUnit, UncheckedSignedUnit, Unit, UnitStore, UnitStoreStatus, ValidationError,
        Validator as UnitValidator, WrappedUnit,
    },
    Data, Hasher, MultiKeychain, NodeIndex, NodeSubset, Round,
};

/// What can go wrong when validating a unit.
#[derive(Eq, PartialEq)]
pub enum Error<H: Hasher, D: Data, MK: MultiKeychain> {
    Invalid(ValidationError<H, D, MK::Signature>),
    Duplicate(SignedUnit<H, D, MK>),
    Uncommitted(SignedUnit<H, D, MK>),
    NewForker(Box<Alert<H, D, MK::Signature>>),
}

impl<H: Hasher, D: Data, MK: MultiKeychain> Debug for Error<H, D, MK> {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        use Error::*;
        match self {
            Invalid(e) => write!(f, "Invalid({:?})", e),
            Duplicate(u) => write!(f, "Duplicate({:?})", u.clone().into_unchecked()),
            Uncommitted(u) => write!(f, "Uncommitted({:?})", u.clone().into_unchecked()),
            NewForker(a) => write!(f, "NewForker({:?})", a),
        }
    }
}

impl<H: Hasher, D: Data, MK: MultiKeychain> From<ValidationError<H, D, MK::Signature>>
    for Error<H, D, MK>
{
    fn from(e: ValidationError<H, D, MK::Signature>) -> Self {
        Error::Invalid(e)
    }
}

/// The summary status of the validator.
pub struct ValidatorStatus {
    processing_units: UnitStoreStatus,
    known_forkers: NodeSubset,
}

impl ValidatorStatus {
    /// The highest round among the units that are currently processing.
    pub fn top_round(&self) -> Round {
        self.processing_units.top_round()
    }
}

impl Display for ValidatorStatus {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        write!(
            f,
            "processing units: ({}), forkers: {}",
            self.processing_units, self.known_forkers
        )
    }
}

type ValidatorResult<H, D, MK> = Result<SignedUnit<H, D, MK>, Error<H, D, MK>>;

/// A validator that checks basic properties of units and catches forks.
pub struct Validator<H: Hasher, D: Data, MK: MultiKeychain> {
    unit_validator: UnitValidator<MK>,
    processing_units: UnitStore<SignedUnit<H, D, MK>>,
    known_forkers: NodeSubset,
}

impl<H: Hasher, D: Data, MK: MultiKeychain> Validator<H, D, MK> {
    /// A new validator using the provided unit validator under the hood.
    pub fn new(unit_validator: UnitValidator<MK>) -> Self {
        let node_count = unit_validator.node_count();
        Validator {
            unit_validator,
            processing_units: UnitStore::new(node_count),
            known_forkers: NodeSubset::with_size(node_count),
        }
    }

    fn is_forker(&self, node_id: NodeIndex) -> bool {
        self.known_forkers[node_id]
    }

    fn mark_forker<U: WrappedUnit<H, Wrapped = SignedUnit<H, D, MK>>>(
        &mut self,
        forker: NodeIndex,
        store: &UnitStore<U>,
    ) -> Vec<UncheckedSignedUnit<H, D, MK::Signature>> {
        assert!(!self.is_forker(forker), "we shouldn't mark a forker twice");
        self.known_forkers.insert(forker);
        store
            .canonical_units(forker)
            .cloned()
            .map(WrappedUnit::unpack)
            // In principle we can have "canonical" processing units that are forks of store canonical units,
            // but only after we already marked a node as a forker, so not yet.
            // Also note that these units can be from different branches and we still commit to them here.
            // This is somewhat confusing, but not a problem for any theoretical guarantees.
            .chain(self.processing_units.canonical_units(forker).cloned())
            .map(|unit| unit.into_unchecked())
            .collect()
    }

    fn pre_validate<U: WrappedUnit<H, Wrapped = SignedUnit<H, D, MK>>>(
        &mut self,
        unit: UncheckedSignedUnit<H, D, MK::Signature>,
        store: &UnitStore<U>,
    ) -> ValidatorResult<H, D, MK> {
        let unit = self.unit_validator.validate_unit(unit)?;
        let unit_hash = unit.as_signable().hash();
        if store.unit(&unit_hash).is_some() || self.processing_units.unit(&unit_hash).is_some() {
            return Err(Error::Duplicate(unit));
        }
        Ok(unit)
    }

    /// Validate an incoming unit.
    pub fn validate<U: WrappedUnit<H, Wrapped = SignedUnit<H, D, MK>>>(
        &mut self,
        unit: UncheckedSignedUnit<H, D, MK::Signature>,
        store: &UnitStore<U>,
    ) -> ValidatorResult<H, D, MK> {
        use Error::*;
        let unit = self.pre_validate(unit, store)?;
        let unit_coord = unit.as_signable().coord();
        if self.is_forker(unit_coord.creator()) {
            return Err(Uncommitted(unit));
        }
        if let Some(canonical_unit) = store
            .canonical_unit(unit_coord)
            .map(|unit| unit.clone().unpack())
            .or(self.processing_units.canonical_unit(unit_coord).cloned())
        {
            let proof = (canonical_unit.into(), unit.into());
            let committed_units = self.mark_forker(unit_coord.creator(), store);
            return Err(NewForker(Box::new(Alert::new(
                self.unit_validator.index(),
                proof,
                committed_units,
            ))));
        }
        self.processing_units.insert(unit.clone());
        Ok(unit)
    }

    /// Validate a committed unit, it has to be from a forker.
    pub fn validate_committed<U: WrappedUnit<H, Wrapped = SignedUnit<H, D, MK>>>(
        &mut self,
        unit: UncheckedSignedUnit<H, D, MK::Signature>,
        store: &UnitStore<U>,
    ) -> ValidatorResult<H, D, MK> {
        let unit = self.pre_validate(unit, store)?;
        assert!(
            self.is_forker(unit.creator()),
            "We should only receive committed units for known forkers."
        );
        self.processing_units.insert(unit.clone());
        Ok(unit)
    }

    /// The store of units currently being processed.
    pub fn processing_units(&self) -> &UnitStore<SignedUnit<H, D, MK>> {
        &self.processing_units
    }

    /// Signal that a unit finished processing and thus it's copy no longer has to be kept for fork detection.
    /// NOTE: This is only a memory optimization, if the units stay there forever everything still works.
    pub fn finished_processing(&mut self, unit: &H::Hash) {
        self.processing_units.remove(unit)
    }

    /// The status summary of this validator.
    pub fn status(&self) -> ValidatorStatus {
        ValidatorStatus {
            processing_units: self.processing_units.status(),
            known_forkers: self.known_forkers.clone(),
        }
    }
}

#[cfg(test)]
mod test {
    use crate::{
        dag::validation::{Error, Validator},
        units::{
            random_full_parent_units_up_to, Unit, UnitStore, Validator as UnitValidator,
            WrappedSignedUnit,
        },
        NodeCount, NodeIndex, Signed,
    };
    use aleph_bft_mock::Keychain;

    #[test]
    fn validates_trivially_correct() {
        let node_count = NodeCount(7);
        let session_id = 0;
        let max_round = 2137;
        let keychains: Vec<_> = node_count
            .into_iterator()
            .map(|node_id| Keychain::new(node_count, node_id))
            .collect();
        let store = UnitStore::<WrappedSignedUnit>::new(node_count);
        let mut validator = Validator::new(UnitValidator::new(session_id, keychains[0], max_round));
        for unit in random_full_parent_units_up_to(4, node_count, session_id)
            .iter()
            .flatten()
            .map(|unit| Signed::sign(unit.clone(), &keychains[unit.creator().0]))
        {
            assert_eq!(
                validator.validate(unit.clone().into(), &store),
                Ok(unit.clone())
            );
        }
    }

    #[test]
    fn refuses_processing_duplicates() {
        let node_count = NodeCount(7);
        let session_id = 0;
        let max_round = 2137;
        let keychains: Vec<_> = node_count
            .into_iterator()
            .map(|node_id| Keychain::new(node_count, node_id))
            .collect();
        let store = UnitStore::<WrappedSignedUnit>::new(node_count);
        let mut validator = Validator::new(UnitValidator::new(session_id, keychains[0], max_round));
        let unit = random_full_parent_units_up_to(0, node_count, session_id)
            .first()
            .expect("we have the first round")
            .first()
            .expect("we have the initial unit for the zeroth creator")
            .clone();
        let unit = Signed::sign(unit, &keychains[0]);
        assert_eq!(
            validator.validate(unit.clone().into(), &store),
            Ok(unit.clone())
        );
        assert_eq!(
            validator.validate(unit.clone().into(), &store),
            Err(Error::Duplicate(unit.clone()))
        );
    }

    #[test]
    fn refuses_external_duplicates() {
        let node_count = NodeCount(7);
        let session_id = 0;
        let max_round = 2137;
        let keychains: Vec<_> = node_count
            .into_iterator()
            .map(|node_id| Keychain::new(node_count, node_id))
            .collect();
        let mut store = UnitStore::new(node_count);
        let mut validator = Validator::new(UnitValidator::new(session_id, keychains[0], max_round));
        let unit = random_full_parent_units_up_to(0, node_count, session_id)
            .first()
            .expect("we have the first round")
            .first()
            .expect("we have the initial unit for the zeroth creator")
            .clone();
        let unit = Signed::sign(unit, &keychains[0]);
        store.insert(WrappedSignedUnit(unit.clone()));
        assert_eq!(
            validator.validate(unit.clone().into(), &store),
            Err(Error::Duplicate(unit.clone()))
        );
    }

    #[test]
    fn detects_processing_fork() {
        let node_count = NodeCount(7);
        let session_id = 0;
        let max_round = 2137;
        let produced_round = 4;
        let keychains: Vec<_> = node_count
            .into_iterator()
            .map(|node_id| Keychain::new(node_count, node_id))
            .collect();
        let store = UnitStore::<WrappedSignedUnit>::new(node_count);
        let mut validator = Validator::new(UnitValidator::new(session_id, keychains[0], max_round));
        for unit in random_full_parent_units_up_to(produced_round, node_count, session_id)
            .iter()
            .flatten()
            .map(|unit| Signed::sign(unit.clone(), &keychains[unit.creator().0]))
        {
            assert_eq!(
                validator.validate(unit.clone().into(), &store),
                Ok(unit.clone())
            );
        }
        let fork = random_full_parent_units_up_to(2, node_count, session_id)
            .get(2)
            .expect("we have the requested round")
            .first()
            .expect("we have the unit for the zeroth creator")
            .clone();
        let fork = Signed::sign(fork, &keychains[0]);
        assert!(matches!(
            validator.validate(fork.clone().into(), &store),
            Err(Error::NewForker(_))
        ));
    }

    #[test]
    fn detects_external_fork() {
        let node_count = NodeCount(7);
        let session_id = 0;
        let max_round = 2137;
        let produced_round = 4;
        let keychains: Vec<_> = node_count
            .into_iterator()
            .map(|node_id| Keychain::new(node_count, node_id))
            .collect();
        let mut store = UnitStore::new(node_count);
        let mut validator = Validator::new(UnitValidator::new(session_id, keychains[0], max_round));
        for unit in random_full_parent_units_up_to(produced_round, node_count, session_id)
            .iter()
            .flatten()
            .map(|unit| Signed::sign(unit.clone(), &keychains[unit.creator().0]))
        {
            store.insert(WrappedSignedUnit(unit));
        }
        let fork = random_full_parent_units_up_to(2, node_count, session_id)
            .get(2)
            .expect("we have the requested round")
            .first()
            .expect("we have the unit for the zeroth creator")
            .clone();
        let fork = Signed::sign(fork, &keychains[0]);
        assert!(matches!(
            validator.validate(fork.clone().into(), &store),
            Err(Error::NewForker(_))
        ));
    }

    #[test]
    fn refuses_uncommitted() {
        let node_count = NodeCount(7);
        let session_id = 0;
        let max_round = 2137;
        let produced_round = 4;
        let keychains: Vec<_> = node_count
            .into_iterator()
            .map(|node_id| Keychain::new(node_count, node_id))
            .collect();
        let store = UnitStore::<WrappedSignedUnit>::new(node_count);
        let mut validator = Validator::new(UnitValidator::new(session_id, keychains[0], max_round));
        let fork = random_full_parent_units_up_to(2, node_count, session_id)
            .get(2)
            .expect("we have the requested round")
            .first()
            .expect("we have the unit for the zeroth creator")
            .clone();
        let fork = Signed::sign(fork, &keychains[0]);
        for unit in random_full_parent_units_up_to(produced_round, node_count, session_id)
            .iter()
            .flatten()
            .filter(|unit| unit.creator() == NodeIndex(0))
            .map(|unit| Signed::sign(unit.clone(), &keychains[unit.creator().0]))
        {
            match unit.round() {
                0..=1 => assert_eq!(
                    validator.validate(unit.clone().into(), &store),
                    Ok(unit.clone())
                ),
                2 => {
                    assert_eq!(
                        validator.validate(unit.clone().into(), &store),
                        Ok(unit.clone())
                    );
                    assert!(matches!(
                        validator.validate(fork.clone().into(), &store),
                        Err(Error::NewForker(_))
                    ))
                }
                3.. => assert_eq!(
                    validator.validate(unit.clone().into(), &store),
                    Err(Error::Uncommitted(unit.clone()))
                ),
            }
        }
    }

    #[test]
    fn accepts_committed() {
        let node_count = NodeCount(7);
        let session_id = 0;
        let max_round = 2137;
        let produced_round = 4;
        let keychains: Vec<_> = node_count
            .into_iterator()
            .map(|node_id| Keychain::new(node_count, node_id))
            .collect();
        let store = UnitStore::<WrappedSignedUnit>::new(node_count);
        let mut validator = Validator::new(UnitValidator::new(session_id, keychains[0], max_round));
        let fork = random_full_parent_units_up_to(2, node_count, session_id)
            .get(2)
            .expect("we have the requested round")
            .first()
            .expect("we have the unit for the zeroth creator")
            .clone();
        let fork = Signed::sign(fork, &keychains[0]);
        let units: Vec<_> = random_full_parent_units_up_to(produced_round, node_count, session_id)
            .iter()
            .flatten()
            .filter(|unit| unit.creator() == NodeIndex(0))
            .map(|unit| Signed::sign(unit.clone(), &keychains[unit.creator().0]))
            .collect();
        for unit in units.iter().take(3) {
            assert_eq!(
                validator.validate(unit.clone().into(), &store),
                Ok(unit.clone())
            );
        }
        assert!(matches!(
            validator.validate(fork.clone().into(), &store),
            Err(Error::NewForker(_))
        ));
        assert_eq!(
            validator.validate_committed(fork.clone().into(), &store),
            Ok(fork)
        );
    }
}