1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
use std::sync::Arc;
use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor};
use sp_runtime::generic::BlockId;
use sp_runtime::Justification;
use log::warn;
use parking_lot::RwLock;
use crate::header_metadata::HeaderMetadata;
use crate::error::{Error, Result};
pub trait HeaderBackend<Block: BlockT>: Send + Sync {
fn header(&self, id: BlockId<Block>) -> Result<Option<Block::Header>>;
fn info(&self) -> Info<Block>;
fn status(&self, id: BlockId<Block>) -> Result<BlockStatus>;
fn number(&self, hash: Block::Hash) -> Result<Option<<<Block as BlockT>::Header as HeaderT>::Number>>;
fn hash(&self, number: NumberFor<Block>) -> Result<Option<Block::Hash>>;
fn block_hash_from_id(&self, id: &BlockId<Block>) -> Result<Option<Block::Hash>> {
match *id {
BlockId::Hash(h) => Ok(Some(h)),
BlockId::Number(n) => self.hash(n),
}
}
fn block_number_from_id(&self, id: &BlockId<Block>) -> Result<Option<NumberFor<Block>>> {
match *id {
BlockId::Hash(_) => Ok(self.header(*id)?.map(|h| h.number().clone())),
BlockId::Number(n) => Ok(Some(n)),
}
}
fn expect_header(&self, id: BlockId<Block>) -> Result<Block::Header> {
self.header(id)?.ok_or_else(|| Error::UnknownBlock(format!("Expect header: {}", id)))
}
fn expect_block_number_from_id(&self, id: &BlockId<Block>) -> Result<NumberFor<Block>> {
self.block_number_from_id(id)
.and_then(|n| n.ok_or_else(||
Error::UnknownBlock(format!("Expect block number from id: {}", id))
))
}
fn expect_block_hash_from_id(&self, id: &BlockId<Block>) -> Result<Block::Hash> {
self.block_hash_from_id(id)
.and_then(|n| n.ok_or_else(||
Error::UnknownBlock(format!("Expect block hash from id: {}", id))
))
}
}
pub trait Backend<Block: BlockT>: HeaderBackend<Block> + HeaderMetadata<Block, Error=Error> {
fn body(&self, id: BlockId<Block>) -> Result<Option<Vec<<Block as BlockT>::Extrinsic>>>;
fn justification(&self, id: BlockId<Block>) -> Result<Option<Justification>>;
fn last_finalized(&self) -> Result<Block::Hash>;
fn cache(&self) -> Option<Arc<dyn Cache<Block>>>;
fn leaves(&self) -> Result<Vec<Block::Hash>>;
fn children(&self, parent_hash: Block::Hash) -> Result<Vec<Block::Hash>>;
fn best_containing(
&self,
target_hash: Block::Hash,
maybe_max_number: Option<NumberFor<Block>>,
import_lock: &RwLock<()>,
) -> Result<Option<Block::Hash>> {
let target_header = {
match self.header(BlockId::Hash(target_hash))? {
Some(x) => x,
None => { return Ok(None); },
}
};
if let Some(max_number) = maybe_max_number {
if target_header.number() > &max_number {
return Ok(None);
}
}
let leaves = {
let _import_guard = import_lock.read();
let info = self.info();
let maybe_canon_hash = self.hash(*target_header.number())?;
if maybe_canon_hash.as_ref() == Some(&target_hash) {
if let Some(max_number) = maybe_max_number {
if let Some(header) = self.hash(max_number)? {
return Ok(Some(header));
}
}
} else if info.finalized_number >= *target_header.number() {
return Ok(None);
}
self.leaves()?
};
for leaf_hash in leaves {
let mut current_hash = leaf_hash;
let mut best_hash = leaf_hash;
if let Some(max_number) = maybe_max_number {
loop {
let current_header = self.header(BlockId::Hash(current_hash.clone()))?
.ok_or_else(|| Error::from(format!("failed to get header for hash {}", current_hash)))?;
if current_header.number() <= &max_number {
best_hash = current_header.hash();
break;
}
current_hash = *current_header.parent_hash();
}
}
loop {
if current_hash == target_hash {
return Ok(Some(best_hash));
}
let current_header = self.header(BlockId::Hash(current_hash.clone()))?
.ok_or_else(|| Error::from(format!("failed to get header for hash {}", current_hash)))?;
if current_header.number() < target_header.number() {
break;
}
current_hash = *current_header.parent_hash();
}
}
warn!(
"Block {:?} exists in chain but not found when following all \
leaves backwards. Number limit = {:?}",
target_hash,
maybe_max_number,
);
Ok(None)
}
}
pub trait ProvideCache<Block: BlockT> {
fn cache(&self) -> Option<Arc<dyn Cache<Block>>>;
}
pub trait Cache<Block: BlockT>: Send + Sync {
fn initialize(&self, key: &well_known_cache_keys::Id, value_at_genesis: Vec<u8>) -> Result<()>;
fn get_at(
&self,
key: &well_known_cache_keys::Id,
block: &BlockId<Block>,
) -> Result<Option<((NumberFor<Block>, Block::Hash), Option<(NumberFor<Block>, Block::Hash)>, Vec<u8>)>>;
}
#[derive(Debug, Eq, PartialEq)]
pub struct Info<Block: BlockT> {
pub best_hash: Block::Hash,
pub best_number: <<Block as BlockT>::Header as HeaderT>::Number,
pub genesis_hash: Block::Hash,
pub finalized_hash: Block::Hash,
pub finalized_number: <<Block as BlockT>::Header as HeaderT>::Number,
pub number_leaves: usize
}
#[derive(Debug, PartialEq, Eq)]
pub enum BlockStatus {
InChain,
Unknown,
}
pub mod well_known_cache_keys {
pub type Id = sp_consensus::import_queue::CacheKeyId;
pub const AUTHORITIES: Id = *b"auth";
pub const EPOCH: Id = *b"epch";
pub const CHANGES_TRIE_CONFIG: Id = *b"chtr";
}