referrerpolicy=no-referrer-when-downgrade

sp_consensus_aura/
digests.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//! Aura (Authority-Round) digests
19//!
20//! This implements the digests for AuRa, to allow the private
21//! `CompatibleDigestItem` trait to appear in public interfaces.
22
23use crate::AURA_ENGINE_ID;
24use codec::{Codec, Encode};
25use sp_consensus_slots::Slot;
26use sp_runtime::generic::{Digest, DigestItem};
27
28/// A digest item which is usable with aura consensus.
29pub trait CompatibleDigestItem<Signature>: Sized {
30	/// Construct a digest item which contains a signature on the hash.
31	fn aura_seal(signature: Signature) -> Self;
32
33	/// If this item is an Aura seal, return the signature.
34	fn as_aura_seal(&self) -> Option<Signature>;
35
36	/// Construct a digest item which contains the slot number
37	fn aura_pre_digest(slot: Slot) -> Self;
38
39	/// If this item is an AuRa pre-digest, return the slot number
40	fn as_aura_pre_digest(&self) -> Option<Slot>;
41}
42
43impl<Signature> CompatibleDigestItem<Signature> for DigestItem
44where
45	Signature: Codec,
46{
47	fn aura_seal(signature: Signature) -> Self {
48		DigestItem::Seal(AURA_ENGINE_ID, signature.encode())
49	}
50
51	fn as_aura_seal(&self) -> Option<Signature> {
52		self.seal_try_to(&AURA_ENGINE_ID)
53	}
54
55	fn aura_pre_digest(slot: Slot) -> Self {
56		DigestItem::PreRuntime(AURA_ENGINE_ID, slot.encode())
57	}
58
59	fn as_aura_pre_digest(&self) -> Option<Slot> {
60		self.pre_runtime_try_to(&AURA_ENGINE_ID)
61	}
62}
63
64/// Errors in seal lookup.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum SealLookupError {
67	/// The digest is empty.
68	Unsealed,
69	/// The last digest item is not a valid AuRa seal.
70	BadSeal,
71	/// There are multiple AuRa seals.
72	MultipleSeals,
73}
74
75/// Errors in pre-digest lookup.
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum PreDigestLookupError {
78	/// Multiple AuRa pre-runtime digests
79	MultiplePreDigests,
80	/// No valid Aura pre-runtime digest found
81	NoDigestFound,
82}
83
84impl core::fmt::Display for PreDigestLookupError {
85	fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
86		match self {
87			Self::MultiplePreDigests => write!(f, "Multiple AuRa pre-runtime digests"),
88			Self::NoDigestFound => write!(f, "No valid Aura pre-runtime digest found"),
89		}
90	}
91}
92
93impl core::error::Error for PreDigestLookupError {}
94
95impl core::fmt::Display for SealLookupError {
96	fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
97		match self {
98			Self::Unsealed => write!(f, "The digest is empty"),
99			Self::BadSeal => write!(f, "The last digest item is not a valid AuRa seal"),
100			Self::MultipleSeals => write!(f, "There are multiple AuRa seals"),
101		}
102	}
103}
104
105impl core::error::Error for SealLookupError {}
106
107/// Removes the AuRa seal from `digest`.
108///
109/// The seal must be the last digest item and the only AuRa seal in `digest`. Returns the removed
110/// digest item and the signature it contains.
111pub fn take_seal<Signature: Codec>(
112	digest: &mut Digest,
113) -> Result<(DigestItem, Signature), SealLookupError> {
114	let seal = digest.pop().ok_or(SealLookupError::Unsealed)?;
115	let signature =
116		CompatibleDigestItem::<Signature>::as_aura_seal(&seal).ok_or(SealLookupError::BadSeal)?;
117
118	if digest
119		.logs()
120		.iter()
121		.any(|d| matches!(d, DigestItem::Seal(id, _) if *id == AURA_ENGINE_ID))
122	{
123		return Err(SealLookupError::MultipleSeals);
124	}
125
126	Ok((seal, signature))
127}
128
129/// Returns the slot of the AuRa pre-runtime digest.
130///
131/// There must be exactly one AuRa pre-runtime digest in `digest` and it must decode to a [`Slot`].
132pub fn find_pre_digest(digest: &Digest) -> Result<Slot, PreDigestLookupError> {
133	let mut pre_digests = digest
134		.logs()
135		.iter()
136		.filter(|d| matches!(d, DigestItem::PreRuntime(id, _) if *id == AURA_ENGINE_ID));
137
138	let pre_digest = pre_digests.next().ok_or(PreDigestLookupError::NoDigestFound)?;
139
140	if pre_digests.next().is_some() {
141		return Err(PreDigestLookupError::MultiplePreDigests);
142	}
143
144	CompatibleDigestItem::<()>::as_aura_pre_digest(pre_digest)
145		.ok_or(PreDigestLookupError::NoDigestFound)
146}
147
148#[cfg(test)]
149mod tests {
150	use super::*;
151
152	type Signature = u64;
153
154	fn seal(sig: Signature) -> DigestItem {
155		CompatibleDigestItem::aura_seal(sig)
156	}
157
158	fn pre_digest(slot: u64) -> DigestItem {
159		CompatibleDigestItem::<Signature>::aura_pre_digest(slot.into())
160	}
161
162	fn digest(logs: Vec<DigestItem>) -> Digest {
163		Digest { logs }
164	}
165
166	#[test]
167	fn take_seal_works() {
168		let other = DigestItem::Other(vec![1]);
169		let mut d = digest(vec![pre_digest(1), other.clone(), seal(5)]);
170
171		assert_eq!(take_seal::<Signature>(&mut d), Ok((seal(5), 5)));
172		assert_eq!(d, digest(vec![pre_digest(1), other]));
173	}
174
175	#[test]
176	fn take_seal_rejects_invalid_seals() {
177		let trailing_bytes = DigestItem::Seal(AURA_ENGINE_ID, (5u64, 1u8).encode());
178		let other_engine = DigestItem::Seal(*b"babe", 5u64.encode());
179
180		for (logs, expected) in [
181			(vec![], SealLookupError::Unsealed),
182			(vec![pre_digest(1)], SealLookupError::BadSeal),
183			(vec![seal(5), pre_digest(1)], SealLookupError::BadSeal),
184			(vec![seal(4), pre_digest(1), seal(5)], SealLookupError::MultipleSeals),
185			(vec![pre_digest(1), trailing_bytes], SealLookupError::BadSeal),
186			(vec![pre_digest(1), other_engine], SealLookupError::BadSeal),
187		] {
188			assert_eq!(
189				take_seal::<Signature>(&mut digest(logs.clone())),
190				Err(expected),
191				"{logs:?}"
192			);
193		}
194	}
195
196	#[test]
197	fn find_pre_digest_works() {
198		let other_engine = DigestItem::PreRuntime(*b"babe", 2u64.encode());
199
200		assert_eq!(find_pre_digest(&digest(vec![other_engine, pre_digest(1)])), Ok(1.into()));
201	}
202
203	#[test]
204	fn find_pre_digest_rejects_invalid_pre_digests() {
205		let trailing_bytes = DigestItem::PreRuntime(AURA_ENGINE_ID, (1u64, 1u8).encode());
206
207		for (logs, expected) in [
208			(vec![], PreDigestLookupError::NoDigestFound),
209			(vec![trailing_bytes.clone()], PreDigestLookupError::NoDigestFound),
210			(vec![pre_digest(1), pre_digest(1)], PreDigestLookupError::MultiplePreDigests),
211			(vec![trailing_bytes, pre_digest(1)], PreDigestLookupError::MultiplePreDigests),
212		] {
213			assert_eq!(find_pre_digest(&digest(logs.clone())), Err(expected), "{logs:?}");
214		}
215	}
216}