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 GRANDPA equivocations
21
//! and some utility traits to wire together:
22
//! - a key ownership proof system (e.g. to prove that a given authority was
23
//! part of a session);
24
//! - a system for reporting offences;
25
//! - a system for signing and submitting transactions;
26
//! - a way to get the current block author;
27
//!
28
//! These can be used in an offchain context in order to submit equivocation
29
//! reporting extrinsics (from the client that's running the GRANDPA protocol).
30
//! And in a runtime context, so that the GRANDPA module can validate the
31
//! equivocation proofs in the extrinsic and report the offences.
32
//!
33
//! IMPORTANT:
34
//! When using this module for enabling equivocation reporting it is required
35
//! that the `ValidateUnsigned` for the GRANDPA pallet is used in the runtime
36
//! definition.
37

            
38
use alloc::{boxed::Box, vec, vec::Vec};
39
use codec::{self as codec, Decode, Encode};
40
use frame_support::traits::{Get, KeyOwnerProofSystem};
41
use frame_system::pallet_prelude::BlockNumberFor;
42
use log::{error, info};
43
use sp_consensus_grandpa::{AuthorityId, EquivocationProof, RoundNumber, SetId, KEY_TYPE};
44
use sp_runtime::{
45
	transaction_validity::{
46
		InvalidTransaction, TransactionPriority, TransactionSource, TransactionValidity,
47
		TransactionValidityError, ValidTransaction,
48
	},
49
	DispatchError, KeyTypeId, Perbill,
50
};
51
use sp_session::{GetSessionNumber, GetValidatorCount};
52
use sp_staking::{
53
	offence::{Kind, Offence, OffenceReportSystem, ReportOffence},
54
	SessionIndex,
55
};
56

            
57
use super::{Call, Config, Error, Pallet, LOG_TARGET};
58

            
59
/// A round number and set id which point on the time of an offence.
60
#[derive(Copy, Clone, PartialOrd, Ord, Eq, PartialEq, Encode, Decode)]
61
pub struct TimeSlot {
62
	// The order of these matters for `derive(Ord)`.
63
	/// Grandpa Set ID.
64
	pub set_id: SetId,
65
	/// Round number.
66
	pub round: RoundNumber,
67
}
68

            
69
/// GRANDPA equivocation offence report.
70
pub struct EquivocationOffence<Offender> {
71
	/// Time slot at which this incident happened.
72
	pub time_slot: TimeSlot,
73
	/// The session index in which the incident happened.
74
	pub session_index: SessionIndex,
75
	/// The size of the validator set at the time of the offence.
76
	pub validator_set_count: u32,
77
	/// The authority which produced this equivocation.
78
	pub offender: Offender,
79
}
80

            
81
impl<Offender: Clone> Offence<Offender> for EquivocationOffence<Offender> {
82
	const ID: Kind = *b"grandpa:equivoca";
83
	type TimeSlot = TimeSlot;
84

            
85
	fn offenders(&self) -> Vec<Offender> {
86
		vec![self.offender.clone()]
87
	}
88

            
89
	fn session_index(&self) -> SessionIndex {
90
		self.session_index
91
	}
92

            
93
	fn validator_set_count(&self) -> u32 {
94
		self.validator_set_count
95
	}
96

            
97
	fn time_slot(&self) -> Self::TimeSlot {
98
		self.time_slot
99
	}
100

            
101
	// The formula is min((3k / n)^2, 1)
102
	// where k = offenders_number and n = validators_number
103
	fn slash_fraction(&self, offenders_count: u32) -> Perbill {
104
		// Perbill type domain is [0, 1] by definition
105
		Perbill::from_rational(3 * offenders_count, self.validator_set_count).square()
106
	}
107
}
108

            
109
/// GRANDPA equivocation offence report system.
110
///
111
/// This type implements `OffenceReportSystem` such that:
112
/// - Equivocation reports are published on-chain as unsigned extrinsic via
113
///   `offchain::SendTransactionTypes`.
114
/// - On-chain validity checks and processing are mostly delegated to the user provided generic
115
///   types implementing `KeyOwnerProofSystem` and `ReportOffence` traits.
116
/// - Offence reporter for unsigned transactions is fetched via the the authorship pallet.
117
pub struct EquivocationReportSystem<T, R, P, L>(core::marker::PhantomData<(T, R, P, L)>);
118

            
119
impl<T, R, P, L>
120
	OffenceReportSystem<
