This repository was archived by the owner on Nov 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathslashing.rs
More file actions
912 lines (797 loc) · 28.7 KB
/
slashing.rs
File metadata and controls
912 lines (797 loc) · 28.7 KB
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
// Copyright 2022 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot 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.
// Polkadot 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 Polkadot. If not, see <http://www.gnu.org/licenses/>.
//! Dispute slashing pallet.
//!
//! The implementation relies on the `offences` pallet and
//! looks like a hybrid of `im-online` and `grandpa` equivocation handlers.
//! Meaning, we submit an `offence` for the concluded disputes about
//! the current session candidate directly from the runtime.
//! If, however, the dispute is about a past session, we record pending
//! slashes on chain, without `FullIdentification` of the offenders.
//! Later on, a block producer can submit an unsigned transaction with
//! `KeyOwnershipProof` of an offender and submit it to the runtime
//! to produce an offence.
//! The reason for this separation is that we do not want to rely on
//! `FullIdentification` to be available on chain for the past sessions
//! because it is quite heavy.
use crate::{
disputes,
initializer::ValidatorSetCount,
session_info::{AccountId, IdentificationTuple},
};
use frame_support::{
traits::{Defensive, Get, KeyOwnerProofSystem, ValidatorSet, ValidatorSetWithIdentification},
weights::{Pays, Weight},
};
use parity_scale_codec::{Decode, Encode};
use primitives::v2::{CandidateHash, SessionIndex, ValidatorId, ValidatorIndex};
use scale_info::TypeInfo;
use sp_runtime::{
traits::Convert,
transaction_validity::{
InvalidTransaction, TransactionPriority, TransactionSource, TransactionValidity,
TransactionValidityError, ValidTransaction,
},
DispatchResult, KeyTypeId, Perbill, RuntimeDebug,
};
use sp_session::{GetSessionNumber, GetValidatorCount};
use sp_staking::offence::{DisableStrategy, Kind, Offence, OffenceError, ReportOffence};
use sp_std::{
collections::btree_map::{BTreeMap, Entry},
prelude::*,
};
const LOG_TARGET: &str = "runtime::parachains::slashing";
// These are constants, but we want to make them configurable
// via `HostConfiguration` in the future.
const SLASH_FOR_INVALID: Perbill = Perbill::from_percent(100);
const SLASH_AGAINST_VALID: Perbill = Perbill::from_percent(1);
const DEFENSIVE_PROOF: &'static str = "disputes module should bail on old session";
#[cfg(feature = "runtime-benchmarks")]
pub mod benchmarking;
/// Timeslots should uniquely identify offences and are used for the offence
/// deduplication.
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Encode, Decode, TypeInfo, RuntimeDebug)]
pub struct DisputesTimeSlot {
// The order of these matters for `derive(Ord)`.
session_index: SessionIndex,
candidate_hash: CandidateHash,
}
impl DisputesTimeSlot {
pub fn new(session_index: SessionIndex, candidate_hash: CandidateHash) -> Self {
Self { session_index, candidate_hash }
}
}
/// An offence that is filed when a series of validators lost a dispute about an
/// invalid candidate.
#[derive(RuntimeDebug, TypeInfo)]
#[cfg_attr(feature = "std", derive(Clone, PartialEq, Eq))]
pub struct ForInvalidOffence<KeyOwnerIdentification> {
/// The size of the validator set in that session.
pub validator_set_count: ValidatorSetCount,
/// Should be unique per dispute.
pub time_slot: DisputesTimeSlot,
/// Staking information about the validators that lost the dispute
/// needed for slashing.
pub offenders: Vec<KeyOwnerIdentification>,
}
impl<Offender> Offence<Offender> for ForInvalidOffence<Offender>
where
Offender: Clone,
{
const ID: Kind = *b"disputes:invalid";
type TimeSlot = DisputesTimeSlot;
fn offenders(&self) -> Vec<Offender> {
self.offenders.clone()
}
fn session_index(&self) -> SessionIndex {
self.time_slot.session_index
}
fn validator_set_count(&self) -> ValidatorSetCount {
self.validator_set_count
}
fn time_slot(&self) -> Self::TimeSlot {
self.time_slot.clone()
}
fn disable_strategy(&self) -> DisableStrategy {
// The default is `DisableStrategy::DisableWhenSlashed`
// which is true for this offence type, but we're being explicit
DisableStrategy::Always
}
fn slash_fraction(_offenders: u32, _: ValidatorSetCount) -> Perbill {
SLASH_FOR_INVALID
}
}
/// An offence that is filed when a series of validators lost a dispute about an
/// valid candidate.
#[derive(RuntimeDebug, TypeInfo)]
#[cfg_attr(feature = "std", derive(Clone, PartialEq, Eq))]
pub struct AgainstValidOffence<KeyOwnerIdentification> {
/// The size of the validator set in that session.
pub validator_set_count: ValidatorSetCount,
/// Should be unique per dispute.
pub time_slot: DisputesTimeSlot,
/// Staking information about the validators that lost the dispute
/// needed for slashing.
pub offenders: Vec<KeyOwnerIdentification>,
}
impl<Offender> Offence<Offender> for AgainstValidOffence<Offender>
where
Offender: Clone,
{
const ID: Kind = *b"disputes:valid::";
type TimeSlot = DisputesTimeSlot;
fn offenders(&self) -> Vec<Offender> {
self.offenders.clone()
}
fn session_index(&self) -> SessionIndex {
self.time_slot.session_index
}
fn validator_set_count(&self) -> ValidatorSetCount {
self.validator_set_count
}
fn time_slot(&self) -> Self::TimeSlot {
self.time_slot.clone()
}
fn disable_strategy(&self) -> DisableStrategy {
DisableStrategy::Never
}
fn slash_fraction(_offenders: u32, _: ValidatorSetCount) -> Perbill {
SLASH_AGAINST_VALID
}
}
impl<KeyOwnerIdentification> ForInvalidOffence<KeyOwnerIdentification> {
fn new(
session_index: SessionIndex,
candidate_hash: CandidateHash,
validator_set_count: ValidatorSetCount,
offender: KeyOwnerIdentification,
) -> Self {
let time_slot = DisputesTimeSlot::new(session_index, candidate_hash);
Self { time_slot, validator_set_count, offenders: vec![offender] }
}
}
impl<KeyOwnerIdentification> AgainstValidOffence<KeyOwnerIdentification> {
fn new(
session_index: SessionIndex,
candidate_hash: CandidateHash,
validator_set_count: ValidatorSetCount,
offender: KeyOwnerIdentification,
) -> Self {
let time_slot = DisputesTimeSlot::new(session_index, candidate_hash);
Self { time_slot, validator_set_count, offenders: vec![offender] }
}
}
/// This type implements `SlashingHandler`.
pub struct SlashValidatorsForDisputes<C> {
_phantom: sp_std::marker::PhantomData<C>,
}
impl<C> Default for SlashValidatorsForDisputes<C> {
fn default() -> Self {
Self { _phantom: Default::default() }
}
}
impl<T> SlashValidatorsForDisputes<Pallet<T>>
where
T: Config,
{
/// If in the current session, returns the identified validators. `None`
/// otherwise.
fn maybe_identify_validators(
session_index: SessionIndex,
account_ids: &[AccountId<T>],
validators: impl IntoIterator<Item = ValidatorIndex>,
) -> Option<Vec<IdentificationTuple<T>>> {
// We use `ValidatorSet::session_index` and not
// `shared::Pallet<T>::session_index()` because at the first block of a new era,
// the `IdentificationOf` of a validator in the previous session might be
// missing, while `shared` pallet would return the same session index as being
// updated at the end of the block.
let current_session = T::ValidatorSet::session_index();
if session_index == current_session {
let fully_identified = validators
.into_iter()
.flat_map(|i| account_ids.get(i.0 as usize).cloned())
.filter_map(|id| {
<T::ValidatorSet as ValidatorSetWithIdentification<T::AccountId>>::IdentificationOf::convert(
id.clone()
).map(|full_id| (id, full_id))
})
.collect::<Vec<IdentificationTuple<T>>>();
return Some(fully_identified)
}
None
}
}
impl<T> disputes::SlashingHandler<T::BlockNumber> for SlashValidatorsForDisputes<Pallet<T>>
where
T: Config<KeyOwnerIdentification = IdentificationTuple<T>>,
{
fn punish_for_invalid(
session_index: SessionIndex,
candidate_hash: CandidateHash,
losers: impl IntoIterator<Item = ValidatorIndex>,
winners: impl IntoIterator<Item = ValidatorIndex>,
) {
let losers: Vec<ValidatorIndex> = losers.into_iter().collect();
if losers.is_empty() {
// Nothing to do
return
}
let account_keys = crate::session_info::Pallet::<T>::account_keys(session_index);
let account_ids = account_keys.defensive_unwrap_or_default();
let session_info = crate::session_info::Pallet::<T>::session_info(session_index);
let session_info = match session_info.defensive_proof(DEFENSIVE_PROOF) {
Some(info) => info,
None => return,
};
let validator_set_count = session_info.discovery_keys.len() as ValidatorSetCount;
let winners: Winners<T> = winners
.into_iter()
.filter_map(|i| account_ids.get(i.0 as usize).cloned())
.collect();
let maybe =
Self::maybe_identify_validators(session_index, &account_ids, losers.iter().cloned());
if let Some(offenders) = maybe {
let time_slot = DisputesTimeSlot::new(session_index, candidate_hash);
let offence = ForInvalidOffence { validator_set_count, time_slot, offenders };
// This is the first time we report an offence for this dispute,
// so it is not a duplicate.
let _ = T::HandleReports::report_for_invalid_offence(winners, offence);
return
}
let losers: Losers = losers
.into_iter()
.filter_map(|i| session_info.validators.get(i.0 as usize).cloned().map(|id| (i, id)))
.collect();
<PendingForInvalidLosers<T>>::insert(session_index, candidate_hash, losers);
<ForInvalidWinners<T>>::insert(session_index, candidate_hash, winners);
}
fn punish_against_valid(
session_index: SessionIndex,
candidate_hash: CandidateHash,
losers: impl IntoIterator<Item = ValidatorIndex>,
winners: impl IntoIterator<Item = ValidatorIndex>,
) {
let losers: Vec<ValidatorIndex> = losers.into_iter().collect();
if losers.is_empty() {
// Nothing to do
return
}
let account_keys = crate::session_info::Pallet::<T>::account_keys(session_index);
let account_ids = account_keys.defensive_unwrap_or_default();
let session_info = crate::session_info::Pallet::<T>::session_info(session_index);
let session_info = match session_info.defensive_proof(DEFENSIVE_PROOF) {
Some(info) => info,
None => return,
};
let validator_set_count = session_info.discovery_keys.len() as ValidatorSetCount;
let winners: Winners<T> = winners
.into_iter()
.filter_map(|i| account_ids.get(i.0 as usize).cloned())
.collect();
let maybe =
Self::maybe_identify_validators(session_index, &account_ids, losers.iter().cloned());
if let Some(offenders) = maybe {
let time_slot = DisputesTimeSlot::new(session_index, candidate_hash);
let offence = AgainstValidOffence { validator_set_count, time_slot, offenders };
// This is the first time we report an offence for this dispute,
// so it is not a duplicate.
let _ = T::HandleReports::report_against_valid_offence(winners, offence);
return
}
let losers: Losers = losers
.into_iter()
.filter_map(|i| session_info.validators.get(i.0 as usize).cloned().map(|id| (i, id)))
.collect();
<PendingAgainstValidLosers<T>>::insert(session_index, candidate_hash, losers);
<AgainstValidWinners<T>>::insert(session_index, candidate_hash, winners);
}
fn initializer_initialize(now: T::BlockNumber) -> Weight {
Pallet::<T>::initializer_initialize(now)
}
fn initializer_finalize() {
Pallet::<T>::initializer_finalize()
}
fn initializer_on_new_session(session_index: SessionIndex, count: ValidatorSetCount) {
Pallet::<T>::initializer_on_new_session(session_index, count)
}
}
#[derive(PartialEq, Eq, Clone, Copy, Encode, Decode, RuntimeDebug, TypeInfo)]
pub enum SlashingOffenceKind {
#[codec(index = 0)]
ForInvalid,
#[codec(index = 1)]
AgainstValid,
}
/// We store most of the information about a lost dispute on chain. This struct
/// is required to identify and verify it.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
pub struct DisputeProof {
/// Time slot when the dispute occured.
pub time_slot: DisputesTimeSlot,
/// The dispute outcome.
pub kind: SlashingOffenceKind,
/// The index of the validator who lost a dispute.
pub validator_index: ValidatorIndex,
/// The parachain session key of the validator.
pub validator_id: ValidatorId,
}
/// Indices and keys of the validators who lost a dispute and are pending
/// slashes.
pub type Losers = BTreeMap<ValidatorIndex, ValidatorId>;
/// `AccountId`s of the validators who were on the winning side of a dispute.
pub type Winners<T> = Vec<AccountId<T>>;
/// A trait that defines methods to report an offence (after the slashing report
/// has been validated) and for submitting a transaction to report a slash (from
/// an offchain context).
pub trait HandleReports<T: Config> {
/// The longevity, in blocks, that the offence report is valid for. When
/// using the staking pallet this should be equal to the bonding duration
/// (in blocks, not eras).
type ReportLongevity: Get<u64>;
/// Report a `for valid` offence.
fn report_for_invalid_offence(
reporters: Vec<AccountId<T>>,
offence: ForInvalidOffence<T::KeyOwnerIdentification>,
) -> Result<(), OffenceError>;
/// Report an against invalid offence.
fn report_against_valid_offence(
reporters: Vec<AccountId<T>>,
offence: AgainstValidOffence<T::KeyOwnerIdentification>,
) -> Result<(), OffenceError>;
/// Returns true if the offenders at the given time slot has already been
/// reported.
fn is_known_for_invalid_offence(
offenders: &[T::KeyOwnerIdentification],
time_slot: &DisputesTimeSlot,
) -> bool;
/// Returns true if the offenders at the given time slot has already been
/// reported.
fn is_known_against_valid_offence(
offenders: &[T::KeyOwnerIdentification],
time_slot: &DisputesTimeSlot,
) -> bool;
/// Create and dispatch a slashing report extrinsic.
/// This should be called offchain.
fn submit_unsigned_slashing_report(
dispute_proof: DisputeProof,
key_owner_proof: T::KeyOwnerProof,
) -> DispatchResult;
}
impl<T: Config> HandleReports<T> for () {
type ReportLongevity = ();
fn report_for_invalid_offence(
_reporters: Vec<AccountId<T>>,
_offence: ForInvalidOffence<T::KeyOwnerIdentification>,
) -> Result<(), OffenceError> {
Ok(())
}
fn report_against_valid_offence(
_reporters: Vec<AccountId<T>>,
_offence: AgainstValidOffence<T::KeyOwnerIdentification>,
) -> Result<(), OffenceError> {
Ok(())
}
fn is_known_for_invalid_offence(
_offenders: &[T::KeyOwnerIdentification],
_time_slot: &DisputesTimeSlot,
) -> bool {
true
}
fn is_known_against_valid_offence(
_offenders: &[T::KeyOwnerIdentification],
_time_slot: &DisputesTimeSlot,
) -> bool {
true
}
fn submit_unsigned_slashing_report(
_dispute_proof: DisputeProof,
_key_owner_proof: T::KeyOwnerProof,
) -> DispatchResult {
Ok(())
}
}
pub trait WeightInfo {
fn report_dispute_lost(validator_count: ValidatorSetCount) -> Weight;
}
pub struct TestWeightInfo;
impl WeightInfo for TestWeightInfo {
fn report_dispute_lost(_validator_count: ValidatorSetCount) -> Weight {
0
}
}
pub use pallet::*;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
#[pallet::config]
pub trait Config: frame_system::Config + crate::disputes::Config {
/// The proof of key ownership, used for validating slashing reports.
/// The proof must include the session index and validator count of the
/// session at which the offence occurred.
type KeyOwnerProof: Parameter + GetSessionNumber + GetValidatorCount;
/// The identification of a key owner, used when reporting slashes.
type KeyOwnerIdentification: Parameter;
/// A system for proving ownership of keys, i.e. that a given key was
/// part of a validator set, needed for validating slashing reports.
type KeyOwnerProofSystem: KeyOwnerProofSystem<
(KeyTypeId, ValidatorId),
Proof = Self::KeyOwnerProof,
IdentificationTuple = Self::KeyOwnerIdentification,
>;
/// The slashing report handling subsystem, defines methods to report an
/// offence (after the slashing report has been validated) and for
/// submitting a transaction to report a slash (from an offchain
/// context). NOTE: when enabling slashing report handling (i.e. this
/// type isn't set to `()`) you must use this pallet's
/// `ValidateUnsigned` in the runtime definition.
type HandleReports: HandleReports<Self>;
/// Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
}
#[pallet::pallet]
#[pallet::without_storage_info]
pub struct Pallet<T>(_);
/// Indices of the validators pending "for invalid" dispute slashes.
#[pallet::storage]
pub(super) type PendingForInvalidLosers<T> =
StorageDoubleMap<_, Twox64Concat, SessionIndex, Blake2_128Concat, CandidateHash, Losers>;
/// Indices of the validators who won in "for invalid" disputes.
#[pallet::storage]
pub(super) type ForInvalidWinners<T> = StorageDoubleMap<
_,
Twox64Concat,
SessionIndex,
Blake2_128Concat,
CandidateHash,
Winners<T>,
>;
/// `ValidatorSetCount` per session.
#[pallet::storage]
pub(super) type ValidatorSetCounts<T> =
StorageMap<_, Twox64Concat, SessionIndex, ValidatorSetCount>;
/// Indices of the validators pending "against valid" dispute slashes.
#[pallet::storage]
pub(super) type PendingAgainstValidLosers<T> =
StorageDoubleMap<_, Twox64Concat, SessionIndex, Blake2_128Concat, CandidateHash, Losers>;
/// Indices of the validators who won in "against valid" disputes.
#[pallet::storage]
pub(super) type AgainstValidWinners<T> = StorageDoubleMap<
_,
Twox64Concat,
SessionIndex,
Blake2_128Concat,
CandidateHash,
Winners<T>,
>;
#[pallet::error]
pub enum Error<T> {
/// The key ownership proof is invalid.
InvalidKeyOwnershipProof,
/// The session index is too old or invalid.
InvalidSessionIndex,
/// The candidate hash is invalid.
InvalidCandidateHash,
/// There is no pending slash for the given validator index and time
/// slot.
InvalidValidatorIndex,
/// The validator index does not match the validator id.
ValidatorIndexIdMismatch,
/// The given slashing report is valid but already previously reported.
DuplicateSlashingReport,
}
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::weight(<T as Config>::WeightInfo::report_dispute_lost(
key_owner_proof.validator_count()
))]
pub fn report_dispute_lost_unsigned(
origin: OriginFor<T>,
// box to decrease the size of the call
dispute_proof: Box<DisputeProof>,
key_owner_proof: T::KeyOwnerProof,
) -> DispatchResultWithPostInfo {
ensure_none(origin)?;
// check the membership proof to extract the offender's id
let key = (primitives::v2::PARACHAIN_KEY_TYPE_ID, dispute_proof.validator_id.clone());
let offender = T::KeyOwnerProofSystem::check_proof(key, key_owner_proof)
.ok_or(Error::<T>::InvalidKeyOwnershipProof)?;
let session_index = dispute_proof.time_slot.session_index;
let validator_set_count = <ValidatorSetCounts<T>>::get(session_index)
.ok_or(Error::<T>::InvalidSessionIndex)?;
// check that there is a pending slash for the given
// validator index and candidate hash
let candidate_hash = dispute_proof.time_slot.candidate_hash;
let try_remove = |v: &mut Option<Losers>| -> Result<bool, DispatchError> {
let indices = v.as_mut().ok_or(Error::<T>::InvalidCandidateHash)?;
match indices.entry(dispute_proof.validator_index) {
Entry::Vacant(_) => return Err(Error::<T>::InvalidValidatorIndex.into()),
// check that `validator_index` matches `validator_id`
Entry::Occupied(e) if e.get() != &dispute_proof.validator_id =>
return Err(Error::<T>::ValidatorIndexIdMismatch.into()),
Entry::Occupied(e) => {
e.remove(); // all good
},
}
let is_empty = if indices.is_empty() {
*v = None;
true
} else {
false
};
Ok(is_empty)
};
match dispute_proof.kind {
SlashingOffenceKind::ForInvalid => {
let is_empty = <PendingForInvalidLosers<T>>::try_mutate_exists(
&session_index,
&candidate_hash,
try_remove,
)?;
let winners = if is_empty {
<ForInvalidWinners<T>>::take(&session_index, &candidate_hash)
.unwrap_or_default()
} else {
<ForInvalidWinners<T>>::get(&session_index, &candidate_hash)
.unwrap_or_default()
};
let offence = ForInvalidOffence::new(
session_index,
candidate_hash,
validator_set_count,
offender,
);
// We can't really submit a duplicate report
// unless there's a bug.
<T::HandleReports as HandleReports<T>>::report_for_invalid_offence(
winners, offence,
)
.map_err(|_| Error::<T>::DuplicateSlashingReport)?;
},
SlashingOffenceKind::AgainstValid => {
let is_empty = <PendingAgainstValidLosers<T>>::try_mutate_exists(
&session_index,
&candidate_hash,
try_remove,
)?;
let winners = if is_empty {
<AgainstValidWinners<T>>::take(&session_index, &candidate_hash)
.unwrap_or_default()
} else {
<AgainstValidWinners<T>>::get(&session_index, &candidate_hash)
.unwrap_or_default()
};
// submit an offence report
let offence = AgainstValidOffence::new(
session_index,
candidate_hash,
validator_set_count,
offender,
);
// We can't really submit a duplicate report
// unless there's a bug.
<T::HandleReports as HandleReports<T>>::report_against_valid_offence(
winners, offence,
)
.map_err(|_| Error::<T>::DuplicateSlashingReport)?;
},
}
Ok(Pays::No.into())
}
}
#[pallet::validate_unsigned]
impl<T: Config> ValidateUnsigned for Pallet<T> {
type Call = Call<T>;
fn validate_unsigned(source: TransactionSource, call: &Self::Call) -> TransactionValidity {
Self::validate_unsigned(source, call)
}
fn pre_dispatch(call: &Self::Call) -> Result<(), TransactionValidityError> {
Self::pre_dispatch(call)
}
}
}
impl<T: Config> Pallet<T> {
/// Called by the initializer to initialize the disputes slashing module.
fn initializer_initialize(_now: T::BlockNumber) -> Weight {
0
}
/// Called by the initializer to finalize the disputes slashing pallet.
fn initializer_finalize() {}
/// Called by the initializer to note a new session in the disputes slashing
/// pallet.
fn initializer_on_new_session(
session_index: SessionIndex,
validator_set_count: ValidatorSetCount,
) {
<ValidatorSetCounts<T>>::insert(session_index, validator_set_count);
let config = <crate::configuration::Pallet<T>>::config();
if session_index <= config.dispute_period + 1 {
return
}
let old_session = session_index - config.dispute_period - 1;
// This should be small, as disputes are rare, so no limit is fine.
const REMOVE_LIMIT: u32 = u32::MAX;
let _ = <PendingForInvalidLosers<T>>::clear_prefix(old_session, REMOVE_LIMIT, None);
let _ = <PendingAgainstValidLosers<T>>::clear_prefix(old_session, REMOVE_LIMIT, None);
let _ = <ForInvalidWinners<T>>::clear_prefix(old_session, REMOVE_LIMIT, None);
let _ = <AgainstValidWinners<T>>::clear_prefix(old_session, REMOVE_LIMIT, None);
<ValidatorSetCounts<T>>::remove(old_session);
}
}
/// Methods for the `ValidateUnsigned` implementation:
///
/// It restricts calls to `report_dispute_lost_unsigned` to local calls (i.e.
/// extrinsics generated on this node) or that already in a block. This
/// guarantees that only block authors can include unsigned slashing reports.
impl<T: Config> Pallet<T> {
pub fn validate_unsigned(source: TransactionSource, call: &Call<T>) -> TransactionValidity {
if let Call::report_dispute_lost_unsigned { dispute_proof, key_owner_proof } = call {
// discard slashing report not coming from the local node
match source {
TransactionSource::Local | TransactionSource::InBlock => { /* allowed */ },
_ => {
log::warn!(
target: LOG_TARGET,
"rejecting unsigned transaction because it is not local/in-block."
);
return InvalidTransaction::Call.into()
},
}
// check report staleness
is_known_offence::<T>(dispute_proof, key_owner_proof)?;
let longevity = <T::HandleReports as HandleReports<T>>::ReportLongevity::get();
let tag_prefix = match dispute_proof.kind {
SlashingOffenceKind::ForInvalid => "DisputeForInvalid",
SlashingOffenceKind::AgainstValid => "DisputeAgainstValid",
};
ValidTransaction::with_tag_prefix(tag_prefix)
// We assign the maximum priority for any report.
.priority(TransactionPriority::max_value())
// Only one report for the same offender at the same slot.
.and_provides((dispute_proof.time_slot.clone(), dispute_proof.validator_id.clone()))
.longevity(longevity)
// We don't propagate this. This can never be included on a remote node.
.propagate(false)
.build()
} else {
InvalidTransaction::Call.into()
}
}
pub fn pre_dispatch(call: &Call<T>) -> Result<(), TransactionValidityError> {
if let Call::report_dispute_lost_unsigned { dispute_proof, key_owner_proof } = call {
is_known_offence::<T>(dispute_proof, key_owner_proof)
} else {
Err(InvalidTransaction::Call.into())
}
}
}
fn is_known_offence<T: Config>(
dispute_proof: &DisputeProof,
key_owner_proof: &T::KeyOwnerProof,
) -> Result<(), TransactionValidityError> {
// check the membership proof to extract the offender's id
let key = (primitives::v2::PARACHAIN_KEY_TYPE_ID, dispute_proof.validator_id.clone());
let offender = T::KeyOwnerProofSystem::check_proof(key, key_owner_proof.clone())
.ok_or(InvalidTransaction::BadProof)?;
// check if the offence has already been reported,
// and if so then we can discard the report.
let is_known_offence = match dispute_proof.kind {
SlashingOffenceKind::ForInvalid =>
<T::HandleReports as HandleReports<T>>::is_known_for_invalid_offence(
&[offender],
&dispute_proof.time_slot,
),
SlashingOffenceKind::AgainstValid =>
<T::HandleReports as HandleReports<T>>::is_known_against_valid_offence(
&[offender],
&dispute_proof.time_slot,
),
};
if is_known_offence {
Err(InvalidTransaction::Stale.into())
} else {
Ok(())
}
}
/// Actual `HandleReports` implemention.
///
/// When configured properly, should be instantiated with
/// `T::KeyOwnerIdentification, Offences, ReportLongevity` parameters.
pub struct SlashingReportHandler<I, R, L> {
_phantom: sp_std::marker::PhantomData<(I, R, L)>,
}
impl<I, R, L> Default for SlashingReportHandler<I, R, L> {
fn default() -> Self {
Self { _phantom: Default::default() }
}
}
impl<T, R, L> HandleReports<T> for SlashingReportHandler<T::KeyOwnerIdentification, R, L>
where
T: Config + frame_system::offchain::SendTransactionTypes<Call<T>>,
R: ReportOffence<
AccountId<T>,
T::KeyOwnerIdentification,
ForInvalidOffence<T::KeyOwnerIdentification>,
> + ReportOffence<
AccountId<T>,
T::KeyOwnerIdentification,
AgainstValidOffence<T::KeyOwnerIdentification>,
>,
L: Get<u64>,
{
type ReportLongevity = L;
fn report_for_invalid_offence(
reporters: Vec<AccountId<T>>,
offence: ForInvalidOffence<T::KeyOwnerIdentification>,
) -> Result<(), OffenceError> {
R::report_offence(reporters, offence)
}
fn report_against_valid_offence(
reporters: Vec<AccountId<T>>,
offence: AgainstValidOffence<T::KeyOwnerIdentification>,
) -> Result<(), OffenceError> {
R::report_offence(reporters, offence)
}
fn is_known_for_invalid_offence(
offenders: &[T::KeyOwnerIdentification],
time_slot: &DisputesTimeSlot,
) -> bool {
<R as ReportOffence<
AccountId<T>,
T::KeyOwnerIdentification,
ForInvalidOffence<T::KeyOwnerIdentification>,
>>::is_known_offence(offenders, time_slot)
}
fn is_known_against_valid_offence(
offenders: &[T::KeyOwnerIdentification],
time_slot: &DisputesTimeSlot,
) -> bool {
<R as ReportOffence<
AccountId<T>,
T::KeyOwnerIdentification,
AgainstValidOffence<T::KeyOwnerIdentification>,
>>::is_known_offence(offenders, time_slot)
}
fn submit_unsigned_slashing_report(
dispute_proof: DisputeProof,
key_owner_proof: <T as Config>::KeyOwnerProof,
) -> DispatchResult {
use frame_system::offchain::SubmitTransaction;
let session_index = dispute_proof.time_slot.session_index;
let validator_index = dispute_proof.validator_index.0;
let kind = dispute_proof.kind;
let call = Call::report_dispute_lost_unsigned {
dispute_proof: Box::new(dispute_proof),
key_owner_proof,
};
match SubmitTransaction::<T, Call<T>>::submit_unsigned_transaction(call.into()) {
Ok(()) => log::info!(
target: LOG_TARGET,
"Submitted dispute slashing report, session({}), index({}), kind({:?})",
session_index,
validator_index,
kind,
),
Err(()) => log::error!(
target: LOG_TARGET,
"Error submitting dispute slashing report, session({}), index({}), kind({:?})",
session_index,
validator_index,
kind,
),
}
Ok(())
}
}