referrerpolicy=no-referrer-when-downgrade

pallet_babe/
equivocation.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! An opt-in utility module for reporting equivocations.
19//!
20//! This module defines an offence type for BABE equivocations
21//! and some utility traits to wire together:
22//! - a system for reporting offences;
23//! - a system for submitting unsigned transactions;
24//! - a way to get the current block author;
25//!
26//! These can be used in an offchain context in order to submit equivocation
27//! reporting extrinsics (from the client that's import BABE blocks).
28//! And in a runtime context, so that the BABE pallet can validate the
29//! equivocation proofs in the extrinsic and report the offences.
30//!
31//! IMPORTANT:
32//! When using this module for enabling equivocation reporting it is required
33//! that the `ValidateUnsigned` for the BABE pallet is used in the runtime
34//! definition.
35
36use alloc::{boxed::Box, vec, vec::Vec};
37use frame_support::traits::{Get, KeyOwnerProofSystem};
38use frame_system::pallet_prelude::HeaderFor;
39use log::{error, info};
40
41use sp_consensus_babe::{AuthorityId, EquivocationProof, Slot, KEY_TYPE};
42use sp_runtime::{
43	transaction_validity::{
44		InvalidTransaction, TransactionPriority, TransactionSource, TransactionValidity,
45		TransactionValidityError, ValidTransaction,
46	},
47	DispatchError, KeyTypeId, Perbill,
48};
49use sp_session::{GetSessionNumber, GetValidatorCount};
50use sp_staking::{
51	offence::{Kind, Offence, OffenceReportSystem, ReportOffence},
52	SessionIndex,
53};
54
55use crate::{Call, Config, Error, Pallet, LOG_TARGET};
56
57/// BABE equivocation offence report.
58///
59/// When a validator released two or more blocks at the same slot.
60pub struct EquivocationOffence<Offender> {
61	/// A babe slot in which this incident happened.
62	pub slot: Slot,
63	/// The session index in which the incident happened.
64	pub session_index: SessionIndex,
65	/// The size of the validator set at the time of the offence.
66	pub validator_set_count: u32,
67	/// The authority that produced the equivocation.
68	pub offender: Offender,
69}
70
71impl<Offender: Clone> Offence<Offender> for EquivocationOffence<Offender> {
72	const ID: Kind = *b"babe:equivocatio";
73	type TimeSlot = Slot;
74
75	fn offenders(&self) -> Vec<Offender> {
76		vec![self.offender.clone()]
77	}
78
79	fn session_index(&self) -> SessionIndex {
80		self.session_index
81	}
82
83	fn validator_set_count(&self) -> u32 {
84		self.validator_set_count
85	}
86
87	fn time_slot(&self) -> Self::TimeSlot {
88		self.slot
89	}
90
91	// The formula is min((3k / n)^2, 1)
92	// where k = offenders_number and n = validators_number
93	fn slash_fraction(&self, offenders_count: u32) -> Perbill {
94		// Perbill type domain is [0, 1] by definition
95		Perbill::from_rational(3 * offenders_count, self.validator_set_count).square()
96	}
97}
98
99/// BABE equivocation offence report system.
100///
101/// This type implements `OffenceReportSystem` such that:
102/// - Equivocation reports are published on-chain as unsigned extrinsic via
103///   `offchain::CreateTransactionBase`.
104/// - On-chain validity checks and processing are mostly delegated to the user provided generic
105///   types implementing `KeyOwnerProofSystem` and `ReportOffence` traits.
106/// - Offence reporter for unsigned transactions is fetched via the the authorship pallet.
107pub struct EquivocationReportSystem<T, R, P, L>(core::marker::PhantomData<(T, R, P, L)>);
108
109impl<T, R, P, L>
110	OffenceReportSystem<Option<T::AccountId>, (EquivocationProof<HeaderFor<T>>, T::KeyOwnerProof)>
111	for EquivocationReportSystem<T, R, P, L>
112where
113	T: Config + pallet_authorship::Config + frame_system::offchain::CreateBare<Call<T>>,
114	R: ReportOffence<
115		T::AccountId,
116		P::IdentificationTuple,
117		EquivocationOffence<P::IdentificationTuple>,
118	>,
119	P: KeyOwnerProofSystem<(KeyTypeId, AuthorityId), Proof = T::KeyOwnerProof>,
120	P::IdentificationTuple: Clone,
121	L: Get<u64>,
122{
123	type Longevity = L;
124
125	fn publish_evidence(
126		evidence: (EquivocationProof<HeaderFor<T>>, T::KeyOwnerProof),
127	) -> Result<(), ()> {
128		use frame_system::offchain::SubmitTransaction;
129		let (equivocation_proof, key_owner_proof) = evidence;
130
131		let call = Call::report_equivocation_unsigned {
132			equivocation_proof: Box::new(equivocation_proof),
133			key_owner_proof,
134		};
135		let xt = T::create_bare(call.into());
136		let res = SubmitTransaction::<T, Call<T>>::submit_transaction(xt);
137		match res {
138			Ok(_) => info!(target: LOG_TARGET, "Submitted equivocation report"),
139			Err(e) => error!(target: LOG_TARGET, "Error submitting equivocation report: {:?}", e),
140		}
141		res
142	}
143
144	fn check_evidence(
145		evidence: (EquivocationProof<HeaderFor<T>>, T::KeyOwnerProof),
146	) -> Result<(), TransactionValidityError> {
147		let (equivocation_proof, key_owner_proof) = evidence;
148
149		// Check the membership proof to extract the offender's id
150		let key = (sp_consensus_babe::KEY_TYPE, equivocation_proof.offender.clone());
151		let offender =
152			P::check_proof(key, key_owner_proof.clone()).ok_or(InvalidTransaction::BadProof)?;
153
154		// Check if the offence has already been reported, and if so then we can discard the report.
155		if R::is_known_offence(&[offender], &equivocation_proof.slot) {
156			Err(InvalidTransaction::Stale.into())
157		} else {
158			Ok(())
159		}
160	}
161
162	fn process_evidence(
163		reporter: Option<T::AccountId>,
164		evidence: (EquivocationProof<HeaderFor<T>>, T::KeyOwnerProof),
165	) -> Result<(), DispatchError> {
166		let (equivocation_proof, key_owner_proof) = evidence;
167		let reporter = reporter.or_else(|| <pallet_authorship::Pallet<T>>::author());
168		let offender = equivocation_proof.offender.clone();
169		let slot = equivocation_proof.slot;
170
171		// Validate the equivocation proof (check votes are different and signatures are valid)
172		if !sp_consensus_babe::check_equivocation_proof(equivocation_proof) {
173			return Err(Error::<T>::InvalidEquivocationProof.into())
174		}
175
176		let validator_set_count = key_owner_proof.validator_count();
177		let session_index = key_owner_proof.session();
178
179		let epoch_index =
180			*slot.saturating_sub(crate::GenesisSlot::<T>::get()) / T::EpochDuration::get();
181
182		// Check that the slot number is consistent with the session index
183		// in the key ownership proof (i.e. slot is for that epoch)
184		if Pallet::<T>::session_index_for_epoch(epoch_index) != session_index {
185			return Err(Error::<T>::InvalidKeyOwnershipProof.into())
186		}
187
188		// Check the membership proof and extract the offender's id
189		let offender = P::check_proof((KEY_TYPE, offender), key_owner_proof)
190			.ok_or(Error::<T>::InvalidKeyOwnershipProof)?;
191
192		let offence = EquivocationOffence { slot, validator_set_count, offender, session_index };
193
194		R::report_offence(reporter.into_iter().collect(), offence)
195			.map_err(|_| Error::<T>::DuplicateOffenceReport)?;
196
197		Ok(())
198	}
199}
200
201/// Methods for the `ValidateUnsigned` implementation:
202/// It restricts calls to `report_equivocation_unsigned` to local calls (i.e. extrinsics generated
203/// on this node) or that already in a block. This guarantees that only block authors can include
204/// unsigned equivocation reports.
205impl<T: Config> Pallet<T> {
206	pub fn validate_unsigned(source: TransactionSource, call: &Call<T>) -> TransactionValidity {
207		if let Call::report_equivocation_unsigned { equivocation_proof, key_owner_proof } = call {
208			// discard equivocation report not coming from the local node
209			match source {
210				TransactionSource::Local | TransactionSource::InBlock => { /* allowed */ },
211				_ => {
212					log::warn!(
213						target: LOG_TARGET,
214						"rejecting unsigned report equivocation transaction because it is not local/in-block.",
215					);
216
217					return InvalidTransaction::Call.into()
218				},
219			}
220
221			// Check report validity
222			let evidence = (*equivocation_proof.clone(), key_owner_proof.clone());
223			T::EquivocationReportSystem::check_evidence(evidence)?;
224
225			let longevity =
226				<T::EquivocationReportSystem as OffenceReportSystem<_, _>>::Longevity::get();
227
228			ValidTransaction::with_tag_prefix("BabeEquivocation")
229				// We assign the maximum priority for any equivocation report.
230				.priority(TransactionPriority::max_value())
231				// Only one equivocation report for the same offender at the same slot.
232				.and_provides((equivocation_proof.offender.clone(), *equivocation_proof.slot))
233				.longevity(longevity)
234				// We don't propagate this. This can never be included on a remote node.
235				.propagate(false)
236				.build()
237		} else {
238			InvalidTransaction::Call.into()
239		}
240	}
241
242	pub fn pre_dispatch(call: &Call<T>) -> Result<(), TransactionValidityError> {
243		if let Call::report_equivocation_unsigned { equivocation_proof, key_owner_proof } = call {
244			let evidence = (*equivocation_proof.clone(), key_owner_proof.clone());
245			T::EquivocationReportSystem::check_evidence(evidence)
246		} else {
247			Err(InvalidTransaction::Call.into())
248		}
249	}
250}