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
156/// A tree-route from one block to another in the chain.
157///
158/// All blocks prior to the pivot in the vector is the reverse-order unique ancestry
159/// of the first block, the block at the pivot index is the common ancestor,
160/// and all blocks after the pivot is the ancestry of the second block, in
161/// order.
162///
163/// The ancestry sets will include the given blocks, and thus the tree-route is
164/// never empty.
165///
166/// ```text
167/// Tree route from R1 to E2. Retracted is [R1, R2, R3], Common is C, enacted [E1, E2]
168///   <- R3 <- R2 <- R1
169///  /
170/// C
171///  \-> E1 -> E2
172/// ```
173///
174/// ```text
175/// Tree route from C to E2. Retracted empty. Common is C, enacted [E1, E2]
176/// C -> E1 -> E2
177/// ```
178#[derive(Debug, Clone)]
179pub struct TreeRoute<Block: BlockT> {
180	route: Vec<HashAndNumber<Block>>,
181	pivot: usize,
182}
183
184impl<Block: BlockT> TreeRoute<Block> {
185	/// Creates a new `TreeRoute`.
186	///
187	/// To preserve the structure safety invariants it is required that `pivot < route.len()`.
188	pub fn new(route: Vec<HashAndNumber<Block>>, pivot: usize) -> Result<Self, String> {
189		if pivot < route.len() {
190			Ok(TreeRoute { route, pivot })
191		} else {
192			Err(format!(
193				"TreeRoute pivot ({}) should be less than route length ({})",
194				pivot,
195				route.len()
196			))
197		}
198	}
199
200	/// Get a slice of all retracted blocks in reverse order (towards common ancestor).
201	pub fn retracted(&self) -> &[HashAndNumber<Block>] {
202		&self.route[..self.pivot]
203	}
204
205	/// Convert into all retracted blocks in reverse order (towards common ancestor).
206	pub fn into_retracted(mut self) -> Vec<HashAndNumber<Block>> {
207		self.route.truncate(self.pivot);
208		self.route
209	}
210
211	/// Get the common ancestor block. This might be one of the two blocks of the
212	/// route.
213	pub fn common_block(&self) -> &HashAndNumber<Block> {
214		self.route.get(self.pivot).expect(
215			"tree-routes are computed between blocks; \
216			which are included in the route; \
217			thus it is never empty; qed",
218		)
219	}
220
221	/// Get a slice of enacted blocks (descendants of the common ancestor)
222	pub fn enacted(&self) -> &[HashAndNumber<Block>] {
223		&self.route[self.pivot + 1..]
224	}
225
226	/// Returns the last block.
227	pub fn last(&self) -> Option<&HashAndNumber<Block>> {
228		self.route.last()
229	}
230}
231
232/// Handles header metadata: hash, number, parent hash, etc.
233pub trait HeaderMetadata<Block: BlockT> {
234	/// Error used in case the header metadata is not found.
235	type Error: std::error::Error;
236
237	fn header_metadata(
238		&self,
239		hash: Block::Hash,
240	) -> Result<CachedHeaderMetadata<Block>, Self::Error>;
241	fn insert_header_metadata(
242		&self,
243		hash: Block::Hash,
244		header_metadata: CachedHeaderMetadata<Block>,
245	);
246	fn remove_header_metadata(&self, hash: Block::Hash);
247}
248
249/// Caches header metadata in an in-memory LRU cache.
250pub struct HeaderMetadataCache<Block: BlockT> {
251	cache: Mutex<LruMap<Block::Hash, CachedHeaderMetadata<Block>>>,
252}
253
254impl<Block: BlockT> HeaderMetadataCache<Block> {
255	/// Creates a new LRU header metadata cache with `capacity`.
256	pub fn new(capacity: u32) -> Self {
257		HeaderMetadataCache { cache: Mutex::new(LruMap::new(ByLength::new(capacity))) }
258	}
259}
260
261impl<Block: BlockT> Default for HeaderMetadataCache<Block> {
262	fn default() -> Self {
263		Self::new(LRU_CACHE_SIZE)
264	}
265}
266
267impl<Block: BlockT> HeaderMetadataCache<Block> {
268	pub fn header_metadata(&self, hash: Block::Hash) -> Option<CachedHeaderMetadata<Block>> {
269		self.cache.lock().get(&hash).cloned()
270	}
271
272	pub fn insert_header_metadata(&self, hash: Block::Hash, metadata: CachedHeaderMetadata<Block>) {
273		self.cache.lock().insert(hash, metadata);
274	}
275
276	pub fn remove_header_metadata(&self, hash: Block::Hash) {
277		self.cache.lock().remove(&hash);
278	}
279}
280
281/// Cached header metadata. Used to efficiently traverse the tree.
282#[derive(Debug, Clone)]
283pub struct CachedHeaderMetadata<Block: BlockT> {
284	/// Hash of the header.
285	pub hash: Block::Hash,
286	/// Block number.
287	pub number: NumberFor<Block>,
288	/// Hash of parent header.
289	pub parent: Block::Hash,
290	/// Block state root.
291	pub state_root: Block::Hash,
292	/// Hash of an ancestor header. Used to jump through the tree.
293	ancestor: Block::Hash,
294}
295
296impl<Block: BlockT> From<&Block::Header> for CachedHeaderMetadata<Block> {
297	fn from(header: &Block::Header) -> Self {
298		CachedHeaderMetadata {
299			hash: header.hash(),
300			number: *header.number(),
301			parent: *header.parent_hash(),
302			state_root: *header.state_root(),
303			ancestor: *header.parent_hash(),
304		}
305	}
306}