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
/
gossip.rs
2637 lines (2263 loc) · 76.6 KB
/
gossip.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 2019-2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate 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.
// Substrate 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 Substrate. If not, see <http://www.gnu.org/licenses/>.
//! Gossip and politeness for polite-grandpa.
//!
//! This module implements the following message types:
//! #### Neighbor Packet
//!
//! The neighbor packet is sent to only our neighbors. It contains this information
//!
//! - Current Round
//! - Current voter set ID
//! - Last finalized hash from commit messages.
//!
//! If a peer is at a given voter set, it is impolite to send messages from
//! an earlier voter set. It is extremely impolite to send messages
//! from a future voter set. "future-set" messages can be dropped and ignored.
//!
//! If a peer is at round r, is impolite to send messages about r-2 or earlier and extremely
//! impolite to send messages about r+1 or later. "future-round" messages can
//! be dropped and ignored.
//!
//! It is impolite to send a neighbor packet which moves backwards in protocol state.
//!
//! This is beneficial if it conveys some progress in the protocol state of the peer.
//!
//! #### Prevote / Precommit
//!
//! These are votes within a round. Noting that we receive these messages
//! from our peers who are not necessarily voters, we have to account the benefit
//! based on what they might have seen.
//!
//! #### Propose
//!
//! This is a broadcast by a known voter of the last-round estimate.
//!
//! #### Commit
//!
//! These are used to announce past agreement of finality.
//!
//! It is impolite to send commits which are earlier than the last commit
//! sent. It is especially impolite to send commits which are invalid, or from
//! a different Set ID than the receiving peer has indicated.
//!
//! Sending a commit is polite when it may finalize something that the receiving peer
//! was not aware of.
//!
//! #### Catch Up
//!
//! These allow a peer to request another peer, which they perceive to be in a
//! later round, to provide all the votes necessary to complete a given round
//! `R`.
//!
//! It is impolite to send a catch up request for a round `R` to a peer whose
//! announced view is behind `R`. It is also impolite to send a catch up request
//! to a peer in a new different Set ID.
//!
//! The logic for issuing and tracking pending catch up requests is implemented
//! in the `GossipValidator`. A catch up request is issued anytime we see a
//! neighbor packet from a peer at a round `CATCH_UP_THRESHOLD` higher than at
//! we are.
//!
//! ## Expiration
//!
//! We keep some amount of recent rounds' messages, but do not accept new ones from rounds
//! older than our current_round - 1.
//!
//! ## Message Validation
//!
//! We only send polite messages to peers,
use sp_runtime::traits::{NumberFor, Block as BlockT, Zero};
use sc_network_gossip::{MessageIntent, ValidatorContext};
use sc_network::{ObservedRole, PeerId, ReputationChange};
use parity_scale_codec::{Encode, Decode};
use sp_finality_grandpa::AuthorityId;
use sc_telemetry::{telemetry, CONSENSUS_DEBUG};
use log::{trace, debug};
use sp_utils::mpsc::{tracing_unbounded, TracingUnboundedReceiver, TracingUnboundedSender};
use prometheus_endpoint::{CounterVec, Opts, PrometheusError, register, Registry, U64};
use rand::seq::SliceRandom;
use crate::{environment, CatchUp, CompactCommit, SignedMessage};
use super::{cost, benefit, Round, SetId};
use std::collections::{HashMap, VecDeque, HashSet};
use std::time::{Duration, Instant};
const REBROADCAST_AFTER: Duration = Duration::from_secs(60 * 5);
const CATCH_UP_REQUEST_TIMEOUT: Duration = Duration::from_secs(45);
const CATCH_UP_PROCESS_TIMEOUT: Duration = Duration::from_secs(30);
/// Maximum number of rounds we are behind a peer before issuing a
/// catch up request.
const CATCH_UP_THRESHOLD: u64 = 2;
const PROPAGATION_ALL: u32 = 4; //in rounds;
const PROPAGATION_ALL_AUTHORITIES: u32 = 2; //in rounds;
const PROPAGATION_SOME_NON_AUTHORITIES: u32 = 3; //in rounds;
const ROUND_DURATION: u32 = 2; // measured in gossip durations
const MIN_LUCKY: usize = 5;
type Report = (PeerId, ReputationChange);
/// An outcome of examining a message.
#[derive(Debug, PartialEq, Clone, Copy)]
enum Consider {
/// Accept the message.
Accept,
/// Message is too early. Reject.
RejectPast,
/// Message is from the future. Reject.
RejectFuture,
/// Message cannot be evaluated. Reject.
RejectOutOfScope,
}
/// A view of protocol state.
#[derive(Debug)]
struct View<N> {
round: Round, // the current round we are at.
set_id: SetId, // the current voter set id.
last_commit: Option<N>, // commit-finalized block height, if any.
}
impl<N> Default for View<N> {
fn default() -> Self {
View {
round: Round(1),
set_id: SetId(0),
last_commit: None,
}
}
}
impl<N: Ord> View<N> {
/// Consider a round and set ID combination under a current view.
fn consider_vote(&self, round: Round, set_id: SetId) -> Consider {
// only from current set
if set_id < self.set_id { return Consider::RejectPast }
if set_id > self.set_id { return Consider::RejectFuture }
// only r-1 ... r+1
if round.0 > self.round.0.saturating_add(1) { return Consider::RejectFuture }
if round.0 < self.round.0.saturating_sub(1) { return Consider::RejectPast }
Consider::Accept
}
/// Consider a set-id global message. Rounds are not taken into account, but are implicitly
/// because we gate on finalization of a further block than a previous commit.
fn consider_global(&self, set_id: SetId, number: N) -> Consider {
// only from current set
if set_id < self.set_id { return Consider::RejectPast }
if set_id > self.set_id { return Consider::RejectFuture }
// only commits which claim to prove a higher block number than
// the one we're aware of.
match self.last_commit {
None => Consider::Accept,
Some(ref num) => if num < &number {
Consider::Accept
} else {
Consider::RejectPast
}
}
}
}
/// A local view of protocol state. Similar to `View` but we additionally track
/// the round and set id at which the last commit was observed, and the instant
/// at which the current round started.
struct LocalView<N> {
round: Round,
set_id: SetId,
last_commit: Option<(N, Round, SetId)>,
round_start: Instant,
}
impl<N> LocalView<N> {
/// Creates a new `LocalView` at the given set id and round.
fn new(set_id: SetId, round: Round) -> LocalView<N> {
LocalView {
set_id,
round,
last_commit: None,
round_start: Instant::now(),
}
}
/// Converts the local view to a `View` discarding round and set id
/// information about the last commit.
fn as_view(&self) -> View<&N> {
View {
round: self.round,
set_id: self.set_id,
last_commit: self.last_commit_height(),
}
}
/// Update the set ID. implies a reset to round 1.
fn update_set(&mut self, set_id: SetId) {
if set_id != self.set_id {
self.set_id = set_id;
self.round = Round(1);
self.round_start = Instant::now();
}
}
/// Updates the current round.
fn update_round(&mut self, round: Round) {
self.round = round;
self.round_start = Instant::now();
}
/// Returns the height of the block that the last observed commit finalizes.
fn last_commit_height(&self) -> Option<&N> {
self.last_commit.as_ref().map(|(number, _, _)| number)
}
}
const KEEP_RECENT_ROUNDS: usize = 3;
/// Tracks gossip topics that we are keeping messages for. We keep topics of:
///
/// - the last `KEEP_RECENT_ROUNDS` complete GRANDPA rounds,
///
/// - the topic for the current and next round,
///
/// - and a global topic for commit and catch-up messages.
struct KeepTopics<B: BlockT> {
current_set: SetId,
rounds: VecDeque<(Round, SetId)>,
reverse_map: HashMap<B::Hash, (Option<Round>, SetId)>
}
impl<B: BlockT> KeepTopics<B> {
fn new() -> Self {
KeepTopics {
current_set: SetId(0),
rounds: VecDeque::with_capacity(KEEP_RECENT_ROUNDS + 2),
reverse_map: HashMap::new(),
}
}
fn push(&mut self, round: Round, set_id: SetId) {
self.current_set = std::cmp::max(self.current_set, set_id);
// under normal operation the given round is already tracked (since we
// track one round ahead). if we skip rounds (with a catch up) the given
// round topic might not be tracked yet.
if !self.rounds.contains(&(round, set_id)) {
self.rounds.push_back((round, set_id));
}
// we also accept messages for the next round
self.rounds.push_back((Round(round.0.saturating_add(1)), set_id));
// the 2 is for the current and next round.
while self.rounds.len() > KEEP_RECENT_ROUNDS + 2 {
let _ = self.rounds.pop_front();
}
let mut map = HashMap::with_capacity(KEEP_RECENT_ROUNDS + 3);
map.insert(super::global_topic::<B>(self.current_set.0), (None, self.current_set));
for &(round, set) in &self.rounds {
map.insert(
super::round_topic::<B>(round.0, set.0),
(Some(round), set)
);
}
self.reverse_map = map;
}
fn topic_info(&self, topic: &B::Hash) -> Option<(Option<Round>, SetId)> {
self.reverse_map.get(topic).cloned()
}
}
// topics to send to a neighbor based on their view.
fn neighbor_topics<B: BlockT>(view: &View<NumberFor<B>>) -> Vec<B::Hash> {
let s = view.set_id;
let mut topics = vec![
super::global_topic::<B>(s.0),
super::round_topic::<B>(view.round.0, s.0),
];
if view.round.0 != 0 {
let r = Round(view.round.0 - 1);
topics.push(super::round_topic::<B>(r.0, s.0))
}
topics
}
/// Grandpa gossip message type.
/// This is the root type that gets encoded and sent on the network.
#[derive(Debug, Encode, Decode)]
pub(super) enum GossipMessage<Block: BlockT> {
/// Grandpa message with round and set info.
Vote(VoteMessage<Block>),
/// Grandpa commit message with round and set info.
Commit(FullCommitMessage<Block>),
/// A neighbor packet. Not repropagated.
Neighbor(VersionedNeighborPacket<NumberFor<Block>>),
/// Grandpa catch up request message with round and set info. Not repropagated.
CatchUpRequest(CatchUpRequestMessage),
/// Grandpa catch up message with round and set info. Not repropagated.
CatchUp(FullCatchUpMessage<Block>),
}
impl<Block: BlockT> From<NeighborPacket<NumberFor<Block>>> for GossipMessage<Block> {
fn from(neighbor: NeighborPacket<NumberFor<Block>>) -> Self {
GossipMessage::Neighbor(VersionedNeighborPacket::V1(neighbor))
}
}
/// Network level vote message with topic information.
#[derive(Debug, Encode, Decode)]
pub(super) struct VoteMessage<Block: BlockT> {
/// The round this message is from.
pub(super) round: Round,
/// The voter set ID this message is from.
pub(super) set_id: SetId,
/// The message itself.
pub(super) message: SignedMessage<Block>,
}
/// Network level commit message with topic information.
#[derive(Debug, Encode, Decode)]
pub(super) struct FullCommitMessage<Block: BlockT> {
/// The round this message is from.
pub(super) round: Round,
/// The voter set ID this message is from.
pub(super) set_id: SetId,
/// The compact commit message.
pub(super) message: CompactCommit<Block>,
}
/// V1 neighbor packet. Neighbor packets are sent from nodes to their peers
/// and are not repropagated. These contain information about the node's state.
#[derive(Debug, Encode, Decode, Clone)]
pub(super) struct NeighborPacket<N> {
/// The round the node is currently at.
pub(super) round: Round,
/// The set ID the node is currently at.
pub(super) set_id: SetId,
/// The highest finalizing commit observed.
pub(super) commit_finalized_height: N,
}
/// A versioned neighbor packet.
#[derive(Debug, Encode, Decode)]
pub(super) enum VersionedNeighborPacket<N> {
#[codec(index = "1")]
V1(NeighborPacket<N>),
}
impl<N> VersionedNeighborPacket<N> {
fn into_neighbor_packet(self) -> NeighborPacket<N> {
match self {
VersionedNeighborPacket::V1(p) => p,
}
}
}
/// A catch up request for a given round (or any further round) localized by set id.
#[derive(Clone, Debug, Encode, Decode)]
pub(super) struct CatchUpRequestMessage {
/// The round that we want to catch up to.
pub(super) round: Round,
/// The voter set ID this message is from.
pub(super) set_id: SetId,
}
/// Network level catch up message with topic information.
#[derive(Debug, Encode, Decode)]
pub(super) struct FullCatchUpMessage<Block: BlockT> {
/// The voter set ID this message is from.
pub(super) set_id: SetId,
/// The compact commit message.
pub(super) message: CatchUp<Block>,
}
/// Misbehavior that peers can perform.
///
/// `cost` gives a cost that can be used to perform cost/benefit analysis of a
/// peer.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) enum Misbehavior {
// invalid neighbor message, considering the last one.
InvalidViewChange,
// could not decode neighbor message. bytes-length of the packet.
UndecodablePacket(i32),
// Bad catch up message (invalid signatures).
BadCatchUpMessage {
signatures_checked: i32,
},
// Bad commit message
BadCommitMessage {
signatures_checked: i32,
blocks_loaded: i32,
equivocations_caught: i32,
},
// A message received that's from the future relative to our view.
// always misbehavior.
FutureMessage,
// A message received that cannot be evaluated relative to our view.
// This happens before we have a view and have sent out neighbor packets.
// always misbehavior.
OutOfScopeMessage,
}
impl Misbehavior {
pub(super) fn cost(&self) -> ReputationChange {
use Misbehavior::*;
match *self {
InvalidViewChange => cost::INVALID_VIEW_CHANGE,
UndecodablePacket(bytes) => ReputationChange::new(
bytes.saturating_mul(cost::PER_UNDECODABLE_BYTE),
"Grandpa: Bad packet",
),
BadCatchUpMessage { signatures_checked } => ReputationChange::new(
cost::PER_SIGNATURE_CHECKED.saturating_mul(signatures_checked),
"Grandpa: Bad cath-up message",
),
BadCommitMessage { signatures_checked, blocks_loaded, equivocations_caught } => {
let cost = cost::PER_SIGNATURE_CHECKED
.saturating_mul(signatures_checked)
.saturating_add(cost::PER_BLOCK_LOADED.saturating_mul(blocks_loaded));
let benefit = equivocations_caught.saturating_mul(benefit::PER_EQUIVOCATION);
ReputationChange::new((benefit as i32).saturating_add(cost as i32), "Grandpa: Bad commit")
},
FutureMessage => cost::FUTURE_MESSAGE,
OutOfScopeMessage => cost::OUT_OF_SCOPE_MESSAGE,
}
}
}
struct PeerInfo<N> {
view: View<N>,
roles: ObservedRole,
}
impl<N> PeerInfo<N> {
fn new(roles: ObservedRole) -> Self {
PeerInfo {
view: View::default(),
roles,
}
}
}
/// The peers we're connected do in gossip.
struct Peers<N> {
inner: HashMap<PeerId, PeerInfo<N>>,
lucky_peers: HashSet<PeerId>,
lucky_authorities: HashSet<PeerId>,
}
impl<N> Default for Peers<N> {
fn default() -> Self {
Peers {
inner: HashMap::new(),
lucky_peers: HashSet::new(),
lucky_authorities: HashSet::new(),
}
}
}
impl<N: Ord> Peers<N> {
fn new_peer(&mut self, who: PeerId, role: ObservedRole) {
match role {
ObservedRole::Authority if self.lucky_authorities.len() < MIN_LUCKY => {
self.lucky_authorities.insert(who.clone());
},
ObservedRole::Full | ObservedRole::Light if self.lucky_peers.len() < MIN_LUCKY => {
self.lucky_peers.insert(who.clone());
},
_ => {}
}
self.inner.insert(who, PeerInfo::new(role));
}
fn peer_disconnected(&mut self, who: &PeerId) {
self.inner.remove(who);
// This does not happen often enough compared to round duration,
// so we don't reshuffle.
self.lucky_peers.remove(who);
self.lucky_authorities.remove(who);
}
// returns a reference to the new view, if the peer is known.
fn update_peer_state(&mut self, who: &PeerId, update: NeighborPacket<N>)
-> Result<Option<&View<N>>, Misbehavior>
{
let peer = match self.inner.get_mut(who) {
None => return Ok(None),
Some(p) => p,
};
let invalid_change = peer.view.set_id > update.set_id
|| peer.view.round > update.round && peer.view.set_id == update.set_id
|| peer.view.last_commit.as_ref() > Some(&update.commit_finalized_height);
if invalid_change {
return Err(Misbehavior::InvalidViewChange);
}
peer.view = View {
round: update.round,
set_id: update.set_id,
last_commit: Some(update.commit_finalized_height),
};
trace!(target: "afg", "Peer {} updated view. Now at {:?}, {:?}",
who, peer.view.round, peer.view.set_id);
Ok(Some(&peer.view))
}
fn update_commit_height(&mut self, who: &PeerId, new_height: N) -> Result<(), Misbehavior> {
let peer = match self.inner.get_mut(who) {
None => return Ok(()),
Some(p) => p,
};
// this doesn't allow a peer to send us unlimited commits with the
// same height, because there is still a misbehavior condition based on
// sending commits that are <= the best we are aware of.
if peer.view.last_commit.as_ref() > Some(&new_height) {
return Err(Misbehavior::InvalidViewChange);
}
peer.view.last_commit = Some(new_height);
Ok(())
}
fn peer<'a>(&'a self, who: &PeerId) -> Option<&'a PeerInfo<N>> {
self.inner.get(who)
}
fn authorities(&self) -> usize {
// Note that our sentry and our validator are neither authorities nor non-authorities.
self.inner.iter().filter(|(_, info)| matches!(info.roles, ObservedRole::Authority)).count()
}
fn non_authorities(&self) -> usize {
// Note that our sentry and our validator are neither authorities nor non-authorities.
self.inner
.iter()
.filter(|(_, info)| matches!(info.roles, ObservedRole::Full | ObservedRole::Light))
.count()
}
fn reshuffle(&mut self) {
let mut lucky_peers: Vec<_> = self.inner
.iter()
.filter_map(|(id, info)|
if matches!(info.roles, ObservedRole::Full | ObservedRole::Light) { Some(id.clone()) } else { None })
.collect();
let mut lucky_authorities: Vec<_> = self.inner
.iter()
.filter_map(|(id, info)|
if matches!(info.roles, ObservedRole::Authority) { Some(id.clone()) } else { None })
.collect();
let num_non_authorities = ((lucky_peers.len() as f32).sqrt() as usize)
.max(MIN_LUCKY)
.min(lucky_peers.len());
let num_authorities = ((lucky_authorities.len() as f32).sqrt() as usize)
.max(MIN_LUCKY)
.min(lucky_authorities.len());
lucky_peers.partial_shuffle(&mut rand::thread_rng(), num_non_authorities);
lucky_peers.truncate(num_non_authorities);
lucky_authorities.partial_shuffle(&mut rand::thread_rng(), num_authorities);
lucky_authorities.truncate(num_authorities);
self.lucky_peers.clear();
self.lucky_peers.extend(lucky_peers.into_iter());
self.lucky_authorities.clear();
self.lucky_authorities.extend(lucky_authorities.into_iter());
}
}
#[derive(Debug, PartialEq)]
pub(super) enum Action<H> {
// repropagate under given topic, to the given peers, applying cost/benefit to originator.
Keep(H, ReputationChange),
// discard and process.
ProcessAndDiscard(H, ReputationChange),
// discard, applying cost/benefit to originator.
Discard(ReputationChange),
}
/// State of catch up request handling.
#[derive(Debug)]
enum PendingCatchUp {
/// No pending catch up requests.
None,
/// Pending catch up request which has not been answered yet.
Requesting {
who: PeerId,
request: CatchUpRequestMessage,
instant: Instant,
},
/// Pending catch up request that was answered and is being processed.
Processing {
instant: Instant,
},
}
/// Configuration for the round catch-up mechanism.
enum CatchUpConfig {
/// Catch requests are enabled, our node will issue them whenever it sees a
/// neighbor packet for a round further than `CATCH_UP_THRESHOLD`. If
/// `only_from_authorities` is set, the node will only send catch-up
/// requests to other authorities it is connected to. This is useful if the
/// GRANDPA observer protocol is live on the network, in which case full
/// nodes (non-authorities) don't have the necessary round data to answer
/// catch-up requests.
Enabled { only_from_authorities: bool },
/// Catch-up requests are disabled, our node will never issue them. This is
/// useful for the GRANDPA observer mode, where we are only interested in
/// commit messages and don't need to follow the full round protocol.
Disabled,
}
impl CatchUpConfig {
fn enabled(only_from_authorities: bool) -> CatchUpConfig {
CatchUpConfig::Enabled { only_from_authorities }
}
fn disabled() -> CatchUpConfig {
CatchUpConfig::Disabled
}
fn request_allowed<N>(&self, peer: &PeerInfo<N>) -> bool {
match self {
CatchUpConfig::Disabled => false,
CatchUpConfig::Enabled { only_from_authorities, .. } => match peer.roles {
ObservedRole::Authority | ObservedRole::OurSentry |
ObservedRole::OurGuardedAuthority => true,
_ => !only_from_authorities
}
}
}
}
struct Inner<Block: BlockT> {
local_view: Option<LocalView<NumberFor<Block>>>,
peers: Peers<NumberFor<Block>>,
live_topics: KeepTopics<Block>,
authorities: Vec<AuthorityId>,
config: crate::Config,
next_rebroadcast: Instant,
pending_catch_up: PendingCatchUp,
catch_up_config: CatchUpConfig,
}
type MaybeMessage<Block> = Option<(Vec<PeerId>, NeighborPacket<NumberFor<Block>>)>;
impl<Block: BlockT> Inner<Block> {
fn new(config: crate::Config) -> Self {
let catch_up_config = if config.observer_enabled {
if config.is_authority {
// since the observer protocol is enabled, we will only issue
// catch-up requests if we are an authority (and only to other
// authorities).
CatchUpConfig::enabled(true)
} else {
// otherwise, we are running the observer protocol and don't
// care about catch-up requests.
CatchUpConfig::disabled()
}
} else {
// if the observer protocol isn't enabled, then any full node should
// be able to answer catch-up requests.
CatchUpConfig::enabled(false)
};
Inner {
local_view: None,
peers: Peers::default(),
live_topics: KeepTopics::new(),
next_rebroadcast: Instant::now() + REBROADCAST_AFTER,
authorities: Vec::new(),
pending_catch_up: PendingCatchUp::None,
catch_up_config,
config,
}
}
/// Note a round in the current set has started.
fn note_round(&mut self, round: Round) -> MaybeMessage<Block> {
{
let local_view = match self.local_view {
None => return None,
Some(ref mut v) => if v.round == round {
return None
} else {
v
},
};
let set_id = local_view.set_id;
debug!(target: "afg", "Voter {} noting beginning of round {:?} to network.",
self.config.name(), (round, set_id));
local_view.update_round(round);
self.live_topics.push(round, set_id);
self.peers.reshuffle();
}
self.multicast_neighbor_packet()
}
/// Note that a voter set with given ID has started. Does nothing if the last
/// call to the function was with the same `set_id`.
fn note_set(&mut self, set_id: SetId, authorities: Vec<AuthorityId>) -> MaybeMessage<Block> {
{
let local_view = match self.local_view {
ref mut x @ None => x.get_or_insert(LocalView::new(
set_id,
Round(1),
)),
Some(ref mut v) => if v.set_id == set_id {
let diff_authorities =
self.authorities.iter().collect::<HashSet<_>>() !=
authorities.iter().collect();
if diff_authorities {
debug!(target: "afg",
"Gossip validator noted set {:?} twice with different authorities. \
Was the authority set hard forked?",
set_id,
);
self.authorities = authorities;
}
return None;
} else {
v
},
};
local_view.update_set(set_id);
self.live_topics.push(Round(1), set_id);
self.authorities = authorities;
}
self.multicast_neighbor_packet()
}
/// Note that we've imported a commit finalizing a given block.
fn note_commit_finalized(
&mut self,
round: Round,
set_id: SetId,
finalized: NumberFor<Block>,
) -> MaybeMessage<Block> {
{
match self.local_view {
None => return None,
Some(ref mut v) => if v.last_commit_height() < Some(&finalized) {
v.last_commit = Some((finalized, round, set_id));
} else {
return None
},
};
}
self.multicast_neighbor_packet()
}
fn consider_vote(&self, round: Round, set_id: SetId) -> Consider {
self.local_view.as_ref()
.map(LocalView::as_view)
.map(|v| v.consider_vote(round, set_id))
.unwrap_or(Consider::RejectOutOfScope)
}
fn consider_global(&self, set_id: SetId, number: NumberFor<Block>) -> Consider {
self.local_view.as_ref()
.map(LocalView::as_view)
.map(|v| v.consider_global(set_id, &number))
.unwrap_or(Consider::RejectOutOfScope)
}
fn cost_past_rejection(&self, _who: &PeerId, _round: Round, _set_id: SetId) -> ReputationChange {
// hardcoded for now.
cost::PAST_REJECTION
}
fn validate_round_message(&self, who: &PeerId, full: &VoteMessage<Block>)
-> Action<Block::Hash>
{
match self.consider_vote(full.round, full.set_id) {
Consider::RejectFuture => return Action::Discard(Misbehavior::FutureMessage.cost()),
Consider::RejectOutOfScope => return Action::Discard(Misbehavior::OutOfScopeMessage.cost()),
Consider::RejectPast =>
return Action::Discard(self.cost_past_rejection(who, full.round, full.set_id)),
Consider::Accept => {},
}
// ensure authority is part of the set.
if !self.authorities.contains(&full.message.id) {
debug!(target: "afg", "Message from unknown voter: {}", full.message.id);
telemetry!(CONSENSUS_DEBUG; "afg.bad_msg_signature"; "signature" => ?full.message.id);
return Action::Discard(cost::UNKNOWN_VOTER);
}
if !sp_finality_grandpa::check_message_signature(
&full.message.message,
&full.message.id,
&full.message.signature,
full.round.0,
full.set_id.0,
) {
debug!(target: "afg", "Bad message signature {}", full.message.id);
telemetry!(CONSENSUS_DEBUG; "afg.bad_msg_signature"; "signature" => ?full.message.id);
return Action::Discard(cost::BAD_SIGNATURE);
}
let topic = super::round_topic::<Block>(full.round.0, full.set_id.0);
Action::Keep(topic, benefit::ROUND_MESSAGE)
}
fn validate_commit_message(&mut self, who: &PeerId, full: &FullCommitMessage<Block>)
-> Action<Block::Hash>
{
if let Err(misbehavior) = self.peers.update_commit_height(who, full.message.target_number) {
return Action::Discard(misbehavior.cost());
}
match self.consider_global(full.set_id, full.message.target_number) {
Consider::RejectFuture => return Action::Discard(Misbehavior::FutureMessage.cost()),
Consider::RejectPast =>
return Action::Discard(self.cost_past_rejection(who, full.round, full.set_id)),
Consider::RejectOutOfScope => return Action::Discard(Misbehavior::OutOfScopeMessage.cost()),
Consider::Accept => {},
}
if full.message.precommits.len() != full.message.auth_data.len() || full.message.precommits.is_empty() {
debug!(target: "afg", "Malformed compact commit");
telemetry!(CONSENSUS_DEBUG; "afg.malformed_compact_commit";
"precommits_len" => ?full.message.precommits.len(),
"auth_data_len" => ?full.message.auth_data.len(),
"precommits_is_empty" => ?full.message.precommits.is_empty(),
);
return Action::Discard(cost::MALFORMED_COMMIT);
}
// always discard commits initially and rebroadcast after doing full
// checking.
let topic = super::global_topic::<Block>(full.set_id.0);
Action::ProcessAndDiscard(topic, benefit::BASIC_VALIDATED_COMMIT)
}
fn validate_catch_up_message(&mut self, who: &PeerId, full: &FullCatchUpMessage<Block>)
-> Action<Block::Hash>
{
match &self.pending_catch_up {
PendingCatchUp::Requesting { who: peer, request, instant } => {
if peer != who {
return Action::Discard(Misbehavior::OutOfScopeMessage.cost());
}
if request.set_id != full.set_id {
return Action::Discard(cost::MALFORMED_CATCH_UP);
}
if request.round.0 > full.message.round_number {
return Action::Discard(cost::MALFORMED_CATCH_UP);
}
if full.message.prevotes.is_empty() || full.message.precommits.is_empty() {
return Action::Discard(cost::MALFORMED_CATCH_UP);
}
// move request to pending processing state, we won't push out
// any catch up requests until we import this one (either with a
// success or failure).
self.pending_catch_up = PendingCatchUp::Processing {
instant: *instant,
};
// always discard catch up messages, they're point-to-point
let topic = super::global_topic::<Block>(full.set_id.0);
Action::ProcessAndDiscard(topic, benefit::BASIC_VALIDATED_CATCH_UP)
},
_ => Action::Discard(Misbehavior::OutOfScopeMessage.cost()),
}
}
fn note_catch_up_message_processed(&mut self) {
match &self.pending_catch_up {
PendingCatchUp::Processing { .. } => {
self.pending_catch_up = PendingCatchUp::None;
},
state => trace!(target: "afg",
"Noted processed catch up message when state was: {:?}",
state,
),
}
}
fn handle_catch_up_request(
&mut self,
who: &PeerId,
request: CatchUpRequestMessage,
set_state: &environment::SharedVoterSetState<Block>,
) -> (Option<GossipMessage<Block>>, Action<Block::Hash>) {
let local_view = match self.local_view {
None => return (None, Action::Discard(Misbehavior::OutOfScopeMessage.cost())),
Some(ref view) => view,
};
if request.set_id != local_view.set_id {
// NOTE: When we're close to a set change there is potentially a
// race where the peer sent us the request before it observed that
// we had transitioned to a new set. In this case we charge a lower
// cost.
if request.set_id.0.saturating_add(1) == local_view.set_id.0 &&
local_view.round.0.saturating_sub(CATCH_UP_THRESHOLD) == 0
{
return (None, Action::Discard(cost::HONEST_OUT_OF_SCOPE_CATCH_UP));
}
return (None, Action::Discard(Misbehavior::OutOfScopeMessage.cost()));
}
match self.peers.peer(who) {
None =>
return (None, Action::Discard(Misbehavior::OutOfScopeMessage.cost())),
Some(peer) if peer.view.round >= request.round =>
return (None, Action::Discard(Misbehavior::OutOfScopeMessage.cost())),
_ => {},
}
let last_completed_round = set_state.read().last_completed_round();
if last_completed_round.number < request.round.0 {
return (None, Action::Discard(Misbehavior::OutOfScopeMessage.cost()));
}
trace!(target: "afg", "Replying to catch-up request for round {} from {} with round {}",
request.round.0,
who,
last_completed_round.number,
);
let mut prevotes = Vec::new();
let mut precommits = Vec::new();
// NOTE: the set of votes stored in `LastCompletedRound` is a minimal
// set of votes, i.e. at most one equivocation is stored per voter. The
// code below assumes this invariant is maintained when creating the
// catch up reply since peers won't accept catch-up messages that have
// too many equivocations (we exceed the fault-tolerance bound).
for vote in last_completed_round.votes {
match vote.message {
finality_grandpa::Message::Prevote(prevote) => {
prevotes.push(finality_grandpa::SignedPrevote {
prevote,
signature: vote.signature,
id: vote.id,
});
},
finality_grandpa::Message::Precommit(precommit) => {
precommits.push(finality_grandpa::SignedPrecommit {
precommit,
signature: vote.signature,
id: vote.id,
});
},
_ => {},