use std::sync::Arc;
use std::collections::{HashMap, HashSet};
use tet_core::ChangesTrieConfigurationRange;
use tet_core::offchain::OffchainStorage;
use tp_runtime::{generic::BlockId, Justification, Storage};
use tp_runtime::traits::{Block as BlockT, NumberFor, HashFor};
use tp_state_machine::{
ChangesTrieState, ChangesTrieStorage as StateChangesTrieStorage, ChangesTrieTransaction,
StorageCollection, ChildStorageCollection, OffchainChangesCollection,
};
use tetcore_storage::{StorageData, StorageKey, PrefixedStorageKey, ChildInfo};
use crate::{
blockchain::{
Backend as BlockchainBackend, well_known_cache_keys
},
light::RemoteBlockchain,
UsageInfo,
};
use tp_blockchain;
use tp_consensus::BlockOrigin;
use parking_lot::RwLock;
pub use tp_state_machine::Backend as StateBackend;
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<tp_blockchain::TreeRoute<Block>>,
}
pub struct ClientImportOperation<Block: BlockT, B: Backend<Block>> {
pub op: B::BlockImportOperation,
pub notify_imported: Option<ImportSummary<Block>>,
pub notify_finalized: Vec<Block::Hash>,
}
pub fn apply_aux<'a, 'b: 'a, 'c: 'a, B, Block, D, I>(
operation: &mut ClientImportOperation<Block, B>,
insert: I,
delete: D,
) -> tp_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) -> tp_blockchain::Result<Option<&Self::State>>;
fn set_block_data(
&mut self,
header: Block::Header,
body: Option<Vec<Block::Extrinsic>>,
justification: Option<Justification>,
state: NewBlockState,
) -> tp_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>,
) -> tp_blockchain::Result<()>;
fn reset_storage(&mut self, storage: Storage) -> tp_blockchain::Result<Block::Hash>;
fn update_storage(
&mut self,
update: StorageCollection,
child_update: ChildStorageCollection,
) -> tp_blockchain::Result<()>;
fn update_offchain_storage(
&mut self,
_offchain_update: OffchainChangesCollection,
) -> tp_blockchain::Result<()> {
Ok(())
}
fn update_changes_trie(
&mut self,
update: ChangesTrieTransaction<HashFor<Block>, NumberFor<Block>>,
) -> tp_blockchain::Result<()>;
fn insert_aux<I>(&mut self, ops: I) -> tp_blockchain::Result<()>
where I: IntoIterator<Item=(Vec<u8>, Option<Vec<u8>>)>;
fn mark_finalized(
&mut self,
id: BlockId<Block>,
justification: Option<Justification>,
) -> tp_blockchain::Result<()>;
fn mark_head(&mut self, id: BlockId<Block>) -> tp_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<tp_blockchain::Error>;
}
pub trait Finalizer<Block: BlockT, B: Backend<Block>> {
fn apply_finality(
&self,
operation: &mut ClientImportOperation<Block, B>,
id: BlockId<Block>,
justification: Option<Justification>,
notify: bool,
) -> tp_blockchain::Result<()>;
fn finalize_block(
&self,
id: BlockId<Block>,
justification: Option<Justification>,
notify: bool,
) -> tp_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) -> tp_blockchain::Result<()>;
fn get_aux(&self, key: &[u8]) -> tp_blockchain::Result<Option<Vec<u8>>>;
}
pub struct KeyIterator<'a, State, Block> {
state: State,
prefix: Option<&'a StorageKey>,
current_key: Vec<u8>,
_phantom: PhantomData<Block>,
}
impl <'a, State, Block> KeyIterator<'a, State, Block> {
pub fn new(state: State, prefix: Option<&'a StorageKey>, current_key: Vec<u8>) -> Self {
Self {
state,
prefix,
current_key,
_phantom: PhantomData,
}
}
}
impl<'a, State, Block> Iterator for KeyIterator<'a, State, Block> where
Block: BlockT,
State: StateBackend<HashFor<Block>>,
{
type Item = StorageKey;
fn next(&mut self) -> Option<Self::Item> {
let next_key = self.state
.next_storage_key(&self.current_key)
.ok()
.flatten()?;
if let Some(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, id: &BlockId<Block>, key: &StorageKey) -> tp_blockchain::Result<Option<StorageData>>;
fn storage_keys(&self, id: &BlockId<Block>, key_prefix: &StorageKey) -> tp_blockchain::Result<Vec<StorageKey>>;
fn storage_hash(&self, id: &BlockId<Block>, key: &StorageKey) -> tp_blockchain::Result<Option<Block::Hash>>;
fn storage_pairs(
&self,
id: &BlockId<Block>,
key_prefix: &StorageKey
) -> tp_blockchain::Result<Vec<(StorageKey, StorageData)>>;
fn storage_keys_iter<'a>(
&self,
id: &BlockId<Block>,
prefix: Option<&'a StorageKey>,
start_key: Option<&StorageKey>
) -> tp_blockchain::Result<KeyIterator<'a, B::State, Block>>;
fn child_storage(
&self,
id: &BlockId<Block>,
child_info: &ChildInfo,
key: &StorageKey
) -> tp_blockchain::Result<Option<StorageData>>;
fn child_storage_keys(
&self,
id: &BlockId<Block>,
child_info: &ChildInfo,
key_prefix: &StorageKey
) -> tp_blockchain::Result<Vec<StorageKey>>;
fn child_storage_hash(
&self,
id: &BlockId<Block>,
child_info: &ChildInfo,
key: &StorageKey
) -> tp_blockchain::Result<Option<Block::Hash>>;
fn max_key_changes_range(
&self,
first: NumberFor<Block>,
last: BlockId<Block>,
) -> tp_blockchain::Result<Option<(NumberFor<Block>, BlockId<Block>)>>;
fn key_changes(
&self,
first: NumberFor<Block>,
last: BlockId<Block>,
storage_key: Option<&PrefixedStorageKey>,
key: &StorageKey
) -> tp_blockchain::Result<Vec<(NumberFor<Block>, u32)>>;
}
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;
type OffchainStorage: OffchainStorage;
fn begin_operation(&self) -> tp_blockchain::Result<Self::BlockImportOperation>;
fn begin_state_operation(
&self,
operation: &mut Self::BlockImportOperation,
block: BlockId<Block>,
) -> tp_blockchain::Result<()>;
fn commit_operation(
&self,
transaction: Self::BlockImportOperation,
) -> tp_blockchain::Result<()>;
fn finalize_block(
&self,
block: BlockId<Block>,
justification: Option<Justification>,
) -> tp_blockchain::Result<()>;
fn blockchain(&self) -> &Self::Blockchain;
fn usage_info(&self) -> Option<UsageInfo>;
fn changes_trie_storage(&self) -> Option<&dyn PrunableStateChangesTrieStorage<Block>>;
fn offchain_storage(&self) -> Option<Self::OffchainStorage>;
fn have_state_at(&self, hash: &Block::Hash, _number: NumberFor<Block>) -> bool {
self.state_at(BlockId::Hash(hash.clone())).is_ok()
}
fn state_at(&self, block: BlockId<Block>) -> tp_blockchain::Result<Self::State>;
fn revert(
&self,
n: NumberFor<Block>,
revert_finalized: bool,
) -> tp_blockchain::Result<(NumberFor<Block>, HashSet<Block::Hash>)>;
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) -> tp_blockchain::Result<()>
{
AuxStore::insert_aux(self, insert, delete)
}
fn get_aux(&self, key: &[u8]) -> tp_blockchain::Result<Option<Vec<u8>>> {
AuxStore::get_aux(self, key)
}
fn get_import_lock(&self) -> &RwLock<()>;
}
pub trait PrunableStateChangesTrieStorage<Block: BlockT>:
StateChangesTrieStorage<HashFor<Block>, NumberFor<Block>>
{
fn storage(&self) -> &dyn StateChangesTrieStorage<HashFor<Block>, NumberFor<Block>>;
fn configuration_at(&self, at: &BlockId<Block>) -> tp_blockchain::Result<
ChangesTrieConfigurationRange<NumberFor<Block>, Block::Hash>
>;
fn oldest_pruned_digest_range_end(&self) -> NumberFor<Block>;
}
pub trait LocalBackend<Block: BlockT>: Backend<Block> {}
pub trait RemoteBackend<Block: BlockT>: Backend<Block> {
fn is_local_state_available(&self, block: &BlockId<Block>) -> bool;
fn remote_blockchain(&self) -> Arc<dyn RemoteBlockchain<Block>>;
}
pub fn changes_tries_state_at_block<'a, Block: BlockT>(
block: &BlockId<Block>,
maybe_storage: Option<&'a dyn PrunableStateChangesTrieStorage<Block>>,
) -> tp_blockchain::Result<Option<ChangesTrieState<'a, HashFor<Block>, NumberFor<Block>>>> {
let storage = match maybe_storage {
Some(storage) => storage,
None => return Ok(None),
};
let config_range = storage.configuration_at(block)?;
match config_range.config {
Some(config) => Ok(Some(ChangesTrieState::new(config, config_range.zero.0, storage.storage()))),
None => Ok(None),
}
}
pub trait ProvideChtRoots<Block: BlockT> {
fn header_cht_root(
&self,
cht_size: NumberFor<Block>,
block: NumberFor<Block>,
) -> tp_blockchain::Result<Option<Block::Hash>>;
fn changes_trie_cht_root(
&self,
cht_size: NumberFor<Block>,
block: NumberFor<Block>,
) -> tp_blockchain::Result<Option<Block::Hash>>;
}