This repository has been archived by the owner on Nov 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
environment.rs
1513 lines (1319 loc) · 45.5 KB
/
environment.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
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program 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.
// This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
use std::{
collections::{BTreeMap, HashMap},
iter::FromIterator,
marker::PhantomData,
pin::Pin,
sync::Arc,
time::Duration,
};
use finality_grandpa::{
round::State as RoundState, voter, voter_set::VoterSet, BlockNumberOps, Error as GrandpaError,
};
use futures::prelude::*;
use futures_timer::Delay;
use log::{debug, warn};
use parity_scale_codec::{Decode, Encode};
use parking_lot::RwLock;
use prometheus_endpoint::{register, Counter, Gauge, PrometheusError, U64};
use sc_client_api::{
backend::{apply_aux, Backend as BackendT},
utils::is_descendent_of,
};
use sc_telemetry::{telemetry, TelemetryHandle, CONSENSUS_DEBUG, CONSENSUS_INFO};
use sp_blockchain::HeaderMetadata;
use sp_consensus::SelectChain as SelectChainT;
use sp_consensus_grandpa::{
AuthorityId, AuthoritySignature, Equivocation, EquivocationProof, GrandpaApi, RoundNumber,
SetId, GRANDPA_ENGINE_ID,
};
use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor, Zero};
use crate::{
authorities::{AuthoritySet, SharedAuthoritySet},
communication::{Network as NetworkT, Syncing as SyncingT},
justification::GrandpaJustification,
local_authority_id,
notification::GrandpaJustificationSender,
until_imported::UntilVoteTargetImported,
voting_rule::VotingRule as VotingRuleT,
ClientForGrandpa, CommandOrError, Commit, Config, Error, NewAuthoritySet, Precommit, Prevote,
PrimaryPropose, SignedMessage, VoterCommand, LOG_TARGET,
};
type HistoricalVotes<Block> = finality_grandpa::HistoricalVotes<
<Block as BlockT>::Hash,
NumberFor<Block>,
AuthoritySignature,
AuthorityId,
>;
/// Data about a completed round. The set of votes that is stored must be
/// minimal, i.e. at most one equivocation is stored per voter.
#[derive(Debug, Clone, Decode, Encode, PartialEq)]
pub struct CompletedRound<Block: BlockT> {
/// The round number.
pub number: RoundNumber,
/// The round state (prevote ghost, estimate, finalized, etc.)
pub state: RoundState<Block::Hash, NumberFor<Block>>,
/// The target block base used for voting in the round.
pub base: (Block::Hash, NumberFor<Block>),
/// All the votes observed in the round.
pub votes: Vec<SignedMessage<Block::Header>>,
}
// Data about last completed rounds within a single voter set. Stores
// NUM_LAST_COMPLETED_ROUNDS and always contains data about at least one round
// (genesis).
#[derive(Debug, Clone, PartialEq)]
pub struct CompletedRounds<Block: BlockT> {
rounds: Vec<CompletedRound<Block>>,
set_id: SetId,
voters: Vec<AuthorityId>,
}
// NOTE: the current strategy for persisting completed rounds is very naive
// (update everything) and we also rely on cloning to do atomic updates,
// therefore this value should be kept small for now.
const NUM_LAST_COMPLETED_ROUNDS: usize = 2;
impl<Block: BlockT> Encode for CompletedRounds<Block> {
fn encode(&self) -> Vec<u8> {
let v = Vec::from_iter(&self.rounds);
(&v, &self.set_id, &self.voters).encode()
}
}
impl<Block: BlockT> parity_scale_codec::EncodeLike for CompletedRounds<Block> {}
impl<Block: BlockT> Decode for CompletedRounds<Block> {
fn decode<I: parity_scale_codec::Input>(
value: &mut I,
) -> Result<Self, parity_scale_codec::Error> {
<(Vec<CompletedRound<Block>>, SetId, Vec<AuthorityId>)>::decode(value)
.map(|(rounds, set_id, voters)| CompletedRounds { rounds, set_id, voters })
}
}
impl<Block: BlockT> CompletedRounds<Block> {
/// Create a new completed rounds tracker with NUM_LAST_COMPLETED_ROUNDS capacity.
pub(crate) fn new(
genesis: CompletedRound<Block>,
set_id: SetId,
voters: &AuthoritySet<Block::Hash, NumberFor<Block>>,
) -> CompletedRounds<Block> {
let mut rounds = Vec::with_capacity(NUM_LAST_COMPLETED_ROUNDS);
rounds.push(genesis);
let voters = voters.current_authorities.iter().map(|(a, _)| a.clone()).collect();
CompletedRounds { rounds, set_id, voters }
}
/// Get the set-id and voter set of the completed rounds.
pub fn set_info(&self) -> (SetId, &[AuthorityId]) {
(self.set_id, &self.voters[..])
}
/// Iterate over all completed rounds.
pub fn iter(&self) -> impl Iterator<Item = &CompletedRound<Block>> {
self.rounds.iter().rev()
}
/// Returns the last (latest) completed round.
pub fn last(&self) -> &CompletedRound<Block> {
self.rounds
.first()
.expect("inner is never empty; always contains at least genesis; qed")
}
/// Push a new completed round, oldest round is evicted if number of rounds
/// is higher than `NUM_LAST_COMPLETED_ROUNDS`.
pub fn push(&mut self, completed_round: CompletedRound<Block>) {
use std::cmp::Reverse;
match self
.rounds
.binary_search_by_key(&Reverse(completed_round.number), |completed_round| {
Reverse(completed_round.number)
}) {
Ok(idx) => self.rounds[idx] = completed_round,
Err(idx) => self.rounds.insert(idx, completed_round),
};
if self.rounds.len() > NUM_LAST_COMPLETED_ROUNDS {
self.rounds.pop();
}
}
}
/// A map with voter status information for currently live rounds,
/// which votes have we cast and what are they.
pub type CurrentRounds<Block> = BTreeMap<RoundNumber, HasVoted<<Block as BlockT>::Header>>;
/// The state of the current voter set, whether it is currently active or not
/// and information related to the previously completed rounds. Current round
/// voting status is used when restarting the voter, i.e. it will re-use the
/// previous votes for a given round if appropriate (same round and same local
/// key).
#[derive(Debug, Decode, Encode, PartialEq)]
pub enum VoterSetState<Block: BlockT> {
/// The voter is live, i.e. participating in rounds.
Live {
/// The previously completed rounds.
completed_rounds: CompletedRounds<Block>,
/// Voter status for the currently live rounds.
current_rounds: CurrentRounds<Block>,
},
/// The voter is paused, i.e. not casting or importing any votes.
Paused {
/// The previously completed rounds.
completed_rounds: CompletedRounds<Block>,
},
}
impl<Block: BlockT> VoterSetState<Block> {
/// Create a new live VoterSetState with round 0 as a completed round using
/// the given genesis state and the given authorities. Round 1 is added as a
/// current round (with state `HasVoted::No`).
pub(crate) fn live(
set_id: SetId,
authority_set: &AuthoritySet<Block::Hash, NumberFor<Block>>,
genesis_state: (Block::Hash, NumberFor<Block>),
) -> VoterSetState<Block> {
let state = RoundState::genesis((genesis_state.0, genesis_state.1));
let completed_rounds = CompletedRounds::new(
CompletedRound {
number: 0,
state,
base: (genesis_state.0, genesis_state.1),
votes: Vec::new(),
},
set_id,
authority_set,
);
let mut current_rounds = CurrentRounds::<Block>::new();
current_rounds.insert(1, HasVoted::No);
VoterSetState::Live { completed_rounds, current_rounds }
}
/// Returns the last completed rounds.
pub(crate) fn completed_rounds(&self) -> CompletedRounds<Block> {
match self {
VoterSetState::Live { completed_rounds, .. } => completed_rounds.clone(),
VoterSetState::Paused { completed_rounds } => completed_rounds.clone(),
}
}
/// Returns the last completed round.
pub(crate) fn last_completed_round(&self) -> CompletedRound<Block> {
match self {
VoterSetState::Live { completed_rounds, .. } => completed_rounds.last().clone(),
VoterSetState::Paused { completed_rounds } => completed_rounds.last().clone(),
}
}
/// Returns the voter set state validating that it includes the given round
/// in current rounds and that the voter isn't paused.
pub fn with_current_round(
&self,
round: RoundNumber,
) -> Result<(&CompletedRounds<Block>, &CurrentRounds<Block>), Error> {
if let VoterSetState::Live { completed_rounds, current_rounds } = self {
if current_rounds.contains_key(&round) {
Ok((completed_rounds, current_rounds))
} else {
let msg = "Voter acting on a live round we are not tracking.";
Err(Error::Safety(msg.to_string()))
}
} else {
let msg = "Voter acting while in paused state.";
Err(Error::Safety(msg.to_string()))
}
}
}
/// Whether we've voted already during a prior run of the program.
#[derive(Clone, Debug, Decode, Encode, PartialEq)]
pub enum HasVoted<Header: HeaderT> {
/// Has not voted already in this round.
No,
/// Has voted in this round.
Yes(AuthorityId, Vote<Header>),
}
/// The votes cast by this voter already during a prior run of the program.
#[derive(Debug, Clone, Decode, Encode, PartialEq)]
pub enum Vote<Header: HeaderT> {
/// Has cast a proposal.
Propose(PrimaryPropose<Header>),
/// Has cast a prevote.
Prevote(Option<PrimaryPropose<Header>>, Prevote<Header>),
/// Has cast a precommit (implies prevote.)
Precommit(Option<PrimaryPropose<Header>>, Prevote<Header>, Precommit<Header>),
}
impl<Header: HeaderT> HasVoted<Header> {
/// Returns the proposal we should vote with (if any.)
pub fn propose(&self) -> Option<&PrimaryPropose<Header>> {
match self {
HasVoted::Yes(_, Vote::Propose(propose)) => Some(propose),
HasVoted::Yes(_, Vote::Prevote(propose, _)) |
HasVoted::Yes(_, Vote::Precommit(propose, _, _)) => propose.as_ref(),
_ => None,
}
}
/// Returns the prevote we should vote with (if any.)
pub fn prevote(&self) -> Option<&Prevote<Header>> {
match self {
HasVoted::Yes(_, Vote::Prevote(_, prevote)) |
HasVoted::Yes(_, Vote::Precommit(_, prevote, _)) => Some(prevote),
_ => None,
}
}
/// Returns the precommit we should vote with (if any.)
pub fn precommit(&self) -> Option<&Precommit<Header>> {
match self {
HasVoted::Yes(_, Vote::Precommit(_, _, precommit)) => Some(precommit),
_ => None,
}
}
/// Returns true if the voter can still propose, false otherwise.
pub fn can_propose(&self) -> bool {
self.propose().is_none()
}
/// Returns true if the voter can still prevote, false otherwise.
pub fn can_prevote(&self) -> bool {
self.prevote().is_none()
}
/// Returns true if the voter can still precommit, false otherwise.
pub fn can_precommit(&self) -> bool {
self.precommit().is_none()
}
}
/// A voter set state meant to be shared safely across multiple owners.
#[derive(Clone)]
pub struct SharedVoterSetState<Block: BlockT> {
/// The inner shared `VoterSetState`.
inner: Arc<RwLock<VoterSetState<Block>>>,
/// A tracker for the rounds that we are actively participating on (i.e. voting)
/// and the authority id under which we are doing it.
voting: Arc<RwLock<HashMap<RoundNumber, AuthorityId>>>,
}
impl<Block: BlockT> From<VoterSetState<Block>> for SharedVoterSetState<Block> {
fn from(set_state: VoterSetState<Block>) -> Self {
SharedVoterSetState::new(set_state)
}
}
impl<Block: BlockT> SharedVoterSetState<Block> {
/// Create a new shared voter set tracker with the given state.
pub(crate) fn new(state: VoterSetState<Block>) -> Self {
SharedVoterSetState {
inner: Arc::new(RwLock::new(state)),
voting: Arc::new(RwLock::new(HashMap::new())),
}
}
/// Read the inner voter set state.
pub(crate) fn read(&self) -> parking_lot::RwLockReadGuard<VoterSetState<Block>> {
self.inner.read()
}
/// Get the authority id that we are using to vote on the given round, if any.
pub(crate) fn voting_on(&self, round: RoundNumber) -> Option<AuthorityId> {
self.voting.read().get(&round).cloned()
}
/// Note that we started voting on the give round with the given authority id.
pub(crate) fn started_voting_on(&self, round: RoundNumber, local_id: AuthorityId) {
self.voting.write().insert(round, local_id);
}
/// Note that we have finished voting on the given round. If we were voting on
/// the given round, the authority id that we were using to do it will be
/// cleared.
pub(crate) fn finished_voting_on(&self, round: RoundNumber) {
self.voting.write().remove(&round);
}
/// Return vote status information for the current round.
pub(crate) fn has_voted(&self, round: RoundNumber) -> HasVoted<Block::Header> {
match &*self.inner.read() {
VoterSetState::Live { current_rounds, .. } => current_rounds
.get(&round)
.and_then(|has_voted| match has_voted {
HasVoted::Yes(id, vote) => Some(HasVoted::Yes(id.clone(), vote.clone())),
_ => None,
})
.unwrap_or(HasVoted::No),
_ => HasVoted::No,
}
}
// NOTE: not exposed outside of this module intentionally.
fn with<F, R>(&self, f: F) -> R
where
F: FnOnce(&mut VoterSetState<Block>) -> R,
{
f(&mut *self.inner.write())
}
}
/// Prometheus metrics for GRANDPA.
#[derive(Clone)]
pub(crate) struct Metrics {
finality_grandpa_round: Gauge<U64>,
finality_grandpa_prevotes: Counter<U64>,
finality_grandpa_precommits: Counter<U64>,
}
impl Metrics {
pub(crate) fn register(
registry: &prometheus_endpoint::Registry,
) -> Result<Self, PrometheusError> {
Ok(Self {
finality_grandpa_round: register(
Gauge::new("substrate_finality_grandpa_round", "Highest completed GRANDPA round.")?,
registry,
)?,
finality_grandpa_prevotes: register(
Counter::new(
"substrate_finality_grandpa_prevotes_total",
"Total number of GRANDPA prevotes cast locally.",
)?,
registry,
)?,
finality_grandpa_precommits: register(
Counter::new(
"substrate_finality_grandpa_precommits_total",
"Total number of GRANDPA precommits cast locally.",
)?,
registry,
)?,
})
}
}
/// The environment we run GRANDPA in.
pub(crate) struct Environment<
Backend,
Block: BlockT,
C,
N: NetworkT<Block>,
S: SyncingT<Block>,
SC,
VR,
> {
pub(crate) client: Arc<C>,
pub(crate) select_chain: SC,
pub(crate) voters: Arc<VoterSet<AuthorityId>>,
pub(crate) config: Config,
pub(crate) authority_set: SharedAuthoritySet<Block::Hash, NumberFor<Block>>,
pub(crate) network: crate::communication::NetworkBridge<Block, N, S>,
pub(crate) set_id: SetId,
pub(crate) voter_set_state: SharedVoterSetState<Block>,
pub(crate) voting_rule: VR,
pub(crate) metrics: Option<Metrics>,
pub(crate) justification_sender: Option<GrandpaJustificationSender<Block>>,
pub(crate) telemetry: Option<TelemetryHandle>,
pub(crate) _phantom: PhantomData<Backend>,
}
impl<BE, Block: BlockT, C, N: NetworkT<Block>, S: SyncingT<Block>, SC, VR>
Environment<BE, Block, C, N, S, SC, VR>
{
/// Updates the voter set state using the given closure. The write lock is
/// held during evaluation of the closure and the environment's voter set
/// state is set to its result if successful.
pub(crate) fn update_voter_set_state<F>(&self, f: F) -> Result<(), Error>
where
F: FnOnce(&VoterSetState<Block>) -> Result<Option<VoterSetState<Block>>, Error>,
{
self.voter_set_state.with(|voter_set_state| {
if let Some(set_state) = f(voter_set_state)? {
*voter_set_state = set_state;
if let Some(metrics) = self.metrics.as_ref() {
if let VoterSetState::Live { completed_rounds, .. } = voter_set_state {
let highest = completed_rounds
.rounds
.iter()
.map(|round| round.number)
.max()
.expect("There is always one completed round (genesis); qed");
metrics.finality_grandpa_round.set(highest);
}
}
}
Ok(())
})
}
}
impl<BE, Block, C, N, S, SC, VR> Environment<BE, Block, C, N, S, SC, VR>
where
Block: BlockT,
BE: BackendT<Block>,
C: ClientForGrandpa<Block, BE>,
C::Api: GrandpaApi<Block>,
N: NetworkT<Block>,
S: SyncingT<Block>,
SC: SelectChainT<Block>,
{
/// Report the given equivocation to the GRANDPA runtime module. This method
/// generates a session membership proof of the offender and then submits an
/// extrinsic to report the equivocation. In particular, the session membership
/// proof must be generated at the block at which the given set was active which
/// isn't necessarily the best block if there are pending authority set changes.
pub(crate) fn report_equivocation(
&self,
equivocation: Equivocation<Block::Hash, NumberFor<Block>>,
) -> Result<(), Error> {
if let Some(local_id) = self.voter_set_state.voting_on(equivocation.round_number()) {
if *equivocation.offender() == local_id {
return Err(Error::Safety(
"Refraining from sending equivocation report for our own equivocation.".into(),
))
}
}
let is_descendent_of = is_descendent_of(&*self.client, None);
let (best_block_hash, best_block_number) = {
// TODO [#9158]: Use SelectChain::best_chain() to get a potentially
// more accurate best block
let info = self.client.info();
(info.best_hash, info.best_number)
};
let authority_set = self.authority_set.inner();
// block hash and number of the next pending authority set change in the
// given best chain.
let next_change = authority_set
.next_change(&best_block_hash, &is_descendent_of)
.map_err(|e| Error::Safety(e.to_string()))?;
// find the hash of the latest block in the current set
let current_set_latest_hash = match next_change {
Some((_, n)) if n.is_zero() =>
return Err(Error::Safety("Authority set change signalled at genesis.".to_string())),
// the next set starts at `n` so the current one lasts until `n - 1`. if
// `n` is later than the best block, then the current set is still live
// at best block.
Some((_, n)) if n > best_block_number => best_block_hash,
Some((h, _)) => {
// this is the header at which the new set will start
let header = self.client.header(h)?.expect(
"got block hash from registered pending change; \
pending changes are only registered on block import; qed.",
);
// its parent block is the last block in the current set
*header.parent_hash()
},
// there is no pending change, the latest block for the current set is
// the best block.
None => best_block_hash,
};
// generate key ownership proof at that block
let key_owner_proof = match self
.client
.runtime_api()
.generate_key_ownership_proof(
current_set_latest_hash,
authority_set.set_id,
equivocation.offender().clone(),
)
.map_err(Error::RuntimeApi)?
{
Some(proof) => proof,
None => {
debug!(
target: LOG_TARGET,
"Equivocation offender is not part of the authority set."
);
return Ok(())
},
};
// submit equivocation report at **best** block
let equivocation_proof = EquivocationProof::new(authority_set.set_id, equivocation);
self.client
.runtime_api()
.submit_report_equivocation_unsigned_extrinsic(
best_block_hash,
equivocation_proof,
key_owner_proof,
)
.map_err(Error::RuntimeApi)?;
Ok(())
}
}
impl<BE, Block, C, N, S, SC, VR> finality_grandpa::Chain<Block::Hash, NumberFor<Block>>
for Environment<BE, Block, C, N, S, SC, VR>
where
Block: BlockT,
BE: BackendT<Block>,
C: ClientForGrandpa<Block, BE>,
N: NetworkT<Block>,
S: SyncingT<Block>,
SC: SelectChainT<Block>,
VR: VotingRuleT<Block, C>,
NumberFor<Block>: BlockNumberOps,
{
fn ancestry(
&self,
base: Block::Hash,
block: Block::Hash,
) -> Result<Vec<Block::Hash>, GrandpaError> {
ancestry(&self.client, base, block)
}
}
pub(crate) fn ancestry<Block: BlockT, Client>(
client: &Arc<Client>,
base: Block::Hash,
block: Block::Hash,
) -> Result<Vec<Block::Hash>, GrandpaError>
where
Client: HeaderMetadata<Block, Error = sp_blockchain::Error>,
{
if base == block {
return Err(GrandpaError::NotDescendent)
}
let tree_route_res = sp_blockchain::tree_route(&**client, block, base);
let tree_route = match tree_route_res {
Ok(tree_route) => tree_route,
Err(e) => {
debug!(
target: LOG_TARGET,
"Encountered error computing ancestry between block {:?} and base {:?}: {}",
block,
base,
e
);
return Err(GrandpaError::NotDescendent)
},
};
if tree_route.common_block().hash != base {
return Err(GrandpaError::NotDescendent)
}
// skip one because our ancestry is meant to start from the parent of `block`,
// and `tree_route` includes it.
Ok(tree_route.retracted().iter().skip(1).map(|e| e.hash).collect())
}
impl<B, Block, C, N, S, SC, VR> voter::Environment<Block::Hash, NumberFor<Block>>
for Environment<B, Block, C, N, S, SC, VR>
where
Block: BlockT,
B: BackendT<Block>,
C: ClientForGrandpa<Block, B> + 'static,
C::Api: GrandpaApi<Block>,
N: NetworkT<Block>,
S: SyncingT<Block>,
SC: SelectChainT<Block> + 'static,
VR: VotingRuleT<Block, C> + Clone + 'static,
NumberFor<Block>: BlockNumberOps,
{
type Timer = Pin<Box<dyn Future<Output = Result<(), Self::Error>> + Send>>;
type BestChain = Pin<
Box<
dyn Future<Output = Result<Option<(Block::Hash, NumberFor<Block>)>, Self::Error>>
+ Send,
>,
>;
type Id = AuthorityId;
type Signature = AuthoritySignature;
// regular round message streams
type In = Pin<
Box<
dyn Stream<
Item = Result<
::finality_grandpa::SignedMessage<
Block::Hash,
NumberFor<Block>,
Self::Signature,
Self::Id,
>,
Self::Error,
>,
> + Send,
>,
>;
type Out = Pin<
Box<
dyn Sink<
::finality_grandpa::Message<Block::Hash, NumberFor<Block>>,
Error = Self::Error,
> + Send,
>,
>;
type Error = CommandOrError<Block::Hash, NumberFor<Block>>;
fn best_chain_containing(&self, block: Block::Hash) -> Self::BestChain {
let client = self.client.clone();
let authority_set = self.authority_set.clone();
let select_chain = self.select_chain.clone();
let voting_rule = self.voting_rule.clone();
let set_id = self.set_id;
Box::pin(async move {
// NOTE: when we finalize an authority set change through the sync protocol the voter is
// signaled asynchronously. therefore the voter could still vote in the next round
// before activating the new set. the `authority_set` is updated immediately thus
// we restrict the voter based on that.
if set_id != authority_set.set_id() {
return Ok(None)
}
best_chain_containing(block, client, authority_set, select_chain, voting_rule)
.await
.map_err(|e| e.into())
})
}
fn round_data(
&self,
round: RoundNumber,
) -> voter::RoundData<Self::Id, Self::Timer, Self::In, Self::Out> {
let prevote_timer = Delay::new(self.config.gossip_duration * 2);
let precommit_timer = Delay::new(self.config.gossip_duration * 4);
let local_id = local_authority_id(&self.voters, self.config.keystore.as_ref());
let has_voted = match self.voter_set_state.has_voted(round) {
HasVoted::Yes(id, vote) =>
if local_id.as_ref().map(|k| k == &id).unwrap_or(false) {
HasVoted::Yes(id, vote)
} else {
HasVoted::No
},
HasVoted::No => HasVoted::No,
};
// NOTE: we cache the local authority id that we'll be using to vote on the
// given round. this is done to make sure we only check for available keys
// from the keystore in this method when beginning the round, otherwise if
// the keystore state changed during the round (e.g. a key was removed) it
// could lead to internal state inconsistencies in the voter environment
// (e.g. we wouldn't update the voter set state after prevoting since there's
// no local authority id).
if let Some(id) = local_id.as_ref() {
self.voter_set_state.started_voting_on(round, id.clone());
}
// we can only sign when we have a local key in the authority set
// and we have a reference to the keystore.
let keystore = match (local_id.as_ref(), self.config.keystore.as_ref()) {
(Some(id), Some(keystore)) => Some((id.clone(), keystore.clone()).into()),
_ => None,
};
let (incoming, outgoing) = self.network.round_communication(
keystore,
crate::communication::Round(round),
crate::communication::SetId(self.set_id),
self.voters.clone(),
has_voted,
);
// schedule incoming messages from the network to be held until
// corresponding blocks are imported.
let incoming = Box::pin(
UntilVoteTargetImported::new(
self.client.import_notification_stream(),
self.network.clone(),
self.client.clone(),
incoming,
"round",
None,
)
.map_err(Into::into),
);
// schedule network message cleanup when sink drops.
let outgoing = Box::pin(outgoing.sink_err_into());
voter::RoundData {
voter_id: local_id,
prevote_timer: Box::pin(prevote_timer.map(Ok)),
precommit_timer: Box::pin(precommit_timer.map(Ok)),
incoming,
outgoing,
}
}
fn proposed(
&self,
round: RoundNumber,
propose: PrimaryPropose<Block::Header>,
) -> Result<(), Self::Error> {
let local_id = match self.voter_set_state.voting_on(round) {
Some(id) => id,
None => return Ok(()),
};
self.update_voter_set_state(|voter_set_state| {
let (completed_rounds, current_rounds) = voter_set_state.with_current_round(round)?;
let current_round = current_rounds
.get(&round)
.expect("checked in with_current_round that key exists; qed.");
if !current_round.can_propose() {
// we've already proposed in this round (in a previous run),
// ignore the given vote and don't update the voter set
// state
return Ok(None)
}
let mut current_rounds = current_rounds.clone();
let current_round = current_rounds
.get_mut(&round)
.expect("checked previously that key exists; qed.");
*current_round = HasVoted::Yes(local_id, Vote::Propose(propose));
let set_state = VoterSetState::<Block>::Live {
completed_rounds: completed_rounds.clone(),
current_rounds,
};
crate::aux_schema::write_voter_set_state(&*self.client, &set_state)?;
Ok(Some(set_state))
})?;
Ok(())
}
fn prevoted(
&self,
round: RoundNumber,
prevote: Prevote<Block::Header>,
) -> Result<(), Self::Error> {
let local_id = match self.voter_set_state.voting_on(round) {
Some(id) => id,
None => return Ok(()),
};
let report_prevote_metrics = |prevote: &Prevote<Block::Header>| {
telemetry!(
self.telemetry;
CONSENSUS_DEBUG;
"afg.prevote_issued";
"round" => round,
"target_number" => ?prevote.target_number,
"target_hash" => ?prevote.target_hash,
);
if let Some(metrics) = self.metrics.as_ref() {
metrics.finality_grandpa_prevotes.inc();
}
};
self.update_voter_set_state(|voter_set_state| {
let (completed_rounds, current_rounds) = voter_set_state.with_current_round(round)?;
let current_round = current_rounds
.get(&round)
.expect("checked in with_current_round that key exists; qed.");
if !current_round.can_prevote() {
// we've already prevoted in this round (in a previous run),
// ignore the given vote and don't update the voter set
// state
return Ok(None)
}
// report to telemetry and prometheus
report_prevote_metrics(&prevote);
let propose = current_round.propose();
let mut current_rounds = current_rounds.clone();
let current_round = current_rounds
.get_mut(&round)
.expect("checked previously that key exists; qed.");
*current_round = HasVoted::Yes(local_id, Vote::Prevote(propose.cloned(), prevote));
let set_state = VoterSetState::<Block>::Live {
completed_rounds: completed_rounds.clone(),
current_rounds,
};
crate::aux_schema::write_voter_set_state(&*self.client, &set_state)?;
Ok(Some(set_state))
})?;
Ok(())
}
fn precommitted(
&self,
round: RoundNumber,
precommit: Precommit<Block::Header>,
) -> Result<(), Self::Error> {
let local_id = match self.voter_set_state.voting_on(round) {
Some(id) => id,
None => return Ok(()),
};
let report_precommit_metrics = |precommit: &Precommit<Block::Header>| {
telemetry!(
self.telemetry;
CONSENSUS_DEBUG;
"afg.precommit_issued";
"round" => round,
"target_number" => ?precommit.target_number,
"target_hash" => ?precommit.target_hash,
);
if let Some(metrics) = self.metrics.as_ref() {
metrics.finality_grandpa_precommits.inc();
}
};
self.update_voter_set_state(|voter_set_state| {
let (completed_rounds, current_rounds) = voter_set_state.with_current_round(round)?;
let current_round = current_rounds
.get(&round)
.expect("checked in with_current_round that key exists; qed.");
if !current_round.can_precommit() {
// we've already precommitted in this round (in a previous run),
// ignore the given vote and don't update the voter set
// state
return Ok(None)
}
// report to telemetry and prometheus
report_precommit_metrics(&precommit);
let propose = current_round.propose();
let prevote = match current_round {
HasVoted::Yes(_, Vote::Prevote(_, prevote)) => prevote,
_ => {
let msg = "Voter precommitting before prevoting.";
return Err(Error::Safety(msg.to_string()))
},
};
let mut current_rounds = current_rounds.clone();
let current_round = current_rounds
.get_mut(&round)
.expect("checked previously that key exists; qed.");
*current_round = HasVoted::Yes(
local_id,
Vote::Precommit(propose.cloned(), prevote.clone(), precommit),
);
let set_state = VoterSetState::<Block>::Live {
completed_rounds: completed_rounds.clone(),
current_rounds,
};
crate::aux_schema::write_voter_set_state(&*self.client, &set_state)?;
Ok(Some(set_state))
})?;
Ok(())
}
fn completed(
&self,
round: RoundNumber,
state: RoundState<Block::Hash, NumberFor<Block>>,
base: (Block::Hash, NumberFor<Block>),
historical_votes: &HistoricalVotes<Block>,
) -> Result<(), Self::Error> {
debug!(
target: LOG_TARGET,
"Voter {} completed round {} in set {}. Estimate = {:?}, Finalized in round = {:?}",
self.config.name(),
round,
self.set_id,
state.estimate.as_ref().map(|e| e.1),
state.finalized.as_ref().map(|e| e.1),
);
self.update_voter_set_state(|voter_set_state| {
// NOTE: we don't use `with_current_round` here, it is possible that
// we are not currently tracking this round if it is a round we
// caught up to.
let (completed_rounds, current_rounds) =
if let VoterSetState::Live { completed_rounds, current_rounds } = voter_set_state {
(completed_rounds, current_rounds)
} else {
let msg = "Voter acting while in paused state.";
return Err(Error::Safety(msg.to_string()))
};
let mut completed_rounds = completed_rounds.clone();
// TODO: Future integration will store the prevote and precommit index. See #2611.
let votes = historical_votes.seen().to_vec();