Skip to main content

soil_client/blockchain/
header_metadata.rs

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