121
		Option<T::AccountId>,
122
		(EquivocationProof<T::Hash, BlockNumberFor<T>>, T::KeyOwnerProof),
123
	> for EquivocationReportSystem<T, R, P, L>
124
where
125
	T: Config + pallet_authorship::Config + frame_system::offchain::SendTransactionTypes<Call<T>>,
126
	R: ReportOffence<
127
		T::AccountId,
128
		P::IdentificationTuple,
129
		EquivocationOffence<P::IdentificationTuple>,
130
	>,
131
	P: KeyOwnerProofSystem<(KeyTypeId, AuthorityId), Proof = T::KeyOwnerProof>,
132
	P::IdentificationTuple: Clone,
133
	L: Get<u64>,
134
{
135
	type Longevity = L;
136

            
137
	fn publish_evidence(
138
		evidence: (EquivocationProof<T::Hash, BlockNumberFor<T>>, T::KeyOwnerProof),
139
	) -> Result<(), ()> {
140
		use frame_system::offchain::SubmitTransaction;
141
		let (equivocation_proof, key_owner_proof) = evidence;
142

            
143
		let call = Call::report_equivocation_unsigned {
144
			equivocation_proof: Box::new(equivocation_proof),
145
			key_owner_proof,
146
		};
147
		let res = SubmitTransaction::<T, Call<T>>::submit_unsigned_transaction(call.into());
148
		match res {
149
			Ok(_) => info!(target: LOG_TARGET, "Submitted equivocation report"),
150
			Err(e) => error!(target: LOG_TARGET, "Error submitting equivocation report: {:?}", e),
151
		}
152
		res
153
	}
154

            
155
	fn check_evidence(
156
		evidence: (EquivocationProof<T::Hash, BlockNumberFor<T>>, T::KeyOwnerProof),
157
	) -> Result<(), TransactionValidityError> {
158
		let (equivocation_proof, key_owner_proof) = evidence;
159

            
160
		// Check the membership proof to extract the offender's id
161
		let key = (KEY_TYPE, equivocation_proof.offender().clone());
162
		let offender = P::check_proof(key, key_owner_proof).ok_or(InvalidTransaction::BadProof)?;
163

            
164
		// Check if the offence has already been reported, and if so then we can discard the report.
165
		let time_slot =
166
			TimeSlot { set_id: equivocation_proof.set_id(), round: equivocation_proof.round() };
167
		if R::is_known_offence(&[offender], &time_slot) {
168
			Err(InvalidTransaction::Stale.into())
169
		} else {
170
			Ok(())
171
		}
172
	}
173

            
174
1476
	fn process_evidence(
175
1476
		reporter: Option<T::AccountId>,
176
1476
		evidence: (EquivocationProof<T::Hash, BlockNumberFor<T>>, T::KeyOwnerProof),
177
1476
	) -> Result<(), DispatchError> {
178
1476
		let (equivocation_proof, key_owner_proof) = evidence;
179
1476
		let reporter = reporter.or_else(|| <pallet_authorship::Pallet<T>>::author());
180
1476
		let offender = equivocation_proof.offender().clone();
181
1476

            
182
1476
		// We check the equivocation within the context of its set id (and
183
1476
		// associated session) and round. We also need to know the validator
184
1476
		// set count when the offence since it is required to calculate the
185
1476
		// slash amount.
186
1476
		let set_id = equivocation_proof.set_id();
187
1476
		let round = equivocation_proof.round();
188
1476
		let session_index = key_owner_proof.session();
189
1476
		let validator_set_count = key_owner_proof.validator_count();
190
1476

            
191
1476
		// Validate equivocation proof (check votes are different and signatures are valid).
192
1476
		if !sp_consensus_grandpa::check_equivocation_proof(equivocation_proof) {
193
1248
			return Err(Error::<T>::InvalidEquivocationProof.into())
194
228
		}
195

            
196
		// Validate the key ownership proof extracting the id of the offender.
197
228
		let offender = P::check_proof((KEY_TYPE, offender), key_owner_proof)
198
228
			.ok_or(Error::<T>::InvalidKeyOwnershipProof)?;
199

            
200
		// Fetch the current and previous sets last session index.
201
		// For genesis set there's no previous set.
202
		let previous_set_id_session_index = if set_id != 0 {
203
			let idx = crate::SetIdSession::<T>::get(set_id - 1)
204
				.ok_or(Error::<T>::InvalidEquivocationProof)?;
205
			Some(idx)
206
		} else {
207
			None
208
		};
209

            
210
		let set_id_session_index =
211
			crate::SetIdSession::<T>::get(set_id).ok_or(Error::<T>::InvalidEquivocationProof)?;
212

            
213
		// Check that the session id for the membership proof is within the
214
		// bounds of the set id reported in the equivocation.
215
		if session_index > set_id_session_index ||
216
			previous_set_id_session_index
217
				.map(|previous_index| session_index <= previous_index)
218
				.unwrap_or(false)
219
		{
220
			return Err(Error::<T>::InvalidEquivocationProof.into())
221
		}
222

            
223
		let offence = EquivocationOffence {
224
			time_slot: TimeSlot { set_id, round },
225
			session_index,
226
			offender,
227
			validator_set_count,
228
		};
229

            
230
		R::report_offence(reporter.into_iter().collect(), offence)
231
			.map_err(|_| Error::<T>::DuplicateOffenceReport)?;
232

            
233
		Ok(())
234
1476
	}
235
}
236

            
237
/// Methods for the `ValidateUnsigned` implementation:
238
/// It restricts calls to `report_equivocation_unsigned` to local calls (i.e. extrinsics generated
239
/// on this node) or that already in a block. This guarantees that only block authors can include
240
/// unsigned equivocation reports.
241
impl<T: Config> Pallet<T> {
242
	pub fn validate_unsigned(source: TransactionSource, call: &Call<T>) -> TransactionValidity {
243
		if let Call::report_equivocation_unsigned { equivocation_proof, key_owner_proof } = call {
244
			// discard equivocation report not coming from the local node
245
			match source {
246
				TransactionSource::Local | TransactionSource::InBlock => { /* allowed */ },
247
				_ => {
248
					log::warn!(
249
						target: LOG_TARGET,
250
						"rejecting unsigned report equivocation transaction because it is not local/in-block."
251
					);
252

            
253
					return InvalidTransaction::Call.into()
254
				},
255
			}
256

            
257
			// Check report validity
258
			let evidence = (*equivocation_proof.clone(), key_owner_proof.clone());
259
			T::EquivocationReportSystem::check_evidence(evidence)?;
260

            
261
			let longevity =
262
				<T::EquivocationReportSystem as OffenceReportSystem<_, _>>::Longevity::get();
263

            
264
			ValidTransaction::with_tag_prefix("GrandpaEquivocation")
265
				// We assign the maximum priority for any equivocation report.
266
				.priority(TransactionPriority::max_value())
267
				// Only one equivocation report for the same offender at the same slot.
268
				.and_provides((
269
					equivocation_proof.offender().clone(),
270
					equivocation_proof.set_id(),
271
					equivocation_proof.round(),
272
				))
273
				.longevity(longevity)
274
				// We don't propagate this. This can never be included on a remote node.
275
				.propagate(false)
276
				.build()
277
		} else {
278
			InvalidTransaction::Call.into()
279
		}
280
	}
281

            
282
	pub fn pre_dispatch(call: &Call<T>) -> Result<(), TransactionValidityError> {
283
		if let Call::report_equivocation_unsigned { equivocation_proof, key_owner_proof } = call {
284
			let evidence = (*equivocation_proof.clone(), key_owner_proof.clone());
285
			T::EquivocationReportSystem::check_evidence(evidence)
286
		} else {
287
			Err(InvalidTransaction::Call.into())
288
		}
289
	}
290
}