soil_client/blockchain/
header_metadata.rs1use 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
18pub(crate) const LRU_CACHE_SIZE: u32 = 5_000;
20
21pub 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 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 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 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
92pub 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 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 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#[derive(Debug, Clone)]
138pub struct HashAndNumber<Block: BlockT> {
139 pub number: NumberFor<Block>,
141 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#[derive(Debug, Clone)]
191pub struct TreeRoute<Block: BlockT> {
192 route: Vec<HashAndNumber<Block>>,
193 pivot: usize,
194}
195
196impl<Block: BlockT> TreeRoute<Block> {
197 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 pub fn retracted(&self) -> &[HashAndNumber<Block>] {
214 &self.route[..self.pivot]
215 }
216
217 pub fn into_retracted(mut self) -> Vec<HashAndNumber<Block>> {
219 self.route.truncate(self.pivot);
220 self.route
221 }
222
223 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 pub fn enacted(&self) -> &[HashAndNumber<Block>] {
235 &self.route[self.pivot + 1..]
236 }
237
238 pub fn last(&self) -> Option<&HashAndNumber<Block>> {
240 self.route.last()
241 }
242}
243
244pub trait HeaderMetadata<Block: BlockT> {
246 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
261pub struct HeaderMetadataCache<Block: BlockT> {
263 cache: Mutex<LruMap<Block::Hash, CachedHeaderMetadata<Block>>>,
264}
265
266impl<Block: BlockT> HeaderMetadataCache<Block> {
267 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#[derive(Debug, Clone)]
295pub struct CachedHeaderMetadata<Block: BlockT> {
296 pub hash: Block::Hash,
298 pub number: NumberFor<Block>,
300 pub parent: Block::Hash,
302 pub state_root: Block::Hash,
304 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}