use crate::{
blockchain::{well_known_cache_keys, Backend as BlockchainBackend},
UsageInfo,
};
use parking_lot::RwLock;
use sp_blockchain;
use sp_consensus::BlockOrigin;
use sp_core::offchain::OffchainStorage;
use sp_runtime::{
traits::{Block as BlockT, HashFor, NumberFor},
Justification, Justifications, StateVersion, Storage,
};
use sp_state_machine::{
backend::AsTrieBackend, ChildStorageCollection, IndexOperation, OffchainChangesCollection,
StorageCollection,
};
use sp_storage::{ChildInfo, StorageData, StorageKey};
use std::collections::{HashMap, HashSet};
pub use sp_state_machine::{Backend as StateBackend, KeyValueStates};
use std::marker::PhantomData;
pub type StateBackendFor<B, Block> = <B as Backend<Block>>::State;
pub type TransactionForSB<B, Block> = <B as StateBackend<HashFor<Block>>>::Transaction;
pub type TransactionFor<B, Block> = TransactionForSB<StateBackendFor<B, Block>, Block>;
pub struct ImportSummary<Block: BlockT> {
pub hash: Block::Hash,
pub origin: BlockOrigin,
pub header: Block::Header,
pub is_new_best: bool,
pub storage_changes: Option<(StorageCollection, ChildStorageCollection)>,
pub tree_route: Option<sp_blockchain::TreeRoute<Block>>,
}
pub struct FinalizeSummary<Block: BlockT> {
pub header: Block::Header,
pub finalized: Vec<Block::Hash>,
pub stale_heads: Vec<Block::Hash>,
}
pub struct ClientImportOperation<Block: BlockT, B: Backend<Block>> {
pub op: B::BlockImportOperation,
pub notify_imported: Option<ImportSummary<Block>>,
pub notify_finalized: Option<FinalizeSummary<Block>>,
}
pub fn apply_aux<'a, 'b: 'a, 'c: 'a, B, Block, D, I>(
operation: &mut ClientImportOperation<Block, B>,
insert: I,
delete: D,
) -> sp_blockchain::Result<()>
where
Block: BlockT,
B: Backend<Block>,
I: IntoIterator<Item = &'a (&'c [u8], &'c [u8])>,
D: IntoIterator<Item = &'a &'b [u8]>,
{
operation.op.insert_aux(
insert
.into_iter()
.map(|(k, v)| (k.to_vec(), Some(v.to_vec())))
.chain(delete.into_iter().map(|k| (k.to_vec(), None))),
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NewBlockState {
Normal,
Best,
Final,
}
impl NewBlockState {
pub fn is_best(self) -> bool {
match self {
NewBlockState::Best | NewBlockState::Final => true,
NewBlockState::Normal => false,
}
}
pub fn is_final(self) -> bool {
match self {
NewBlockState::Final => true,
NewBlockState::Best | NewBlockState::Normal => false,
}
}
}
pub trait BlockImportOperation<Block: BlockT> {
type State: StateBackend<HashFor<Block>>;
fn state(&self) -> sp_blockchain::Result<Option<&Self::State>>;
fn set_block_data(
&mut self,
header: Block::Header,
body: Option<Vec<Block::Extrinsic>>,
indexed_body: Option<Vec<Vec<u8>>>,
justifications: Option<Justifications>,
state: NewBlockState,
) -> sp_blockchain::Result<()>;
fn update_cache(&mut self, cache: HashMap<well_known_cache_keys::Id, Vec<u8>>);
fn update_db_storage(
&mut self,
update: TransactionForSB<Self::State, Block>,
) -> sp_blockchain::Result<()>;
fn set_genesis_state(
&mut self,
storage: Storage,
commit: bool,
state_version: StateVersion,
) -> sp_blockchain::Result<Block::Hash>;
fn reset_storage(
&mut self,
storage: Storage,
state_version: StateVersion,
) -> sp_blockchain::Result<Block::Hash>;
fn update_storage(
&mut self,
update: StorageCollection,
child_update: ChildStorageCollection,
) -> sp_blockchain::Result<()>;
fn update_offchain_storage(
&mut self,
_offchain_update: OffchainChangesCollection,
) -> sp_blockchain::Result<()> {
Ok(())
}
fn insert_aux<I>(&mut self, ops: I) -> sp_blockchain::Result<()>
where
I: IntoIterator<Item = (Vec<u8>, Option<Vec<u8>>)>;
fn mark_finalized(
&mut self,
hash: Block::Hash,
justification: Option<Justification>,
) -> sp_blockchain::Result<()>;
fn mark_head(&mut self, hash: Block::Hash) -> sp_blockchain::Result<()>;
fn update_transaction_index(&mut self, index: Vec<IndexOperation>)
-> sp_blockchain::Result<()>;
}
pub trait LockImportRun<Block: BlockT, B: Backend<Block>> {
fn lock_import_and_run<R, Err, F>(&self, f: F) -> Result<R, Err>
where
F: FnOnce(&mut ClientImportOperation<Block, B>) -> Result<R, Err>,
Err: From<sp_blockchain::Error>;
}
pub trait Finalizer<Block: BlockT, B: Backend<Block>> {
fn apply_finality(
&self,
operation: &mut ClientImportOperation<Block, B>,
block: Block::Hash,
justification: Option<Justification>,
notify: bool,
) -> sp_blockchain::Result<()>;
fn finalize_block(
&self,
block: Block::Hash,
justification: Option<Justification>,
notify: bool,
) -> sp_blockchain::Result<()>;
}
pub trait AuxStore {
fn insert_aux<
'a,
'b: 'a,
'c: 'a,
I: IntoIterator<Item = &'a (&'c [u8], &'c [u8])>,
D: IntoIterator<Item = &'a &'b [u8]>,
>(
&self,
insert: I,
delete: D,
) -> sp_blockchain::Result<()>;
fn get_aux(&self, key: &[u8]) -> sp_blockchain::Result<Option<Vec<u8>>>;
}
pub struct KeyIterator<State, Block> {
state: State,
child_storage: Option<ChildInfo>,
prefix: Option<StorageKey>,
current_key: Vec<u8>,
_phantom: PhantomData<Block>,
}
impl<State, Block> KeyIterator<State, Block> {
pub fn new(state: State, prefix: Option<StorageKey>, current_key: Vec<u8>) -> Self {
Self { state, child_storage: None, prefix, current_key, _phantom: PhantomData }
}
pub fn new_child(
state: State,
child_info: ChildInfo,
prefix: Option<StorageKey>,
current_key: Vec<u8>,
) -> Self {
Self { state, child_storage: Some(child_info), prefix, current_key, _phantom: PhantomData }
}
}
impl<State, Block> Iterator for KeyIterator<State, Block>
where
Block: BlockT,
State: StateBackend<HashFor<Block>>,
{
type Item = StorageKey;
fn next(&mut self) -> Option<Self::Item> {
let next_key = if let Some(child_info) = self.child_storage.as_ref() {
self.state.next_child_storage_key(child_info, &self.current_key)
} else {
self.state.next_storage_key(&self.current_key)
}
.ok()
.flatten()?;
if let Some(ref prefix) = self.prefix {
if !next_key.starts_with(&prefix.0[..]) {
return None
}
}
self.current_key = next_key.clone();
Some(StorageKey(next_key))
}
}
pub trait StorageProvider<Block: BlockT, B: Backend<Block>> {
fn storage(
&self,
hash: Block::Hash,
key: &StorageKey,
) -> sp_blockchain::Result<Option<StorageData>>;
fn storage_keys(
&self,
hash: Block::Hash,
key_prefix: &StorageKey,
) -> sp_blockchain::Result<Vec<StorageKey>>;
fn storage_hash(
&self,
hash: Block::Hash,
key: &StorageKey,
) -> sp_blockchain::Result<Option<Block::Hash>>;
fn storage_pairs(
&self,
hash: Block::Hash,
key_prefix: &StorageKey,
) -> sp_blockchain::Result<Vec<(StorageKey, StorageData)>>;
fn storage_keys_iter(
&self,
hash: Block::Hash,
prefix: Option<&StorageKey>,
start_key: Option<&StorageKey>,
) -> sp_blockchain::Result<KeyIterator<B::State, Block>>;
fn child_storage(
&self,
hash: Block::Hash,
child_info: &ChildInfo,
key: &StorageKey,
) -> sp_blockchain::Result<Option<StorageData>>;
fn child_storage_keys(
&self,
hash: Block::Hash,
child_info: &ChildInfo,
key_prefix: &StorageKey,
) -> sp_blockchain::Result<Vec<StorageKey>>;
fn child_storage_keys_iter(
&self,
hash: Block::Hash,
child_info: ChildInfo,
prefix: Option<&StorageKey>,
start_key: Option<&StorageKey>,
) -> sp_blockchain::Result<KeyIterator<B::State, Block>>;
fn child_storage_hash(
&self,
hash: Block::Hash,
child_info: &ChildInfo,
key: &StorageKey,
) -> sp_blockchain::Result<Option<Block::Hash>>;
}
pub trait Backend<Block: BlockT>: AuxStore + Send + Sync {
type BlockImportOperation: BlockImportOperation<Block, State = Self::State>;
type Blockchain: BlockchainBackend<Block>;
type State: StateBackend<HashFor<Block>>
+ Send
+ AsTrieBackend<
HashFor<Block>,
TrieBackendStorage = <Self::State as StateBackend<HashFor<Block>>>::TrieBackendStorage,
>;
type OffchainStorage: OffchainStorage;
fn begin_operation(&self) -> sp_blockchain::Result<Self::BlockImportOperation>;
fn begin_state_operation(
&self,
operation: &mut Self::BlockImportOperation,
block: Block::Hash,
) -> sp_blockchain::Result<()>;
fn commit_operation(
&self,
transaction: Self::BlockImportOperation,
) -> sp_blockchain::Result<()>;
fn finalize_block(
&self,
hash: Block::Hash,
justification: Option<Justification>,
) -> sp_blockchain::Result<()>;
fn append_justification(
&self,
hash: Block::Hash,
justification: Justification,
) -> sp_blockchain::Result<()>;
fn blockchain(&self) -> &Self::Blockchain;
fn usage_info(&self) -> Option<UsageInfo>;
fn offchain_storage(&self) -> Option<Self::OffchainStorage>;
fn pin_block(&self, hash: Block::Hash) -> sp_blockchain::Result<()>;
fn unpin_block(&self, hash: Block::Hash);
fn have_state_at(&self, hash: Block::Hash, _number: NumberFor<Block>) -> bool {
self.state_at(hash).is_ok()
}
fn state_at(&self, hash: Block::Hash) -> sp_blockchain::Result<Self::State>;
fn revert(
&self,
n: NumberFor<Block>,
revert_finalized: bool,
) -> sp_blockchain::Result<(NumberFor<Block>, HashSet<Block::Hash>)>;
fn remove_leaf_block(&self, hash: Block::Hash) -> sp_blockchain::Result<()>;
fn insert_aux<
'a,
'b: 'a,
'c: 'a,
I: IntoIterator<Item = &'a (&'c [u8], &'c [u8])>,
D: IntoIterator<Item = &'a &'b [u8]>,
>(
&self,
insert: I,
delete: D,
) -> sp_blockchain::Result<()> {
AuxStore::insert_aux(self, insert, delete)
}
fn get_aux(&self, key: &[u8]) -> sp_blockchain::Result<Option<Vec<u8>>> {
AuxStore::get_aux(self, key)
}
fn get_import_lock(&self) -> &RwLock<()>;
fn requires_full_sync(&self) -> bool;
}
pub trait LocalBackend<Block: BlockT>: Backend<Block> {}