use tp_runtime::traits::{Block as BlockT, DigestItemFor, Header as HeaderT, NumberFor, HashFor};
use tp_runtime::Justification;
use serde::{Serialize, Deserialize};
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::Arc;
use std::any::Any;
use crate::Error;
use crate::import_queue::CacheKeyId;
#[derive(Debug, PartialEq, Eq)]
pub enum ImportResult {
Imported(ImportedAux),
AlreadyInChain,
KnownBad,
UnknownParent,
MissingState,
}
#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ImportedAux {
pub header_only: bool,
pub clear_justification_requests: bool,
pub needs_justification: bool,
pub bad_justification: bool,
pub is_new_best: bool,
}
impl ImportResult {
pub fn imported(is_new_best: bool) -> ImportResult {
let mut aux = ImportedAux::default();
aux.is_new_best = is_new_best;
ImportResult::Imported(aux)
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum BlockOrigin {
Genesis,
NetworkInitialSync,
NetworkBroadcast,
ConsensusBroadcast,
Own,
File,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum ForkChoiceStrategy {
LongestChain,
Custom(bool),
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct BlockCheckParams<Block: BlockT> {
pub hash: Block::Hash,
pub number: NumberFor<Block>,
pub parent_hash: Block::Hash,
pub allow_missing_state: bool,
pub import_existing: bool,
}
#[non_exhaustive]
pub struct BlockImportParams<Block: BlockT, Transaction> {
pub origin: BlockOrigin,
pub header: Block::Header,
pub justification: Option<Justification>,
pub post_digests: Vec<DigestItemFor<Block>>,
pub body: Option<Vec<Block::Extrinsic>>,
pub storage_changes: Option<
tp_state_machine::StorageChanges<Transaction, HashFor<Block>, NumberFor<Block>>
>,
pub finalized: bool,
pub intermediates: HashMap<Cow<'static, [u8]>, Box<dyn Any>>,
pub auxiliary: Vec<(Vec<u8>, Option<Vec<u8>>)>,
pub fork_choice: Option<ForkChoiceStrategy>,
pub allow_missing_state: bool,
pub import_existing: bool,
pub post_hash: Option<Block::Hash>,
}
impl<Block: BlockT, Transaction> BlockImportParams<Block, Transaction> {
pub fn new(
origin: BlockOrigin,
header: Block::Header,
) -> Self {
Self {
origin, header,
justification: None,
post_digests: Vec::new(),
body: None,
storage_changes: None,
finalized: false,
intermediates: HashMap::new(),
auxiliary: Vec::new(),
fork_choice: None,
allow_missing_state: false,
import_existing: false,
post_hash: None,
}
}
pub fn post_hash(&self) -> Block::Hash {
if let Some(hash) = self.post_hash {
hash
} else {
if self.post_digests.is_empty() {
self.header.hash()
} else {
let mut hdr = self.header.clone();
for digest_item in &self.post_digests {
hdr.digest_mut().push(digest_item.clone());
}
hdr.hash()
}
}
}
pub fn convert_transaction<Transaction2>(self) -> BlockImportParams<Block, Transaction2> {
BlockImportParams {
origin: self.origin,
header: self.header,
justification: self.justification,
post_digests: self.post_digests,
body: self.body,
storage_changes: None,
finalized: self.finalized,
auxiliary: self.auxiliary,
intermediates: self.intermediates,
allow_missing_state: self.allow_missing_state,
fork_choice: self.fork_choice,
import_existing: self.import_existing,
post_hash: self.post_hash,
}
}
pub fn take_intermediate<T: 'static>(&mut self, key: &[u8]) -> Result<Box<T>, Error> {
let (k, v) = self.intermediates.remove_entry(key).ok_or(Error::NoIntermediate)?;
match v.downcast::<T>() {
Ok(v) => Ok(v),
Err(v) => {
self.intermediates.insert(k, v);
Err(Error::InvalidIntermediate)
},
}
}
pub fn intermediate<T: 'static>(&self, key: &[u8]) -> Result<&T, Error> {
self.intermediates.get(key)
.ok_or(Error::NoIntermediate)?
.downcast_ref::<T>()
.ok_or(Error::InvalidIntermediate)
}
pub fn intermediate_mut<T: 'static>(&mut self, key: &[u8]) -> Result<&mut T, Error> {
self.intermediates.get_mut(key)
.ok_or(Error::NoIntermediate)?
.downcast_mut::<T>()
.ok_or(Error::InvalidIntermediate)
}
}
pub trait BlockImport<B: BlockT> {
type Error: std::error::Error + Send + 'static;
type Transaction;
fn check_block(
&mut self,
block: BlockCheckParams<B>,
) -> Result<ImportResult, Self::Error>;
fn import_block(
&mut self,
block: BlockImportParams<B, Self::Transaction>,
cache: HashMap<CacheKeyId, Vec<u8>>,
) -> Result<ImportResult, Self::Error>;
}
impl<B: BlockT, Transaction> BlockImport<B> for crate::import_queue::BoxBlockImport<B, Transaction> {
type Error = crate::error::Error;
type Transaction = Transaction;
fn check_block(
&mut self,
block: BlockCheckParams<B>,
) -> Result<ImportResult, Self::Error> {
(**self).check_block(block)
}
fn import_block(
&mut self,
block: BlockImportParams<B, Transaction>,
cache: HashMap<CacheKeyId, Vec<u8>>,
) -> Result<ImportResult, Self::Error> {
(**self).import_block(block, cache)
}
}
impl<B: BlockT, T, E: std::error::Error + Send + 'static, Transaction> BlockImport<B> for Arc<T>
where for<'r> &'r T: BlockImport<B, Error = E, Transaction = Transaction>
{
type Error = E;
type Transaction = Transaction;
fn check_block(
&mut self,
block: BlockCheckParams<B>,
) -> Result<ImportResult, Self::Error> {
(&**self).check_block(block)
}
fn import_block(
&mut self,
block: BlockImportParams<B, Transaction>,
cache: HashMap<CacheKeyId, Vec<u8>>,
) -> Result<ImportResult, Self::Error> {
(&**self).import_block(block, cache)
}
}
pub trait JustificationImport<B: BlockT> {
type Error: std::error::Error + Send + 'static;
fn on_start(&mut self) -> Vec<(B::Hash, NumberFor<B>)> { Vec::new() }
fn import_justification(
&mut self,
hash: B::Hash,
number: NumberFor<B>,
justification: Justification,
) -> Result<(), Self::Error>;
}