sp_blockchain/
header_metadata.rs1use 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
29pub(crate) const LRU_CACHE_SIZE: u32 = 5_000;
31
32pub 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 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 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 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
103pub 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 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 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#[derive(Debug, Clone)]
149pub struct HashAndNumber<Block: BlockT> {
150 pub number: NumberFor<Block>,
152 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#[derive(Debug, Clone)]
202pub struct TreeRoute<Block: BlockT> {
203 route: Vec<HashAndNumber<Block>>,
204 pivot: usize,
205}
206
207impl<Block: BlockT> TreeRoute<Block> {
208 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 pub fn retracted(&self) -> &[HashAndNumber<Block>] {
225 &self.route[..self.pivot]
226 }
227
228 pub fn into_retracted(mut self) -> Vec<HashAndNumber<Block>> {
230 self.route.truncate(self.pivot);
231 self.route
232 }
233
234 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 pub fn enacted(&self) -> &[HashAndNumber<Block>] {
246 &self.route[self.pivot + 1..]
247 }
248
249 pub fn last(&self) -> Option<&HashAndNumber<Block>> {
251 self.route.last()
252 }
253}
254
255pub trait HeaderMetadata<Block: BlockT> {
257 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
272pub struct HeaderMetadataCache<Block: BlockT> {
274 cache: Mutex<LruMap<Block::Hash, CachedHeaderMetadata<Block>>>,
275}
276
277impl<Block: BlockT> HeaderMetadataCache<Block> {
278 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#[derive(Debug, Clone)]
306pub struct CachedHeaderMetadata<Block: BlockT> {
307 pub hash: Block::Hash,
309 pub number: NumberFor<Block>,
311 pub parent: Block::Hash,
313 pub state_root: Block::Hash,
315 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}