1use serde::{Deserialize, Serialize};
22use sp_runtime::{
23 traits::{Block as BlockT, HashingFor, Header as HeaderT, NumberFor},
24 DigestItem, Justification, Justifications,
25};
26use std::{any::Any, borrow::Cow, collections::HashMap, sync::Arc};
27
28use sc_client_api::PrefetchedIndexedTransactions;
29use sp_consensus::{BlockOrigin, Error};
30
31#[derive(Debug, PartialEq, Eq)]
33pub enum ImportResult {
34 Imported(ImportedAux),
36 AlreadyInChain,
38 KnownBad,
40 UnknownParent,
42 MissingState,
44}
45
46#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
48pub struct ImportedAux {
49 pub header_only: bool,
51 pub clear_justification_requests: bool,
53 pub needs_justification: bool,
55 pub bad_justification: bool,
57 pub is_new_best: bool,
59}
60
61impl ImportResult {
62 pub fn imported(is_new_best: bool) -> ImportResult {
66 let aux = ImportedAux { is_new_best, ..Default::default() };
67
68 ImportResult::Imported(aux)
69 }
70
71 pub fn handle_justification<B>(
74 &self,
75 hash: &B::Hash,
76 number: NumberFor<B>,
77 justification_sync_link: &dyn JustificationSyncLink<B>,
78 ) where
79 B: BlockT,
80 {
81 match self {
82 ImportResult::Imported(aux) => {
83 if aux.clear_justification_requests {
84 justification_sync_link.clear_justification_requests();
85 }
86
87 if aux.needs_justification {
88 justification_sync_link.request_justification(hash, number);
89 }
90 },
91 _ => {},
92 }
93 }
94}
95
96#[derive(Debug, PartialEq, Eq, Clone, Copy)]
98pub enum ForkChoiceStrategy {
99 LongestChain,
101 Custom(bool),
103}
104
105#[derive(Debug, PartialEq, Eq, Clone)]
107pub struct BlockCheckParams<Block: BlockT> {
108 pub hash: Block::Hash,
110 pub number: NumberFor<Block>,
112 pub parent_hash: Block::Hash,
114 pub allow_missing_state: bool,
116 pub allow_missing_parent: bool,
118 pub import_existing: bool,
120}
121
122pub enum StorageChanges<Block: BlockT> {
124 Changes(sp_state_machine::StorageChanges<HashingFor<Block>>),
126 Import(ImportedState<Block>),
128}
129
130#[derive(PartialEq, Eq, Clone)]
132pub struct ImportedState<B: BlockT> {
133 pub block: B::Hash,
135 pub state: sp_state_machine::KeyValueStates,
137}
138
139impl<B: BlockT> std::fmt::Debug for ImportedState<B> {
140 fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
141 fmt.debug_struct("ImportedState").field("block", &self.block).finish()
142 }
143}
144
145pub enum StateAction<Block: BlockT> {
147 ApplyChanges(StorageChanges<Block>),
149 Execute,
151 ExecuteIfPossible,
153 Skip,
155}
156
157impl<Block: BlockT> std::fmt::Debug for StateAction<Block> {
158 fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
159 match self {
160 Self::ApplyChanges(_) => fmt.write_str("ApplyChanges(..)"),
161 Self::Execute => fmt.write_str("Execute"),
162 Self::ExecuteIfPossible => fmt.write_str("ExecuteIfPossible"),
163 Self::Skip => fmt.write_str("Skip"),
164 }
165 }
166}
167
168impl<Block: BlockT> StateAction<Block> {
169 pub fn skip_execution_checks(&self) -> bool {
171 match self {
172 StateAction::ApplyChanges(_) |
173 StateAction::Execute |
174 StateAction::ExecuteIfPossible => false,
175 StateAction::Skip => true,
176 }
177 }
178
179 pub fn as_storage_changes(
181 &self,
182 ) -> Option<&sp_state_machine::StorageChanges<HashingFor<Block>>> {
183 match self {
184 StateAction::ApplyChanges(StorageChanges::Changes(changes)) => Some(&changes),
185 _ => None,
186 }
187 }
188}
189
190impl<Block: BlockT> From<StorageChanges<Block>> for StateAction<Block> {
191 fn from(value: StorageChanges<Block>) -> Self {
192 Self::ApplyChanges(value)
193 }
194}
195
196impl<Block: BlockT> From<sp_state_machine::StorageChanges<HashingFor<Block>>>
197 for StateAction<Block>
198{
199 fn from(value: sp_state_machine::StorageChanges<HashingFor<Block>>) -> Self {
200 Self::ApplyChanges(StorageChanges::Changes(value))
201 }
202}
203
204#[non_exhaustive]
206pub struct BlockImportParams<Block: BlockT> {
207 pub origin: BlockOrigin,
209 pub header: Block::Header,
221 pub justifications: Option<Justifications>,
223 pub post_digests: Vec<DigestItem>,
226 pub body: Option<Vec<Block::Extrinsic>>,
228 pub state_action: StateAction<Block>,
230 pub finalized: bool,
233 pub intermediates: HashMap<Cow<'static, [u8]>, Box<dyn Any + Send>>,
237 pub auxiliary: Vec<(Vec<u8>, Option<Vec<u8>>)>,
242 pub fork_choice: Option<ForkChoiceStrategy>,
249 pub import_existing: bool,
251 pub create_gap: bool,
253 pub post_hash: Option<Block::Hash>,
255 pub prefetched_indexed_transactions: PrefetchedIndexedTransactions,
258}
259
260impl<Block: BlockT> BlockImportParams<Block> {
261 pub fn new(origin: BlockOrigin, header: Block::Header) -> Self {
263 Self {
264 origin,
265 header,
266 justifications: None,
267 post_digests: Vec::new(),
268 body: None,
269 state_action: if origin == BlockOrigin::WarpSync {
271 StateAction::Skip
272 } else {
273 StateAction::Execute
274 },
275 finalized: false,
276 intermediates: HashMap::new(),
277 auxiliary: Vec::new(),
278 fork_choice: None,
279 import_existing: false,
280 create_gap: origin != BlockOrigin::WarpSync,
287 post_hash: None,
288 prefetched_indexed_transactions: PrefetchedIndexedTransactions::default(),
289 }
290 }
291
292 pub fn post_hash(&self) -> Block::Hash {
294 if let Some(hash) = self.post_hash {
295 hash
296 } else {
297 self.post_header().hash()
298 }
299 }
300
301 pub fn post_header(&self) -> Block::Header {
303 if self.post_digests.is_empty() {
304 self.header.clone()
305 } else {
306 let mut hdr = self.header.clone();
307 for digest_item in &self.post_digests {
308 hdr.digest_mut().push(digest_item.clone());
309 }
310
311 hdr
312 }
313 }
314
315 pub fn insert_intermediate<T: 'static + Send>(&mut self, key: &'static [u8], value: T) {
317 self.intermediates.insert(Cow::from(key), Box::new(value));
318 }
319
320 pub fn remove_intermediate<T: 'static>(&mut self, key: &[u8]) -> Result<T, Error> {
322 let (k, v) = self.intermediates.remove_entry(key).ok_or(Error::NoIntermediate)?;
323
324 v.downcast::<T>().map(|v| *v).map_err(|v| {
325 self.intermediates.insert(k, v);
326 Error::InvalidIntermediate
327 })
328 }
329
330 pub fn get_intermediate<T: 'static>(&self, key: &[u8]) -> Result<&T, Error> {
332 self.intermediates
333 .get(key)
334 .ok_or(Error::NoIntermediate)?
335 .downcast_ref::<T>()
336 .ok_or(Error::InvalidIntermediate)
337 }
338
339 pub fn get_intermediate_mut<T: 'static>(&mut self, key: &[u8]) -> Result<&mut T, Error> {
341 self.intermediates
342 .get_mut(key)
343 .ok_or(Error::NoIntermediate)?
344 .downcast_mut::<T>()
345 .ok_or(Error::InvalidIntermediate)
346 }
347
348 pub fn with_state(&self) -> bool {
350 matches!(self.state_action, StateAction::ApplyChanges(StorageChanges::Import(_)))
351 }
352}
353
354#[async_trait::async_trait]
356pub trait BlockImport<B: BlockT> {
357 type Error: std::error::Error + Send + 'static;
359
360 async fn check_block(&self, block: BlockCheckParams<B>) -> Result<ImportResult, Self::Error>;
362
363 async fn import_block(&self, block: BlockImportParams<B>) -> Result<ImportResult, Self::Error>;
365}
366
367#[async_trait::async_trait]
368impl<B: BlockT> BlockImport<B> for crate::import_queue::BoxBlockImport<B> {
369 type Error = sp_consensus::error::Error;
370
371 async fn check_block(&self, block: BlockCheckParams<B>) -> Result<ImportResult, Self::Error> {
373 (**self).check_block(block).await
374 }
375
376 async fn import_block(&self, block: BlockImportParams<B>) -> Result<ImportResult, Self::Error> {
378 (**self).import_block(block).await
379 }
380}
381
382#[async_trait::async_trait]
383impl<B: BlockT, T, E: std::error::Error + Send + 'static> BlockImport<B> for Arc<T>
384where
385 for<'r> &'r T: BlockImport<B, Error = E>,
386 T: Send + Sync,
387{
388 type Error = E;
389
390 async fn check_block(&self, block: BlockCheckParams<B>) -> Result<ImportResult, Self::Error> {
391 (&**self).check_block(block).await
392 }
393
394 async fn import_block(&self, block: BlockImportParams<B>) -> Result<ImportResult, Self::Error> {
395 (&**self).import_block(block).await
396 }
397}
398
399#[async_trait::async_trait]
401pub trait JustificationImport<B: BlockT> {
402 type Error: std::error::Error + Send + 'static;
403
404 async fn on_start(&mut self) -> Vec<(B::Hash, NumberFor<B>)>;
407
408 async fn import_justification(
410 &mut self,
411 hash: B::Hash,
412 number: NumberFor<B>,
413 justification: Justification,
414 ) -> Result<(), Self::Error>;
415}
416
417pub trait JustificationSyncLink<B: BlockT>: Send + Sync {
423 fn request_justification(&self, hash: &B::Hash, number: NumberFor<B>);
425
426 fn clear_justification_requests(&self);
428}
429
430impl<B: BlockT> JustificationSyncLink<B> for () {
431 fn request_justification(&self, _hash: &B::Hash, _number: NumberFor<B>) {}
432
433 fn clear_justification_requests(&self) {}
434}
435
436impl<B: BlockT, L: JustificationSyncLink<B>> JustificationSyncLink<B> for Arc<L> {
437 fn request_justification(&self, hash: &B::Hash, number: NumberFor<B>) {
438 L::request_justification(self, hash, number);
439 }
440
441 fn clear_justification_requests(&self) {
442 L::clear_justification_requests(self);
443 }
444}