sp_blockchain/
header_metadata.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//! Implements tree backend, cached header metadata and algorithms
19//! to compute routes efficiently over the tree of headers.
20
21use parking_lot::Mutex;
22use schnellru::{ByLength, LruMap};
23use sp_core::U256;
24use sp_runtime::{
25	traits::{Block as BlockT, Header, NumberFor, One},
26	Saturating,
27};
28
29/// Set to the expected max difference between `best` and `finalized` blocks at sync.
30pub(crate) const LRU_CACHE_SIZE: u32 = 5_000;
31
32/// Get the lowest common ancestor between two blocks in the tree.
33///
34/// This implementation is efficient because our trees have very few and
35/// small branches, and because of our current query pattern:
36/// lca(best, final), lca(best + 1, final), lca(best + 2, final), etc.
37/// The first call is O(h) but the others are O(1).
38pub fn lowest_common_ancestor<Block: BlockT, T: HeaderMetadata<Block> + ?Sized>(
39	backend: &T,
40	id_one: Block::Hash,
41	id_two: Block::Hash,
42) -> Result<HashAndNumber<Block>, T::Error> {
43	let mut header_one = backend.header_metadata(id_one)?;
44	if header_one.parent == id_two {
45		return Ok(HashAndNumber { hash: id_two, number: header_one.number - One::one() })
46	}
47
48	let mut header_two = backend.header_metadata(id_two)?;
49	if header_two.parent == id_one {
50		return Ok(HashAndNumber { hash: id_one, number: header_one.number })
51	}
52
53	let mut orig_header_one = header_one.clone();
54	let mut orig_header_two = header_two.clone();
55
56	// We move through ancestor links as much as possible, since ancestor >= parent.
57
58	while header_one.number > header_two.number {
59		let ancestor_one = backend.header_metadata(header_one.ancestor)?;
60
61		if ancestor_one.number >= header_two.number {
62			header_one = ancestor_one;
63		} else {
64			break
65		}
66	}
67
68	while header_one.number < header_two.number {
69		let ancestor_two = backend.header_metadata(header_two.ancestor)?;
70
71		if ancestor_two.number >= header_one.number {
72			header_two = ancestor_two;
73		} else {
74			break
75		}
76	}
77
78	// Then we move the remaining path using parent links.
79
80	while header_one.hash != header_two.hash {
81		if header_one.number > header_two.number {
82			header_one = backend.header_metadata(header_one.parent)?;
83		} else {
84			header_two = backend.header_metadata(header_two.parent)?;
85		}
86	}
87
88	// Update cached ancestor links.
89
90	if orig_header_one.number > header_one.number {
91		orig_header_one.ancestor = header_one.hash;
92		backend.insert_header_metadata(orig_header_one.hash, orig_header_one);
93	}
94
95	if orig_header_two.number > header_one.number {
96		orig_header_two.ancestor = header_one.hash;
97		backend.insert_header_metadata(orig_header_two.hash, orig_header_two);
98	}
99
100	Ok(HashAndNumber { hash: header_one.hash, number: header_one.number })
101}
102
103/// Compute a tree-route between two blocks. See tree-route docs for more details.
104pub fn tree_route<Block: BlockT, T: HeaderMetadata<Block> + ?Sized>(
105	backend: &T,
106	from: Block::Hash,
107	to: Block::Hash,
108) -> Result<TreeRoute<Block>, T::Error> {
109	let mut from = backend.header_metadata(from)?;
110	let mut to = backend.header_metadata(to)?;
111
112	let mut to_branch =
113		Vec::with_capacity(Into::<U256>::into(to.number.saturating_sub(from.number)).as_usize());
114	while to.number > from.number {
115		to_branch.push(HashAndNumber { number: to.number, hash: to.hash });
116
117		to = backend.header_metadata(to.parent)?;
118	}
119
120	let mut from_branch =
121		Vec::with_capacity(Into::<U256>::into(to.number.saturating_sub(from.number)).as_usize());
122	while from.number > to.number {
123		from_branch.push(HashAndNumber { number: from.number, hash: from.hash });
124		from = backend.header_metadata(from.parent)?;
125	}
126
127	// numbers are equal now. walk backwards until the block is the same
128
129	while to.hash != from.hash {
130		to_branch.push(HashAndNumber { number: to.number, hash: to.hash });
131		to = backend.header_metadata(to.parent)?;
132
133		from_branch.push(HashAndNumber { number: from.number, hash: from.hash });
134		from = backend.header_metadata(from.parent)?;
135	}
136
137	// add the pivot block. and append the reversed to-branch
138	// (note that it's reverse order originals)
139	let pivot = from_branch.len();
140	from_branch.reserve_exact(to_branch.len() + 1);
141	from_branch.push(HashAndNumber { number: to.number, hash: to.hash });
142	from_branch.extend(to_branch.into_iter().rev());
143
144	Ok(TreeRoute { route: from_branch, pivot })
145}
146
147/// Hash and number of a block.
148#[derive(Debug, Clone)]
149pub struct HashAndNumber<Block: BlockT> {
150	/// The number of the block.
151	pub number: NumberFor<Block>,
152	/// The hash of the block.
153	pub hash: Block::Hash,
154}
155
156impl<Block: BlockT> Eq for HashAndNumber<Block> {}
157
158impl<Block: BlockT> PartialEq for HashAndNumber<Block> {
159	fn eq(&self, other: &Self) -> bool {
160		self.number.eq(&other.number) && self.hash.eq(&other.hash)
161	}
162}
163
164impl<Block: BlockT> Ord for HashAndNumber<Block> {
165	fn cmp(&self, other: &Self) -> std::cmp::Ordering {
166		match self.number.cmp(&other.number) {
167			std::cmp::Ordering::Equal => self.hash.cmp(&other.hash),
168			result => result,
169		}
170	}
171}
172
173impl<Block: BlockT> PartialOrd for HashAndNumber<Block> {
174	fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
175		Some(self.cmp(&other))
176	}
177}
178
179/// A tree-route from one block to another in the chain.
180///
181/// All blocks prior to the pivot in the vector is the reverse-order unique ancestry
182/// of the first block, the block at the pivot index is the common ancestor,
183/// and all blocks after the pivot is the ancestry of the second block, in
184/// order.
185///
186/// The ancestry sets will include the given blocks, and thus the tree-route is
187/// never empty.
188///
189/// ```text
190/// Tree route from R1 to E2. Retracted is [R1, R2, R3], Common is C, enacted [E1, E2]
191///   <- R3 <- R2 <- R1
192///  /
193/// C
194///  \-> E1 -> E2
195/// ```
196///
197/// ```text
198/// Tree route from C to E2. Retracted empty. Common is C, enacted [E1, E2]
199/// C -> E1 -> E2
200/// ```
201#[derive(Debug, Clone)]
202pub struct TreeRoute<Block: BlockT> {
203	route: Vec<HashAndNumber<Block>>,
204	pivot: usize,
205}
206
207impl<Block: BlockT> TreeRoute<Block> {
208	/// Creates a new `TreeRoute`.
209	///
210	/// To preserve the structure safety invariants it is required that `pivot < route.len()`.
211	pub fn new(route: Vec<HashAndNumber<Block>>, pivot: usize) -> Result<Self, String> {
212		if pivot < route.len() {
213			Ok(TreeRoute { route, pivot })
214		} else {
215			Err(format!(
216				"TreeRoute pivot ({}) should be less than route length ({})",
217				pivot,
218				route.len()
219			))
220		}
221	}
222
223	/// Get a slice of all retracted blocks in reverse order (towards common ancestor).
224	pub fn retracted(&self) -> &[HashAndNumber<Block>] {
225		&self.route[..self.pivot]
226	}
227
228	/// Convert into all retracted blocks in reverse order (towards common ancestor).
229	pub fn into_retracted(mut self) -> Vec<HashAndNumber<Block>> {
230		self.route.truncate(self.pivot);
231		self.route
232	}
233
234	/// Get the common ancestor block. This might be one of the two blocks of the
235	/// route.
236	pub fn common_block(&self) -> &HashAndNumber<Block> {
237		self.route.get(self.pivot).expect(
238			"tree-routes are computed between blocks; \
239			which are included in the route; \
240			thus it is never empty; qed",
241		)
242	}
243
244	/// Get a slice of enacted blocks (descendants of the common ancestor)
245	pub fn enacted(&self) -> &[HashAndNumber<Block>] {
246		&self.route[self.pivot + 1..]
247	}
248
249	/// Returns the last block.
250	pub fn last(&self) -> Option<&HashAndNumber<Block>> {
251		self.route.last()
252	}
253}
254
255/// Handles header metadata: hash, number, parent hash, etc.
256pub trait HeaderMetadata<Block: BlockT> {
257	/// Error used in case the header metadata is not found.
258	type Error: std::error::Error;
259
260	fn header_metadata(
261		&self,
262		hash: Block::Hash,
263	) -> Result<CachedHeaderMetadata<Block>, Self::Error>;
264	fn insert_header_metadata(
265		&self,
266		hash: Block::Hash,
267		header_metadata: CachedHeaderMetadata<Block>,
268	);
269	fn remove_header_metadata(&self, hash: Block::Hash);
270}
271
272/// Caches header metadata in an in-memory LRU cache.
273pub struct HeaderMetadataCache<Block: BlockT> {
274	cache: Mutex<LruMap<Block::Hash, CachedHeaderMetadata<Block>>>,
275}
276
277impl<Block: BlockT> HeaderMetadataCache<Block> {
278	/// Creates a new LRU header metadata cache with `capacity`.
279	pub fn new(capacity: u32) -> Self {
280		HeaderMetadataCache { cache: Mutex::new(LruMap::new(ByLength::new(capacity))) }
281	}
282}
283
284impl<Block: BlockT> Default for HeaderMetadataCache<Block> {
285	fn default() -> Self {
286		Self::new(LRU_CACHE_SIZE)
287	}
288}
289
290impl<Block: BlockT> HeaderMetadataCache<Block> {
291	pub fn header_metadata(&self, hash: Block::Hash) -> Option<CachedHeaderMetadata<Block>> {
292		self.cache.lock().get(&hash).cloned()
293	}
294
295	pub fn insert_header_metadata(&self, hash: Block::Hash, metadata: CachedHeaderMetadata<Block>) {
296		self.cache.lock().insert(hash, metadata);
297	}
298
299	pub fn remove_header_metadata(&self, hash: Block::Hash) {
300		self.cache.lock().remove(&hash);
301	}
302}
303
304/// Cached header metadata. Used to efficiently traverse the tree.
305#[derive(Debug, Clone)]
306pub struct CachedHeaderMetadata<Block: BlockT> {
307	/// Hash of the header.
308	pub hash: Block::Hash,
309	/// Block number.
310	pub number: NumberFor<Block>,
311	/// Hash of parent header.
312	pub parent: Block::Hash,
313	/// Block state root.
314	pub state_root: Block::Hash,
315	/// Hash of an ancestor header. Used to jump through the tree.
316	ancestor: Block::Hash,
317}
318
319impl<Block: BlockT> From<&Block::Header> for CachedHeaderMetadata<Block> {
320	fn from(header: &Block::Header) -> Self {
321		CachedHeaderMetadata {
322			hash: header.hash(),
323			number: *header.number(),
324			parent: *header.parent_hash(),
325			state_root: *header.state_root(),
326			ancestor: *header.parent_hash(),
327		}
328	}
329}