This repository has been archived by the owner on Nov 6, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathlib.rs
3046 lines (2621 loc) · 110 KB
/
lib.rs
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015-2020 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity Ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
//! A blockchain engine that supports a non-instant BFT proof-of-authority.
//!
//! It is recommended to use the `two_thirds_majority_transition` option, to defend against the
//! ["Attack of the Clones"](https://arxiv.org/pdf/1902.10244.pdf). Newly started networks can
//! set this option to `0`, to use a 2/3 quorum from the beginning.
//!
//! To support on-chain governance, the [ValidatorSet] is pluggable: Aura supports simple
//! constant lists of validators as well as smart contract-based dynamic validator sets.
//! Misbehavior is reported to the [ValidatorSet] as well, so that e.g. governance contracts
//! can penalize or ban attacker's nodes.
//!
//! * "Benign" misbehavior are faults that can happen in normal operation, like failing
//! to propose a block in your slot, which could be due to a temporary network outage, or
//! wrong timestamps (due to out-of-sync clocks).
//! * "Malicious" reports are made only if the sender misbehaved deliberately (or due to a
//! software bug), e.g. if they proposed multiple blocks with the same step number.
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::{cmp, fmt};
use std::iter::{self, FromIterator};
use std::ops::Deref;
use std::sync::atomic::{AtomicU64, AtomicBool, Ordering as AtomicOrdering};
use std::sync::{Weak, Arc};
use std::time::{UNIX_EPOCH, Duration};
use std::u64;
use client_traits::{EngineClient, ForceUpdateSealing, TransactionRequest};
use engine::{Engine, ConstructedVerifier};
use block_gas_limit::block_gas_limit;
use block_reward::{self, BlockRewardContract, RewardKind};
use ethjson;
use machine::{
ExecutedBlock,
Machine,
};
use macros::map;
use keccak_hash::keccak;
use log::{info, debug, error, trace, warn};
use lru_cache::LruCache;
use engine::signer::EngineSigner;
use parity_crypto::publickey::Signature;
use io::{IoContext, IoHandler, TimerToken, IoService};
use itertools::{self, Itertools};
use rand::rngs::OsRng;
use rlp::{encode, Decodable, DecoderError, Encodable, RlpStream, Rlp};
use ethereum_types::{H256, H520, Address, U128, U256};
use parity_bytes::Bytes;
use parking_lot::{Mutex, RwLock};
use time_utils::CheckedSystemTime;
use common_types::{
ancestry_action::AncestryAction,
BlockNumber,
header::{Header, ExtendedHeader},
engines::{
Headers,
params::CommonParams,
PendingTransitionStore,
Seal,
SealingState,
machine::{Call, AuxiliaryData},
},
errors::{BlockError, EthcoreError as Error, EngineError},
ids::BlockId,
snapshot::Snapshotting,
transaction::SignedTransaction,
};
use unexpected::{Mismatch, OutOfBounds};
use validator_set::{ValidatorSet, SimpleList, new_validator_set_posdao};
mod finality;
mod randomness;
pub(crate) mod util;
use self::finality::RollingFinality;
/// `AuthorityRound` params.
pub struct AuthorityRoundParams {
/// A map defining intervals of blocks with the given times (in seconds) to wait before next
/// block or authority switching. The keys in the map are steps of starting blocks of those
/// periods. The entry at `0` should be defined.
///
/// Wait times (durations) are additionally required to be less than 65535 since larger values
/// lead to slow block issuance.
pub step_durations: BTreeMap<u64, u64>,
/// Starting step,
pub start_step: Option<u64>,
/// Valid validators.
pub validators: Box<dyn ValidatorSet>,
/// Chain score validation transition block.
pub validate_score_transition: u64,
/// Monotonic step validation transition block.
pub validate_step_transition: u64,
/// Immediate transitions.
pub immediate_transitions: bool,
/// Block reward in base units.
pub block_reward: U256,
/// Block reward contract addresses with their associated starting block numbers.
pub block_reward_contract_transitions: BTreeMap<u64, BlockRewardContract>,
/// Number of accepted uncles transition block.
pub maximum_uncle_count_transition: u64,
/// Number of accepted uncles.
pub maximum_uncle_count: usize,
/// Empty step messages transition block.
pub empty_steps_transition: u64,
/// First block for which a 2/3 quorum (instead of 1/2) is required.
pub two_thirds_majority_transition: BlockNumber,
/// Number of accepted empty steps.
pub maximum_empty_steps: usize,
/// Transition block to strict empty steps validation.
pub strict_empty_steps_transition: u64,
/// If set, enables random number contract integration. It maps the transition block to the contract address.
pub randomness_contract_address: BTreeMap<u64, Address>,
/// The addresses of contracts that determine the block gas limit with their associated block
/// numbers.
pub block_gas_limit_contract_transitions: BTreeMap<u64, Address>,
/// If set, this is the block number at which the consensus engine switches from AuRa to AuRa
/// with POSDAO modifications.
pub posdao_transition: Option<BlockNumber>,
}
const U16_MAX: usize = ::std::u16::MAX as usize;
/// The number of recent block hashes for which the gas limit override is memoized.
const GAS_LIMIT_OVERRIDE_CACHE_CAPACITY: usize = 10;
impl From<ethjson::spec::AuthorityRoundParams> for AuthorityRoundParams {
fn from(p: ethjson::spec::AuthorityRoundParams) -> Self {
let map_step_duration = |u: ethjson::uint::Uint| {
let mut step_duration_usize: usize = u.into();
if step_duration_usize == 0 {
panic!("AuthorityRoundParams: step duration cannot be 0");
}
if step_duration_usize > U16_MAX {
warn!(target: "engine", "step duration is too high ({}), setting it to {}", step_duration_usize, U16_MAX);
step_duration_usize = U16_MAX;
}
step_duration_usize as u64
};
let step_durations: BTreeMap<_, _> = match p.step_duration {
ethjson::spec::StepDuration::Single(u) =>
iter::once((0, map_step_duration(u))).collect(),
ethjson::spec::StepDuration::Transitions(tr) => {
if tr.is_empty() {
panic!("AuthorityRoundParams: step duration transitions cannot be empty");
}
tr.into_iter().map(|(timestamp, u)| (timestamp.into(), map_step_duration(u))).collect()
}
};
let transition_block_num = p.block_reward_contract_transition.map_or(0, Into::into);
let mut br_transitions: BTreeMap<_, _> = p.block_reward_contract_transitions
.unwrap_or_default()
.into_iter()
.map(|(block_num, address)|
(block_num.into(), BlockRewardContract::new_from_address(address.into())))
.collect();
if (p.block_reward_contract_code.is_some() || p.block_reward_contract_address.is_some()) &&
br_transitions.keys().next().map_or(false, |&block_num| block_num <= transition_block_num)
{
let s = "blockRewardContractTransition";
panic!("{} should be less than any of the keys in {}s", s, s);
}
if let Some(code) = p.block_reward_contract_code {
br_transitions.insert(
transition_block_num,
BlockRewardContract::new_from_code(Arc::new(code.into()))
);
} else if let Some(address) = p.block_reward_contract_address {
br_transitions.insert(
transition_block_num,
BlockRewardContract::new_from_address(address.into())
);
}
let randomness_contract_address = p.randomness_contract_address.map_or_else(BTreeMap::new, |transitions| {
transitions.into_iter().map(|(ethjson::uint::Uint(block), addr)| {
(block.as_u64(), addr.into())
}).collect()
});
let block_gas_limit_contract_transitions: BTreeMap<_, _> =
p.block_gas_limit_contract_transitions
.unwrap_or_default()
.into_iter()
.map(|(block_num, address)| (block_num.into(), address.into()))
.collect();
AuthorityRoundParams {
step_durations,
validators: new_validator_set_posdao(p.validators, p.posdao_transition.map(Into::into)),
start_step: p.start_step.map(Into::into),
validate_score_transition: p.validate_score_transition.map_or(0, Into::into),
validate_step_transition: p.validate_step_transition.map_or(0, Into::into),
immediate_transitions: p.immediate_transitions.unwrap_or(false),
block_reward: p.block_reward.map_or_else(Default::default, Into::into),
block_reward_contract_transitions: br_transitions,
maximum_uncle_count_transition: p.maximum_uncle_count_transition.map_or(0, Into::into),
maximum_uncle_count: p.maximum_uncle_count.map_or(0, Into::into),
empty_steps_transition: p.empty_steps_transition.map_or(u64::max_value(), |n| ::std::cmp::max(n.into(), 1)),
maximum_empty_steps: p.maximum_empty_steps.map_or(0, Into::into),
two_thirds_majority_transition: p.two_thirds_majority_transition.map_or_else(BlockNumber::max_value, Into::into),
strict_empty_steps_transition: p.strict_empty_steps_transition.map_or(0, Into::into),
randomness_contract_address,
block_gas_limit_contract_transitions,
posdao_transition: p.posdao_transition.map(Into::into),
}
}
}
/// A triple containing the first step number and the starting timestamp of the given step duration.
#[derive(Clone, Copy, Debug)]
struct StepDurationInfo {
transition_step: u64,
transition_timestamp: u64,
step_duration: u64,
}
/// Helper for managing the step.
#[derive(Debug)]
struct Step {
calibrate: bool, // whether calibration is enabled.
inner: AtomicU64,
/// Planned durations of steps.
durations: Vec<StepDurationInfo>,
}
impl Step {
fn load(&self) -> u64 { self.inner.load(AtomicOrdering::SeqCst) }
/// Finds the remaining duration of the current step. Panics if there was a counter under- or
/// overflow.
fn duration_remaining(&self) -> Duration {
self.opt_duration_remaining().unwrap_or_else(|| {
let ctr = self.load();
error!(target: "engine", "Step counter under- or overflow: {}, aborting", ctr);
panic!("step counter under- or overflow: {}", ctr)
})
}
/// Finds the remaining duration of the current step. Returns `None` if there was a counter
/// under- or overflow.
fn opt_duration_remaining(&self) -> Option<Duration> {
let next_step = self.load().checked_add(1)?;
let StepDurationInfo { transition_step, transition_timestamp, step_duration } =
self.durations.iter()
.take_while(|info| info.transition_step < next_step)
.last()
.expect("durations cannot be empty")
.clone();
let next_time = transition_timestamp
.checked_add(next_step.checked_sub(transition_step)?.checked_mul(step_duration)?)?;
Some(Duration::from_secs(next_time.saturating_sub(unix_now().as_secs())))
}
/// Increments the step number.
///
/// Panics if the new step number is `u64::MAX`.
fn increment(&self) {
// fetch_add won't panic on overflow but will rather wrap
// around, leading to zero as the step counter, which might
// lead to unexpected situations, so it's better to shut down.
if self.inner.fetch_add(1, AtomicOrdering::SeqCst) == u64::MAX {
error!(target: "engine", "Step counter is too high: {}, aborting", u64::MAX);
panic!("step counter is too high: {}", u64::MAX);
}
}
fn calibrate(&self) {
if self.calibrate {
if self.opt_calibrate().is_none() {
let ctr = self.load();
error!(target: "engine", "Step counter under- or overflow: {}, aborting", ctr);
panic!("step counter under- or overflow: {}", ctr)
}
}
}
/// Calibrates the AuRa step number according to the current time.
fn opt_calibrate(&self) -> Option<()> {
let now = unix_now().as_secs();
let StepDurationInfo { transition_step, transition_timestamp, step_duration } =
self.durations.iter()
.take_while(|info| info.transition_timestamp < now)
.last()
.expect("durations cannot be empty")
.clone();
let new_step = (now.checked_sub(transition_timestamp)? / step_duration)
.checked_add(transition_step)?;
self.inner.store(new_step, AtomicOrdering::SeqCst);
Some(())
}
fn check_future(&self, given: u64) -> Result<(), Option<OutOfBounds<u64>>> {
const REJECTED_STEP_DRIFT: u64 = 4;
// Verify if the step is correct.
if given <= self.load() {
return Ok(());
}
// Make absolutely sure that the given step is incorrect.
self.calibrate();
let current = self.load();
// reject blocks too far in the future
if given > current + REJECTED_STEP_DRIFT {
Err(None)
// wait a bit for blocks in near future
} else if given > current {
let d = self.durations.iter().take_while(|info| info.transition_step <= current).last()
.expect("Duration map has at least a 0 entry.")
.step_duration;
Err(Some(OutOfBounds {
min: None,
max: Some(d * current),
found: d * given,
}))
} else {
Ok(())
}
}
}
// Chain scoring: total weight is sqrt(U256::max_value())*height - step
fn calculate_score(parent_step: u64, current_step: u64, current_empty_steps: usize) -> U256 {
U256::from(U128::max_value()) + U256::from(parent_step) - U256::from(current_step) + U256::from(current_empty_steps)
}
struct EpochManager {
epoch_transition_hash: H256,
epoch_transition_number: BlockNumber,
finality_checker: RollingFinality,
force: bool,
}
impl EpochManager {
fn blank(two_thirds_majority_transition: BlockNumber) -> Self {
EpochManager {
epoch_transition_hash: H256::zero(),
epoch_transition_number: 0,
finality_checker: RollingFinality::blank(Vec::new(), two_thirds_majority_transition),
force: true,
}
}
// Zooms to the epoch after the header with the given hash. Returns true if succeeded, false otherwise.
fn zoom_to_after(
&mut self,
client: &dyn EngineClient,
machine: &Machine,
validators: &dyn ValidatorSet,
hash: H256
) -> bool {
let last_was_parent = self.finality_checker.subchain_head() == Some(hash);
// early exit for current target == chain head, but only if the epochs are
// the same.
if last_was_parent && !self.force {
return true;
}
self.force = false;
debug!(target: "engine", "Zooming to epoch after block {}", hash);
trace!(target: "engine", "Current validator set: {:?}", self.validators());
// epoch_transition_for can be an expensive call, but in the absence of
// forks it will only need to be called for the block directly after
// epoch transition, in which case it will be O(1) and require a single
// DB lookup.
let last_transition = match client.epoch_transition_for(hash) {
Some(t) => t,
None => {
// this really should never happen unless the block passed
// hasn't got a parent in the database.
warn!(target: "engine", "No genesis transition found. Block hash {} does not have a parent in the DB", hash);
return false;
}
};
// extract other epoch set if it's not the same as the last.
if last_transition.block_hash != self.epoch_transition_hash {
let (signal_number, set_proof, _) = destructure_proofs(&last_transition.proof)
.expect("proof produced by this engine; therefore it is valid; qed");
trace!(
target: "engine",
"extracting epoch validator set for epoch ({}, {}) signalled at #{}",
last_transition.block_number, last_transition.block_hash, signal_number
);
let first = signal_number == 0;
let (list, _) = validators.epoch_set(
first,
machine,
signal_number, // use signal number so multi-set first calculation is correct.
set_proof,
).expect("proof produced by this engine; therefore it is valid; qed");
trace!(
target: "engine",
"Updating finality checker with new validator set extracted from epoch ({}, {}): {:?}",
last_transition.block_number, last_transition.block_hash, &list
);
let epoch_set = list.into_inner();
let two_thirds_majority_transition = self.finality_checker.two_thirds_majority_transition();
self.finality_checker = RollingFinality::blank(epoch_set, two_thirds_majority_transition);
}
self.epoch_transition_hash = last_transition.block_hash;
self.epoch_transition_number = last_transition.block_number;
true
}
// Note new epoch hash. This will force the next block to re-load
// the epoch set.
// TODO: optimize and don't require re-loading after epoch change.
fn note_new_epoch(&mut self) {
self.force = true;
}
/// Get validator set. Zoom to the correct epoch first.
fn validators(&self) -> &SimpleList {
self.finality_checker.validators()
}
}
/// A message broadcast by authorities when it's their turn to seal a block but there are no
/// transactions. Other authorities accumulate these messages and later include them in the seal as
/// proof.
///
/// An empty step message is created _instead of_ a block if there are no pending transactions.
/// It cannot itself be a parent, and `parent_hash` always points to the most recent block. E.g.:
/// * Validator A creates block `bA`.
/// * Validator B has no pending transactions, so it signs an empty step message `mB`
/// instead whose hash points to block `bA`.
/// * Validator C also has no pending transactions, so it also signs an empty step message `mC`
/// instead whose hash points to block `bA`.
/// * Validator D creates block `bD`. The parent is block `bA`, and the header includes `mB` and `mC`.
#[derive(Clone, Debug, PartialEq, Eq)]
struct EmptyStep {
/// The signature of the other two fields, by the message's author.
signature: H520,
/// This message's step number.
step: u64,
/// The hash of the most recent block.
parent_hash: H256,
}
impl PartialOrd for EmptyStep {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for EmptyStep {
fn cmp(&self, other: &Self) -> cmp::Ordering {
self.step.cmp(&other.step)
.then_with(|| self.parent_hash.cmp(&other.parent_hash))
.then_with(|| self.signature.cmp(&other.signature))
}
}
impl EmptyStep {
fn from_sealed(sealed_empty_step: SealedEmptyStep, parent_hash: &H256) -> EmptyStep {
let signature = sealed_empty_step.signature;
let step = sealed_empty_step.step;
let parent_hash = parent_hash.clone();
EmptyStep { signature, step, parent_hash }
}
/// Returns `true` if the message has a valid signature by the expected proposer in the message's step.
fn verify(&self, validators: &dyn ValidatorSet) -> Result<bool, Error> {
let message = keccak(empty_step_rlp(self.step, &self.parent_hash));
let correct_proposer = step_proposer(validators, &self.parent_hash, self.step);
parity_crypto::publickey::verify_address(
&correct_proposer,
&self.signature.into(),
&message,
)
.map_err(Into::into)
}
fn author(&self) -> Result<Address, Error> {
let message = keccak(empty_step_rlp(self.step, &self.parent_hash));
let public = parity_crypto::publickey::recover(&self.signature.into(), &message)?;
Ok(parity_crypto::publickey::public_to_address(&public))
}
fn sealed(&self) -> SealedEmptyStep {
let signature = self.signature;
let step = self.step;
SealedEmptyStep { signature, step }
}
}
impl fmt::Display for EmptyStep {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "({:x}, {}, {:x})", self.signature, self.step, self.parent_hash)
}
}
impl Encodable for EmptyStep {
fn rlp_append(&self, s: &mut RlpStream) {
let empty_step_rlp = empty_step_rlp(self.step, &self.parent_hash);
s.begin_list(2)
.append(&self.signature)
.append_raw(&empty_step_rlp, 1);
}
}
impl Decodable for EmptyStep {
fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
let signature = rlp.val_at(0)?;
let empty_step_rlp = rlp.at(1)?;
let step = empty_step_rlp.val_at(0)?;
let parent_hash = empty_step_rlp.val_at(1)?;
Ok(EmptyStep { signature, step, parent_hash })
}
}
/// Given a signature and an rlp encoded partial empty step containing the step number and parent
/// block hash), returns an RLP blob containing the signature and the partial empty step. This is
/// the wire encoding of an EmptyStep.
pub fn empty_step_full_rlp(signature: &H520, empty_step_rlp: &[u8]) -> Vec<u8> {
let mut s = RlpStream::new_list(2);
s.append(signature).append_raw(empty_step_rlp, 1);
s.out()
}
/// Given the hash of the parent block and a step number, returns an RLP encoded partial empty step
/// ready to be signed.
pub fn empty_step_rlp(step: u64, parent_hash: &H256) -> Vec<u8> {
let mut s = RlpStream::new_list(2);
s.append(&step).append(parent_hash);
s.out()
}
/// An empty step message that is included in a seal, the only difference is that it doesn't include
/// the `parent_hash` in order to save space. The included signature is of the original empty step
/// message, which can be reconstructed by using the parent hash of the block in which this sealed
/// empty message is included.
struct SealedEmptyStep {
signature: H520,
step: u64,
}
impl Encodable for SealedEmptyStep {
fn rlp_append(&self, s: &mut RlpStream) {
s.begin_list(2)
.append(&self.signature)
.append(&self.step);
}
}
impl Decodable for SealedEmptyStep {
fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
let signature = rlp.val_at(0)?;
let step = rlp.val_at(1)?;
Ok(SealedEmptyStep { signature, step })
}
}
struct PermissionedStep {
inner: Step,
can_propose: AtomicBool,
}
/// Engine using `AuthorityRound` proof-of-authority BFT consensus.
pub struct AuthorityRound {
transition_service: IoService<()>,
step: Arc<PermissionedStep>,
client: Arc<RwLock<Option<Weak<dyn EngineClient>>>>,
signer: RwLock<Option<Box<dyn EngineSigner>>>,
validators: Box<dyn ValidatorSet>,
validate_score_transition: u64,
validate_step_transition: u64,
empty_steps: Mutex<BTreeSet<EmptyStep>>,
epoch_manager: Mutex<EpochManager>,
immediate_transitions: bool,
block_reward: U256,
block_reward_contract_transitions: BTreeMap<u64, BlockRewardContract>,
maximum_uncle_count_transition: u64,
maximum_uncle_count: usize,
empty_steps_transition: u64,
strict_empty_steps_transition: u64,
two_thirds_majority_transition: BlockNumber,
maximum_empty_steps: usize,
machine: Machine,
/// History of step hashes recently received from peers.
received_step_hashes: RwLock<BTreeMap<(u64, Address), H256>>,
/// If set, enables random number contract integration. It maps the transition block to the contract address.
randomness_contract_address: BTreeMap<u64, Address>,
/// The addresses of contracts that determine the block gas limit.
block_gas_limit_contract_transitions: BTreeMap<u64, Address>,
/// Memoized gas limit overrides, by block hash.
gas_limit_override_cache: Mutex<LruCache<H256, Option<U256>>>,
/// The block number at which the consensus engine switches from AuRa to AuRa with POSDAO
/// modifications. For details about POSDAO, see the whitepaper:
/// https://www.xdaichain.com/for-validators/posdao-whitepaper
posdao_transition: Option<BlockNumber>,
}
// header-chain validator.
struct EpochVerifier {
step: Arc<PermissionedStep>,
subchain_validators: SimpleList,
empty_steps_transition: u64,
/// First block for which a 2/3 quorum (instead of 1/2) is required.
two_thirds_majority_transition: BlockNumber,
}
impl engine::EpochVerifier for EpochVerifier {
fn verify_light(&self, header: &Header) -> Result<(), Error> {
// Validate the timestamp
verify_timestamp(&self.step.inner, header_step(header, self.empty_steps_transition)?)?;
// always check the seal since it's fast.
// nothing heavier to do.
verify_external(header, &self.subchain_validators, self.empty_steps_transition)
}
fn check_finality_proof(&self, proof: &[u8]) -> Option<Vec<H256>> {
let signers = self.subchain_validators.clone().into_inner();
let mut finality_checker = RollingFinality::blank(signers, self.two_thirds_majority_transition);
let mut finalized = Vec::new();
let headers: Vec<Header> = Rlp::new(proof).as_list().ok()?;
{
let mut push_header = |parent_header: &Header, header: Option<&Header>| {
// ensure all headers have correct number of seal fields so we can `verify_external`
// and get `empty_steps` without panic.
if parent_header.seal().len() != header_expected_seal_fields(parent_header, self.empty_steps_transition) {
return None
}
if header.iter().any(|h| h.seal().len() != header_expected_seal_fields(h, self.empty_steps_transition)) {
return None
}
// `verify_external` checks that signature is correct and author == signer.
verify_external(parent_header, &self.subchain_validators, self.empty_steps_transition).ok()?;
let mut signers = match header {
Some(header) => header_empty_steps_signers(header, self.empty_steps_transition).ok()?,
_ => Vec::new(),
};
signers.push(*parent_header.author());
let newly_finalized =
finality_checker.push_hash(parent_header.hash(), parent_header.number(), signers).ok()?;
finalized.extend(newly_finalized);
Some(())
};
for window in headers.windows(2) {
push_header(&window[0], Some(&window[1]))?;
}
if let Some(last) = headers.last() {
push_header(last, None)?;
}
}
if finalized.is_empty() { None } else { Some(finalized) }
}
}
fn header_seal_hash(header: &Header, empty_steps_rlp: Option<&[u8]>) -> H256 {
match empty_steps_rlp {
Some(empty_steps_rlp) => {
let mut message = header.bare_hash().as_bytes().to_vec();
message.extend_from_slice(empty_steps_rlp);
keccak(message)
},
None => {
header.bare_hash()
},
}
}
fn header_expected_seal_fields(header: &Header, empty_steps_transition: u64) -> usize {
if header.number() >= empty_steps_transition {
3
} else {
2
}
}
fn header_step(header: &Header, empty_steps_transition: u64) -> Result<u64, ::rlp::DecoderError> {
Rlp::new(&header.seal().get(0).unwrap_or_else(||
panic!("was either checked with verify_block_basic or is genesis; has {} fields; qed (Make sure the spec \
file has a correct genesis seal)", header_expected_seal_fields(header, empty_steps_transition))
))
.as_val()
}
fn header_signature(header: &Header, empty_steps_transition: u64) -> Result<Signature, ::rlp::DecoderError> {
Rlp::new(&header.seal().get(1).unwrap_or_else(||
panic!("was checked with verify_block_basic; has {} fields; qed",
header_expected_seal_fields(header, empty_steps_transition))
))
.as_val::<H520>().map(Into::into)
}
// extracts the raw empty steps vec from the header seal. should only be called when there are 3 fields in the seal
// (i.e. header.number() >= self.empty_steps_transition)
fn header_empty_steps_raw(header: &Header) -> &[u8] {
header.seal().get(2).expect("was checked with verify_block_basic; has 3 fields; qed")
}
// extracts the empty steps from the header seal. should only be called when there are 3 fields in the seal
// (i.e. header.number() >= self.empty_steps_transition).
fn header_empty_steps(header: &Header) -> Result<Vec<EmptyStep>, ::rlp::DecoderError> {
let empty_steps = Rlp::new(header_empty_steps_raw(header)).as_list::<SealedEmptyStep>()?;
Ok(empty_steps.into_iter().map(|s| EmptyStep::from_sealed(s, header.parent_hash())).collect())
}
// gets the signers of empty step messages for the given header, does not include repeated signers
fn header_empty_steps_signers(header: &Header, empty_steps_transition: u64) -> Result<Vec<Address>, Error> {
if header.number() >= empty_steps_transition {
let mut signers = HashSet::new();
for empty_step in header_empty_steps(header)? {
signers.insert(empty_step.author()?);
}
Ok(Vec::from_iter(signers.into_iter()))
} else {
Ok(Vec::new())
}
}
fn step_proposer(validators: &dyn ValidatorSet, bh: &H256, step: u64) -> Address {
let proposer = validators.get(bh, step as usize);
trace!(target: "engine", "step_proposer: Fetched proposer for step {}: {}", step, proposer);
proposer
}
fn is_step_proposer(validators: &dyn ValidatorSet, bh: &H256, step: u64, address: &Address) -> bool {
step_proposer(validators, bh, step) == *address
}
fn verify_timestamp(step: &Step, header_step: u64) -> Result<(), BlockError> {
match step.check_future(header_step) {
Err(None) => {
trace!(target: "engine", "verify_timestamp: block from the future");
Err(BlockError::InvalidSeal.into())
},
Err(Some(oob)) => {
// NOTE This error might be returned only in early stage of verification (Stage 1).
// Returning it further won't recover the sync process.
trace!(target: "engine", "verify_timestamp: block too early");
let found = CheckedSystemTime::checked_add(UNIX_EPOCH, Duration::from_secs(oob.found))
.ok_or(BlockError::TimestampOverflow)?;
let max = oob.max.and_then(|m| CheckedSystemTime::checked_add(UNIX_EPOCH, Duration::from_secs(m)));
let min = oob.min.and_then(|m| CheckedSystemTime::checked_add(UNIX_EPOCH, Duration::from_secs(m)));
let new_oob = OutOfBounds { min, max, found };
Err(BlockError::TemporarilyInvalid(new_oob.into()))
},
Ok(_) => Ok(()),
}
}
fn verify_external(header: &Header, validators: &dyn ValidatorSet, empty_steps_transition: u64) -> Result<(), Error> {
let header_step = header_step(header, empty_steps_transition)?;
let proposer_signature = header_signature(header, empty_steps_transition)?;
let correct_proposer = validators.get(header.parent_hash(), header_step as usize);
let is_invalid_proposer = *header.author() != correct_proposer || {
let empty_steps_rlp = if header.number() >= empty_steps_transition {
Some(header_empty_steps_raw(header))
} else {
None
};
let header_seal_hash = header_seal_hash(header, empty_steps_rlp);
!parity_crypto::publickey::verify_address(&correct_proposer, &proposer_signature, &header_seal_hash)?
};
if is_invalid_proposer {
warn!(target: "engine", "verify_block_external: bad proposer for step: {}", header_step);
Err(EngineError::NotProposer(Mismatch { expected: correct_proposer, found: *header.author() }))?
} else {
Ok(())
}
}
fn combine_proofs(signal_number: BlockNumber, set_proof: &[u8], finality_proof: &[u8]) -> Vec<u8> {
let mut stream = RlpStream::new_list(3);
stream.append(&signal_number).append(&set_proof).append(&finality_proof);
stream.out()
}
fn destructure_proofs(combined: &[u8]) -> Result<(BlockNumber, &[u8], &[u8]), Error> {
let rlp = Rlp::new(combined);
Ok((
rlp.at(0)?.as_val()?,
rlp.at(1)?.data()?,
rlp.at(2)?.data()?,
))
}
trait AsMillis {
fn as_millis(&self) -> u64;
}
impl AsMillis for Duration {
fn as_millis(&self) -> u64 {
self.as_secs() * 1_000 + (self.subsec_nanos() / 1_000_000) as u64
}
}
// A type for storing owned or borrowed data that has a common type.
// Useful for returning either a borrow or owned data from a function.
enum CowLike<'a, A: 'a + ?Sized, B> {
Borrowed(&'a A),
Owned(B),
}
impl<'a, A: ?Sized, B> Deref for CowLike<'a, A, B> where B: AsRef<A> {
type Target = A;
fn deref(&self) -> &A {
match self {
CowLike::Borrowed(b) => b,
CowLike::Owned(o) => o.as_ref(),
}
}
}
impl AuthorityRound {
/// Create a new instance of AuthorityRound engine.
pub fn new(our_params: AuthorityRoundParams, machine: Machine) -> Result<Arc<Self>, Error> {
if !our_params.step_durations.contains_key(&0) {
error!(target: "engine", "Authority Round step 0 duration is undefined, aborting");
return Err(Error::Engine(EngineError::Custom(String::from("step 0 duration is undefined"))));
}
if our_params.step_durations.values().any(|v| *v == 0) {
error!(target: "engine", "Authority Round step duration cannot be 0");
return Err(Error::Engine(EngineError::Custom(String::from("step duration cannot be 0"))));
}
let should_timeout = our_params.start_step.is_none();
let initial_step = our_params.start_step.unwrap_or(0);
let mut durations = Vec::new();
{
let mut dur_info = StepDurationInfo {
transition_step: 0u64,
transition_timestamp: 0u64,
step_duration: our_params.step_durations[&0],
};
durations.push(dur_info);
for (time, dur) in our_params.step_durations.iter().skip(1) {
let (step, time) = next_step_time_duration(dur_info, *time)
.ok_or(BlockError::TimestampOverflow)?;
dur_info.transition_step = step;
dur_info.transition_timestamp = time;
dur_info.step_duration = *dur;
durations.push(dur_info);
}
}
let step = Step {
inner: AtomicU64::new(initial_step),
calibrate: our_params.start_step.is_none(),
durations,
};
step.calibrate();
let engine = Arc::new(
AuthorityRound {
transition_service: IoService::<()>::start()?,
step: Arc::new(PermissionedStep { inner: step, can_propose: AtomicBool::new(true) }),
client: Arc::new(RwLock::new(None)),
signer: RwLock::new(None),
validators: our_params.validators,
validate_score_transition: our_params.validate_score_transition,
validate_step_transition: our_params.validate_step_transition,
empty_steps: Default::default(),
epoch_manager: Mutex::new(EpochManager::blank(our_params.two_thirds_majority_transition)),
immediate_transitions: our_params.immediate_transitions,
block_reward: our_params.block_reward,
block_reward_contract_transitions: our_params.block_reward_contract_transitions,
maximum_uncle_count_transition: our_params.maximum_uncle_count_transition,
maximum_uncle_count: our_params.maximum_uncle_count,
empty_steps_transition: our_params.empty_steps_transition,
maximum_empty_steps: our_params.maximum_empty_steps,
two_thirds_majority_transition: our_params.two_thirds_majority_transition,
strict_empty_steps_transition: our_params.strict_empty_steps_transition,
machine,
received_step_hashes: RwLock::new(Default::default()),
randomness_contract_address: our_params.randomness_contract_address,
block_gas_limit_contract_transitions: our_params.block_gas_limit_contract_transitions,
gas_limit_override_cache: Mutex::new(LruCache::new(GAS_LIMIT_OVERRIDE_CACHE_CAPACITY)),
posdao_transition: our_params.posdao_transition,
});
// Do not initialize timeouts for tests.
if should_timeout {
let handler = TransitionHandler {
step: engine.step.clone(),
client: engine.client.clone(),
};
engine.transition_service.register_handler(Arc::new(handler))?;
}
Ok(engine)
}
// fetch correct validator set for epoch at header, taking into account
// finality of previous transitions.
fn epoch_set<'a>(&'a self, header: &Header) -> Result<(CowLike<dyn ValidatorSet, SimpleList>, BlockNumber), Error> {
Ok(if self.immediate_transitions {
(CowLike::Borrowed(&*self.validators), header.number())
} else {
let mut epoch_manager = self.epoch_manager.lock();
let client = self.upgrade_client_or("Unable to verify sig")?;
if !epoch_manager.zoom_to_after(&*client, &self.machine, &*self.validators, *header.parent_hash()) {
debug!(target: "engine", "Unable to zoom to epoch.");
return Err(EngineError::MissingParent(*header.parent_hash()).into())
}
(CowLike::Owned(epoch_manager.validators().clone()), epoch_manager.epoch_transition_number)
})
}
/// Return the `EmptyStep`s matching the step interval (non-inclusive) and parent hash.
fn empty_steps(&self, from_step: u64, to_step: u64, parent_hash: H256) -> Vec<EmptyStep> {
let from = EmptyStep {
step: from_step + 1,
parent_hash,
signature: Default::default(),
};
let to = EmptyStep {
step: to_step,
parent_hash: Default::default(),
signature: Default::default(),
};
if from >= to {
return vec![];
}
self.empty_steps.lock()
.range(from..to)
.filter(|e| e.parent_hash == parent_hash)
.cloned()
.collect()
}
/// Drops all `EmptySteps` less than or equal to the passed `step`, irregardless of the parent hash.
fn clear_empty_steps(&self, step: u64) {
let mut empty_steps = self.empty_steps.lock();
*empty_steps = empty_steps.split_off(&EmptyStep {
step: step + 1,
parent_hash: Default::default(),
signature: Default::default(),
});
}
fn store_empty_step(&self, empty_step: EmptyStep) {
self.empty_steps.lock().insert(empty_step);
}
/// Build an EmptyStep and broadcast it to the network.
fn emit_empty_step(&self, parent_hash: &H256) {
let step = self.step.inner.load();
let empty_step_rlp = empty_step_rlp(step, parent_hash);
if let Ok(signature) = self.sign(keccak(&empty_step_rlp)).map(Into::into) {
let parent_hash = *parent_hash;
let empty_step = EmptyStep { signature, step, parent_hash };
trace!(target: "engine", "broadcasting empty step message: {:?}", empty_step);
if let Ok(c) = self.upgrade_client_or("could not broadcast empty step message") {
self.store_empty_step(empty_step);
c.broadcast_consensus_message(empty_step_full_rlp(&signature, &empty_step_rlp));
}
} else {
warn!(target: "engine", "generate_empty_step: FAIL: accounts secret key unavailable");
}