Skip to main content

cumulus_client_consensus_aura/
equivocation_import_queue.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Cumulus.
3// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
4
5// Cumulus is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9
10// Cumulus is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14
15// You should have received a copy of the GNU General Public License
16// along with Cumulus. If not, see <https://www.gnu.org/licenses/>.
17
18/// An import queue which provides some equivocation resistance with lenient trait bounds.
19///
20/// Equivocation resistance in general is a hard problem, as different nodes in the network
21/// may see equivocations in a different order, and therefore may not agree on which blocks
22/// should be thrown out and which ones should be kept.
23use codec::Codec;
24use cumulus_client_consensus_common::ParachainBlockImportMarker;
25use cumulus_primitives_core::{CumulusDigestItem, RelayBlockIdentifier};
26use parking_lot::Mutex;
27use polkadot_primitives::Hash as RHash;
28use sc_consensus::{
29	import_queue::{BasicQueue, Verifier as VerifierT},
30	BlockImport, BlockImportParams, ForkChoiceStrategy,
31};
32use sc_consensus_aura::{standalone as aura_internal, AuthoritiesTracker};
33use sc_telemetry::{telemetry, TelemetryHandle, CONSENSUS_DEBUG, CONSENSUS_TRACE};
34use schnellru::{ByLength, LruMap};
35use sp_api::{ApiExt, ProvideRuntimeApi};
36use sp_block_builder::BlockBuilder as BlockBuilderApi;
37use sp_blockchain::{HeaderBackend, HeaderMetadata};
38use sp_consensus::{error::Error as ConsensusError, BlockOrigin};
39use sp_consensus_aura::{AuraApi, Slot, SlotDuration};
40use sp_core::crypto::Pair;
41use sp_inherents::CreateInherentDataProviders;
42use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor};
43use std::{fmt::Debug, sync::Arc};
44
45const LRU_WINDOW: u32 = 512;
46const EQUIVOCATION_LIMIT: usize = 16;
47
48struct NaiveEquivocationDefender<N> {
49	/// We distinguish blocks by `(Slot, BlockNumber, RelayParent)`.
50	cache: LruMap<(u64, N, RHash), usize>,
51}
52
53impl<N: std::hash::Hash + PartialEq> Default for NaiveEquivocationDefender<N> {
54	fn default() -> Self {
55		NaiveEquivocationDefender { cache: LruMap::new(ByLength::new(LRU_WINDOW)) }
56	}
57}
58
59impl<N: std::hash::Hash + PartialEq> NaiveEquivocationDefender<N> {
60	// Returns `true` if equivocation is beyond the limit.
61	fn insert_and_check(&mut self, slot: Slot, block_number: N, relay_chain_parent: RHash) -> bool {
62		let val = self
63			.cache
64			.get_or_insert((*slot, block_number, relay_chain_parent), || 0)
65			.expect("insertion with ByLength limiter always succeeds; qed");
66
67		if *val == EQUIVOCATION_LIMIT {
68			true
69		} else {
70			*val += 1;
71			false
72		}
73	}
74}
75
76/// A parachain block import verifier that checks for equivocation limits within each slot.
77pub struct Verifier<P: Pair, Client, Block: BlockT, CIDP> {
78	client: Arc<Client>,
79	create_inherent_data_providers: CIDP,
80	defender: Mutex<NaiveEquivocationDefender<NumberFor<Block>>>,
81	telemetry: Option<TelemetryHandle>,
82	// Unused for now. Will be plugged in with a later PR.
83	_authorities_tracker: AuthoritiesTracker<P, Block, Client>,
84}
85
86impl<P, Client, Block, CIDP> Verifier<P, Client, Block, CIDP>
87where
88	P: Pair,
89	P::Signature: Codec,
90	P::Public: Codec + Debug,
91	Block: BlockT,
92	Client: ProvideRuntimeApi<Block> + Send + Sync,
93	<Client as ProvideRuntimeApi<Block>>::Api: BlockBuilderApi<Block> + AuraApi<Block, P::Public>,
94
95	CIDP: CreateInherentDataProviders<Block, ()>,
96{
97	/// Creates a new Verifier instance for handling parachain block import verification in Aura
98	/// consensus.
99	pub fn new(
100		client: Arc<Client>,
101		inherent_data_provider: CIDP,
102		telemetry: Option<TelemetryHandle>,
103	) -> Self {
104		Self {
105			client: client.clone(),
106			create_inherent_data_providers: inherent_data_provider,
107			defender: Mutex::new(NaiveEquivocationDefender::default()),
108			telemetry,
109			_authorities_tracker: AuthoritiesTracker::new(client),
110		}
111	}
112}
113
114#[async_trait::async_trait]
115impl<P, Client, Block, CIDP> VerifierT<Block> for Verifier<P, Client, Block, CIDP>
116where
117	P: Pair,
118	P::Signature: Codec,
119	P::Public: Codec + Debug,
120	Block: BlockT,
121	Client: HeaderBackend<Block>
122		+ HeaderMetadata<Block, Error = sp_blockchain::Error>
123		+ ProvideRuntimeApi<Block>
124		+ Send
125		+ Sync,
126	<Client as ProvideRuntimeApi<Block>>::Api: BlockBuilderApi<Block> + AuraApi<Block, P::Public>,
127
128	CIDP: CreateInherentDataProviders<Block, ()>,
129{
130	async fn verify(
131		&self,
132		mut block_params: BlockImportParams<Block>,
133	) -> Result<BlockImportParams<Block>, String> {
134		// Skip checks that include execution, if being told so, or when importing only state.
135		//
136		// This is done for example when gap syncing and it is expected that the block after the gap
137		// was checked/chosen properly, e.g. by warp syncing to this block using a finality proof.
138		if block_params.state_action.skip_execution_checks() || block_params.with_state() {
139			block_params.fork_choice = Some(ForkChoiceStrategy::Custom(block_params.with_state()));
140			return Ok(block_params);
141		}
142
143		let post_hash = block_params.header.hash();
144		let parent_hash = *block_params.header.parent_hash();
145
146		// check seal and update pre-hash/post-hash
147		{
148			let authorities = aura_internal::fetch_authorities(self.client.as_ref(), parent_hash)
149				.map_err(|e| {
150				format!("Could not fetch authorities at {:?}: {}", parent_hash, e)
151			})?;
152
153			let mut runtime_api = self.client.runtime_api();
154			runtime_api.set_call_context(sp_core::traits::CallContext::Onchain);
155			let slot_duration =
156				runtime_api.slot_duration(parent_hash).map_err(|e| e.to_string())?;
157
158			let slot_now = slot_now(slot_duration);
159			let res = aura_internal::check_header_slot_and_seal::<Block, P>(
160				slot_now,
161				block_params.header,
162				&authorities,
163			);
164
165			match res {
166				Ok((pre_header, slot, seal_digest)) => {
167					telemetry!(
168						self.telemetry;
169						CONSENSUS_TRACE;
170						"aura.checked_and_importing";
171						"pre_header" => ?pre_header,
172					);
173
174					// We need some kind of identifier for the relay parent, in the worst case we
175					// take the all `0` hash.
176					let relay_parent =
177						match CumulusDigestItem::find_relay_block_identifier(pre_header.digest()) {
178							None => Default::default(),
179							Some(RelayBlockIdentifier::ByHash(h)) |
180							Some(RelayBlockIdentifier::ByStorageRoot {
181								storage_root: h, ..
182							}) => h,
183						};
184
185					block_params.header = pre_header;
186					block_params.post_digests.push(seal_digest);
187					block_params.fork_choice = Some(ForkChoiceStrategy::LongestChain);
188					block_params.post_hash = Some(post_hash);
189
190					// Check for and reject egregious amounts of equivocations.
191					//
192					// If the `origin` is `ConsensusBroadcast`, we ignore the result of the
193					// equivocation check. This `origin` is for example used by pov-recovery.
194					if self.defender.lock().insert_and_check(
195						slot,
196						*block_params.header.number(),
197						relay_parent,
198					) && !matches!(block_params.origin, BlockOrigin::ConsensusBroadcast)
199					{
200						return Err(format!(
201							"Rejecting block {:?} due to excessive equivocations at slot",
202							post_hash,
203						));
204					}
205				},
206				Err(aura_internal::SealVerificationError::Deferred(hdr, slot)) => {
207					telemetry!(
208						self.telemetry;
209						CONSENSUS_DEBUG;
210						"aura.header_too_far_in_future";
211						"hash" => ?post_hash,
212						"a" => ?hdr,
213						"b" => ?slot,
214					);
215
216					return Err(format!(
217						"Rejecting block ({:?}) from future slot {:?}",
218						post_hash, slot
219					));
220				},
221				Err(e) => {
222					return Err(format!(
223						"Rejecting block ({:?}) with invalid seal ({:?})",
224						post_hash, e
225					))
226				},
227			}
228		}
229
230		// Check inherents.
231		if let Some(body) = block_params.body.clone() {
232			let block = Block::new(block_params.header.clone(), body);
233			let create_inherent_data_providers = self
234				.create_inherent_data_providers
235				.create_inherent_data_providers(parent_hash, ())
236				.await
237				.map_err(|e| format!("Could not create inherent data {:?}", e))?;
238
239			sp_block_builder::check_inherents(
240				self.client.clone(),
241				parent_hash,
242				block,
243				&create_inherent_data_providers,
244			)
245			.await
246			.map_err(|e| format!("Error checking block inherents {:?}", e))?;
247		}
248
249		Ok(block_params)
250	}
251}
252
253fn slot_now(slot_duration: SlotDuration) -> Slot {
254	let timestamp = sp_timestamp::InherentDataProvider::from_system_time().timestamp();
255	Slot::from_timestamp(timestamp, slot_duration)
256}
257
258/// Start an import queue for a Cumulus node which checks blocks' seals and inherent data.
259///
260/// Pass in only inherent data providers which don't include aura or parachain consensus inherents,
261/// e.g. things like timestamp and custom inherents for the runtime.
262///
263/// The others are generated explicitly internally.
264///
265/// This should only be used for runtimes where the runtime does not check all inherents and
266/// seals in `execute_block` (see <https://github.com/paritytech/cumulus/issues/2436>)
267pub fn fully_verifying_import_queue<P, Client, Block: BlockT, I, CIDP>(
268	client: Arc<Client>,
269	block_import: I,
270	create_inherent_data_providers: CIDP,
271	spawner: &impl sp_core::traits::SpawnEssentialNamed,
272	registry: Option<&prometheus_endpoint::Registry>,
273	telemetry: Option<TelemetryHandle>,
274) -> BasicQueue<Block>
275where
276	P: Pair + 'static,
277	P::Signature: Codec,
278	P::Public: Codec + Debug,
279	I: BlockImport<Block, Error = ConsensusError>
280		+ ParachainBlockImportMarker
281		+ Send
282		+ Sync
283		+ 'static,
284	Client: HeaderBackend<Block>
285		+ HeaderMetadata<Block, Error = sp_blockchain::Error>
286		+ ProvideRuntimeApi<Block>
287		+ Send
288		+ Sync
289		+ 'static,
290	<Client as ProvideRuntimeApi<Block>>::Api: BlockBuilderApi<Block> + AuraApi<Block, P::Public>,
291	CIDP: CreateInherentDataProviders<Block, ()> + 'static,
292{
293	let verifier = Verifier::<P, _, _, _> {
294		client: client.clone(),
295		create_inherent_data_providers,
296		defender: Mutex::new(NaiveEquivocationDefender::default()),
297		telemetry,
298		_authorities_tracker: AuthoritiesTracker::new(client.clone()),
299	};
300
301	BasicQueue::new(verifier, Box::new(block_import), None, spawner, registry)
302}
303
304#[cfg(test)]
305mod test {
306	use super::*;
307	use codec::Encode;
308	use cumulus_test_client::{
309		runtime::Block, seal_block, Client, InitBlockBuilder, TestClientBuilder,
310		TestClientBuilderExt,
311	};
312	use cumulus_test_relay_sproof_builder::RelayStateSproofBuilder;
313	use futures::FutureExt;
314	use polkadot_primitives::{HeadData, PersistedValidationData};
315	use sc_client_api::HeaderBackend;
316	use sp_consensus_aura::sr25519;
317	use sp_tracing::try_init_simple;
318	use std::{collections::HashSet, sync::Arc};
319
320	#[test]
321	fn import_equivocated_blocks_from_recovery() {
322		try_init_simple();
323
324		let client = Arc::new(TestClientBuilder::default().build());
325
326		let verifier = Verifier::<sr25519::AuthorityPair, Client, Block, _> {
327			client: client.clone(),
328			create_inherent_data_providers: |_, _| async move {
329				Ok(sp_timestamp::InherentDataProvider::from_system_time())
330			},
331			defender: Mutex::new(NaiveEquivocationDefender::default()),
332			telemetry: None,
333			_authorities_tracker: AuthoritiesTracker::new(client.clone()),
334		};
335
336		let genesis = client.info().best_hash;
337		let mut sproof = RelayStateSproofBuilder::default();
338		sproof.included_para_head = Some(HeadData(client.header(genesis).unwrap().encode()));
339		sproof.para_id = cumulus_test_client::runtime::PARACHAIN_ID.into();
340
341		let validation_data = PersistedValidationData {
342			relay_parent_number: 1,
343			parent_head: client.header(genesis).unwrap().encode().into(),
344			..Default::default()
345		};
346
347		let block_builder = client.init_block_builder(Some(validation_data), sproof);
348		let block = block_builder.block_builder.build().unwrap();
349
350		let mut blocks = Vec::new();
351		for _ in 0..EQUIVOCATION_LIMIT + 1 {
352			blocks.push(seal_block(block.block.clone(), &client))
353		}
354
355		// sr25519 should generate a different signature every time you sign something and thus, all
356		// blocks get a different hash (even if they are the same block).
357		assert_eq!(blocks.iter().map(|b| b.hash()).collect::<HashSet<_>>().len(), blocks.len());
358
359		blocks.iter().take(EQUIVOCATION_LIMIT).for_each(|block| {
360			let mut params =
361				BlockImportParams::new(BlockOrigin::NetworkBroadcast, block.header().clone());
362			params.body = Some(block.extrinsics().to_vec());
363			verifier.verify(params).now_or_never().unwrap().unwrap();
364		});
365
366		// Now let's try some previously verified block and a block we have not verified yet.
367		//
368		// Verify should fail, because we are above the limit. However, when we change the origin to
369		// `ConsensusBroadcast`, it should work.
370		let extra_blocks =
371			vec![blocks[EQUIVOCATION_LIMIT / 2].clone(), blocks.last().unwrap().clone()];
372
373		extra_blocks.into_iter().for_each(|block| {
374			let mut params =
375				BlockImportParams::new(BlockOrigin::NetworkBroadcast, block.header().clone());
376			params.body = Some(block.extrinsics().to_vec());
377			assert!(verifier
378				.verify(params)
379				.now_or_never()
380				.unwrap()
381				.map(drop)
382				.unwrap_err()
383				.contains("excessive equivocations at slot"));
384
385			// When it comes from `pov-recovery`, we will accept it
386			let mut params =
387				BlockImportParams::new(BlockOrigin::ConsensusBroadcast, block.header().clone());
388			params.body = Some(block.extrinsics().to_vec());
389			assert!(verifier.verify(params).now_or_never().unwrap().is_ok());
390		});
391	}
392}