1use std::collections::HashSet;
22
23use parking_lot::RwLock;
24
25use sp_api::CallContext;
26use sp_consensus::BlockOrigin;
27use sp_core::offchain::OffchainStorage;
28use sp_runtime::{
29 traits::{Block as BlockT, HashingFor, NumberFor},
30 Justification, Justifications, StateVersion, Storage,
31};
32use sp_state_machine::{
33 backend::AsTrieBackend, ChildStorageCollection, IndexOperation, IterArgs,
34 OffchainChangesCollection, StorageCollection, StorageIterator,
35};
36use sp_storage::{ChildInfo, StorageData, StorageKey};
37pub use sp_trie::MerkleValue;
38
39use crate::{blockchain::Backend as BlockchainBackend, UsageInfo};
40
41pub use sp_state_machine::{Backend as StateBackend, BackendTransaction, KeyValueStates};
42
43pub type StateBackendFor<B, Block> = <B as Backend<Block>>::State;
45
46#[derive(Debug, Clone, Copy)]
48pub enum ImportNotificationAction {
49 RecentBlock,
51 EveryBlock,
53 Both,
55 None,
57}
58
59pub struct ImportSummary<Block: BlockT> {
64 pub hash: Block::Hash,
66 pub origin: BlockOrigin,
68 pub header: Block::Header,
70 pub is_new_best: bool,
72 pub storage_changes: Option<(StorageCollection, ChildStorageCollection)>,
74 pub tree_route: Option<sp_blockchain::TreeRoute<Block>>,
78 pub import_notification_action: ImportNotificationAction,
80}
81
82#[derive(Clone, Debug)]
84pub struct StaleBlock<Block: BlockT> {
85 pub hash: Block::Hash,
87 pub is_head: bool,
89}
90
91pub struct FinalizeSummary<Block: BlockT> {
96 pub header: Block::Header,
98 pub finalized: Vec<Block::Hash>,
102 pub stale_blocks: Vec<StaleBlock<Block>>,
104}
105
106pub struct ClientImportOperation<Block: BlockT, B: Backend<Block>> {
108 pub op: B::BlockImportOperation,
110 pub notify_imported: Option<ImportSummary<Block>>,
112 pub notify_finalized: Option<FinalizeSummary<Block>>,
114}
115
116pub fn apply_aux<'a, 'b: 'a, 'c: 'a, B, Block, D, I>(
118 operation: &mut ClientImportOperation<Block, B>,
119 insert: I,
120 delete: D,
121) -> sp_blockchain::Result<()>
122where
123 Block: BlockT,
124 B: Backend<Block>,
125 I: IntoIterator<Item = &'a (&'c [u8], &'c [u8])>,
126 D: IntoIterator<Item = &'a &'b [u8]>,
127{
128 operation.op.insert_aux(
129 insert
130 .into_iter()
131 .map(|(k, v)| (k.to_vec(), Some(v.to_vec())))
132 .chain(delete.into_iter().map(|k| (k.to_vec(), None))),
133 )
134}
135
136#[derive(Debug, Clone, Copy, PartialEq, Eq)]
138pub enum NewBlockState {
139 Normal,
141 Best,
143 Final,
145}
146
147impl NewBlockState {
148 pub fn is_best(self) -> bool {
150 match self {
151 NewBlockState::Best | NewBlockState::Final => true,
152 NewBlockState::Normal => false,
153 }
154 }
155
156 pub fn is_final(self) -> bool {
158 match self {
159 NewBlockState::Final => true,
160 NewBlockState::Best | NewBlockState::Normal => false,
161 }
162 }
163}
164
165pub trait BlockImportOperation<Block: BlockT> {
169 type State: StateBackend<HashingFor<Block>>;
171
172 fn state(&self) -> sp_blockchain::Result<Option<&Self::State>>;
176
177 fn set_block_data(
189 &mut self,
190 header: Block::Header,
191 body: Option<Vec<Block::Extrinsic>>,
192 indexed_body: Option<Vec<Vec<u8>>>,
193 justifications: Option<Justifications>,
194 state: NewBlockState,
195 register_as_leaf: bool,
196 ) -> sp_blockchain::Result<()>;
197
198 fn update_db_storage(
200 &mut self,
201 update: BackendTransaction<HashingFor<Block>>,
202 ) -> sp_blockchain::Result<()>;
203
204 fn set_genesis_state(
207 &mut self,
208 storage: Storage,
209 commit: bool,
210 state_version: StateVersion,
211 ) -> sp_blockchain::Result<Block::Hash>;
212
213 fn reset_storage(
215 &mut self,
216 storage: Storage,
217 state_version: StateVersion,
218 ) -> sp_blockchain::Result<Block::Hash>;
219
220 fn update_storage(
222 &mut self,
223 update: StorageCollection,
224 child_update: ChildStorageCollection,
225 ) -> sp_blockchain::Result<()>;
226
227 fn update_offchain_storage(
229 &mut self,
230 _offchain_update: OffchainChangesCollection,
231 ) -> sp_blockchain::Result<()> {
232 Ok(())
233 }
234
235 fn insert_aux<I>(&mut self, ops: I) -> sp_blockchain::Result<()>
239 where
240 I: IntoIterator<Item = (Vec<u8>, Option<Vec<u8>>)>;
241
242 fn mark_finalized(
245 &mut self,
246 hash: Block::Hash,
247 justification: Option<Justification>,
248 ) -> sp_blockchain::Result<()>;
249
250 fn mark_head(&mut self, hash: Block::Hash) -> sp_blockchain::Result<()>;
253
254 fn update_transaction_index(&mut self, index: Vec<IndexOperation>)
256 -> sp_blockchain::Result<()>;
257
258 fn set_create_gap(&mut self, create_gap: bool);
260}
261
262pub trait LockImportRun<Block: BlockT, B: Backend<Block>> {
264 fn lock_import_and_run<R, Err, F>(&self, f: F) -> Result<R, Err>
266 where
267 F: FnOnce(&mut ClientImportOperation<Block, B>) -> Result<R, Err>,
268 Err: From<sp_blockchain::Error>;
269}
270
271pub trait Finalizer<Block: BlockT, B: Backend<Block>> {
273 fn apply_finality(
283 &self,
284 operation: &mut ClientImportOperation<Block, B>,
285 block: Block::Hash,
286 justification: Option<Justification>,
287 notify: bool,
288 ) -> sp_blockchain::Result<()>;
289
290 fn finalize_block(
304 &self,
305 block: Block::Hash,
306 justification: Option<Justification>,
307 notify: bool,
308 ) -> sp_blockchain::Result<()>;
309}
310
311pub trait AuxStore {
317 fn insert_aux<
321 'a,
322 'b: 'a,
323 'c: 'a,
324 I: IntoIterator<Item = &'a (&'c [u8], &'c [u8])>,
325 D: IntoIterator<Item = &'a &'b [u8]>,
326 >(
327 &self,
328 insert: I,
329 delete: D,
330 ) -> sp_blockchain::Result<()>;
331
332 fn get_aux(&self, key: &[u8]) -> sp_blockchain::Result<Option<Vec<u8>>>;
334}
335
336pub struct KeysIter<State, Block>
338where
339 State: StateBackend<HashingFor<Block>>,
340 Block: BlockT,
341{
342 inner: <State as StateBackend<HashingFor<Block>>>::RawIter,
343 state: State,
344}
345
346impl<State, Block> KeysIter<State, Block>
347where
348 State: StateBackend<HashingFor<Block>>,
349 Block: BlockT,
350{
351 pub fn new(
353 state: State,
354 prefix: Option<&StorageKey>,
355 start_at: Option<&StorageKey>,
356 ) -> Result<Self, State::Error> {
357 let mut args = IterArgs::default();
358 args.prefix = prefix.as_ref().map(|prefix| prefix.0.as_slice());
359 args.start_at = start_at.as_ref().map(|start_at| start_at.0.as_slice());
360 args.start_at_exclusive = true;
361
362 Ok(Self { inner: state.raw_iter(args)?, state })
363 }
364
365 pub fn new_child(
367 state: State,
368 child_info: ChildInfo,
369 prefix: Option<&StorageKey>,
370 start_at: Option<&StorageKey>,
371 ) -> Result<Self, State::Error> {
372 let mut args = IterArgs::default();
373 args.prefix = prefix.as_ref().map(|prefix| prefix.0.as_slice());
374 args.start_at = start_at.as_ref().map(|start_at| start_at.0.as_slice());
375 args.child_info = Some(child_info);
376 args.start_at_exclusive = true;
377
378 Ok(Self { inner: state.raw_iter(args)?, state })
379 }
380}
381
382impl<State, Block> Iterator for KeysIter<State, Block>
383where
384 Block: BlockT,
385 State: StateBackend<HashingFor<Block>>,
386{
387 type Item = StorageKey;
388
389 fn next(&mut self) -> Option<Self::Item> {
390 self.inner.next_key(&self.state)?.ok().map(StorageKey)
391 }
392}
393
394pub struct PairsIter<State, Block>
396where
397 State: StateBackend<HashingFor<Block>>,
398 Block: BlockT,
399{
400 inner: <State as StateBackend<HashingFor<Block>>>::RawIter,
401 state: State,
402}
403
404impl<State, Block> Iterator for PairsIter<State, Block>
405where
406 Block: BlockT,
407 State: StateBackend<HashingFor<Block>>,
408{
409 type Item = (StorageKey, StorageData);
410
411 fn next(&mut self) -> Option<Self::Item> {
412 self.inner
413 .next_pair(&self.state)?
414 .ok()
415 .map(|(key, value)| (StorageKey(key), StorageData(value)))
416 }
417}
418
419impl<State, Block> PairsIter<State, Block>
420where
421 State: StateBackend<HashingFor<Block>>,
422 Block: BlockT,
423{
424 pub fn new(
426 state: State,
427 prefix: Option<&StorageKey>,
428 start_at: Option<&StorageKey>,
429 ) -> Result<Self, State::Error> {
430 let mut args = IterArgs::default();
431 args.prefix = prefix.as_ref().map(|prefix| prefix.0.as_slice());
432 args.start_at = start_at.as_ref().map(|start_at| start_at.0.as_slice());
433 args.start_at_exclusive = true;
434
435 Ok(Self { inner: state.raw_iter(args)?, state })
436 }
437}
438
439pub trait StorageProvider<Block: BlockT, B: Backend<Block>> {
441 fn storage(
443 &self,
444 hash: Block::Hash,
445 key: &StorageKey,
446 ) -> sp_blockchain::Result<Option<StorageData>>;
447
448 fn storage_hash(
450 &self,
451 hash: Block::Hash,
452 key: &StorageKey,
453 ) -> sp_blockchain::Result<Option<Block::Hash>>;
454
455 fn storage_keys(
458 &self,
459 hash: Block::Hash,
460 prefix: Option<&StorageKey>,
461 start_key: Option<&StorageKey>,
462 ) -> sp_blockchain::Result<KeysIter<B::State, Block>>;
463
464 fn storage_pairs(
467 &self,
468 hash: <Block as BlockT>::Hash,
469 prefix: Option<&StorageKey>,
470 start_key: Option<&StorageKey>,
471 ) -> sp_blockchain::Result<PairsIter<B::State, Block>>;
472
473 fn child_storage(
476 &self,
477 hash: Block::Hash,
478 child_info: &ChildInfo,
479 key: &StorageKey,
480 ) -> sp_blockchain::Result<Option<StorageData>>;
481
482 fn child_storage_keys(
485 &self,
486 hash: Block::Hash,
487 child_info: ChildInfo,
488 prefix: Option<&StorageKey>,
489 start_key: Option<&StorageKey>,
490 ) -> sp_blockchain::Result<KeysIter<B::State, Block>>;
491
492 fn child_storage_hash(
495 &self,
496 hash: Block::Hash,
497 child_info: &ChildInfo,
498 key: &StorageKey,
499 ) -> sp_blockchain::Result<Option<Block::Hash>>;
500
501 fn closest_merkle_value(
503 &self,
504 hash: Block::Hash,
505 key: &StorageKey,
506 ) -> sp_blockchain::Result<Option<MerkleValue<Block::Hash>>>;
507
508 fn child_closest_merkle_value(
510 &self,
511 hash: Block::Hash,
512 child_info: &ChildInfo,
513 key: &StorageKey,
514 ) -> sp_blockchain::Result<Option<MerkleValue<Block::Hash>>>;
515}
516
517#[derive(Debug, Clone, Copy)]
521pub enum TrieCacheContext {
522 Trusted,
530 Untrusted,
534}
535
536impl From<CallContext> for TrieCacheContext {
537 fn from(call_context: CallContext) -> Self {
538 match call_context {
539 CallContext::Onchain => TrieCacheContext::Trusted,
540 CallContext::Offchain => TrieCacheContext::Untrusted,
541 }
542 }
543}
544
545pub trait Backend<Block: BlockT>: AuxStore + Send + Sync {
568 type BlockImportOperation: BlockImportOperation<Block, State = Self::State>;
570 type Blockchain: BlockchainBackend<Block>;
572 type State: StateBackend<HashingFor<Block>>
574 + Send
575 + AsTrieBackend<
576 HashingFor<Block>,
577 TrieBackendStorage = <Self::State as StateBackend<HashingFor<Block>>>::TrieBackendStorage,
578 >;
579 type OffchainStorage: OffchainStorage;
581
582 fn begin_operation(&self) -> sp_blockchain::Result<Self::BlockImportOperation>;
586
587 fn begin_state_operation(
589 &self,
590 operation: &mut Self::BlockImportOperation,
591 block: Block::Hash,
592 ) -> sp_blockchain::Result<()>;
593
594 fn commit_operation(
596 &self,
597 transaction: Self::BlockImportOperation,
598 ) -> sp_blockchain::Result<()>;
599
600 fn finalize_block(
604 &self,
605 hash: Block::Hash,
606 justification: Option<Justification>,
607 ) -> sp_blockchain::Result<()>;
608
609 fn append_justification(
613 &self,
614 hash: Block::Hash,
615 justification: Justification,
616 ) -> sp_blockchain::Result<()>;
617
618 fn blockchain(&self) -> &Self::Blockchain;
620
621 fn usage_info(&self) -> Option<UsageInfo>;
623
624 fn offchain_storage(&self) -> Option<Self::OffchainStorage>;
626
627 fn pin_block(&self, hash: Block::Hash) -> sp_blockchain::Result<()>;
631
632 fn unpin_block(&self, hash: Block::Hash);
634
635 fn have_state_at(&self, hash: Block::Hash, _number: NumberFor<Block>) -> bool {
637 self.state_at(hash, TrieCacheContext::Untrusted).is_ok()
638 }
639
640 fn state_at(
642 &self,
643 hash: Block::Hash,
644 trie_cache_context: TrieCacheContext,
645 ) -> sp_blockchain::Result<Self::State>;
646
647 fn revert(
655 &self,
656 n: NumberFor<Block>,
657 revert_finalized: bool,
658 ) -> sp_blockchain::Result<(NumberFor<Block>, HashSet<Block::Hash>)>;
659
660 fn remove_leaf_block(&self, hash: Block::Hash) -> sp_blockchain::Result<()>;
662
663 fn insert_aux<
665 'a,
666 'b: 'a,
667 'c: 'a,
668 I: IntoIterator<Item = &'a (&'c [u8], &'c [u8])>,
669 D: IntoIterator<Item = &'a &'b [u8]>,
670 >(
671 &self,
672 insert: I,
673 delete: D,
674 ) -> sp_blockchain::Result<()> {
675 AuxStore::insert_aux(self, insert, delete)
676 }
677 fn get_aux(&self, key: &[u8]) -> sp_blockchain::Result<Option<Vec<u8>>> {
679 AuxStore::get_aux(self, key)
680 }
681
682 fn get_import_lock(&self) -> &RwLock<()>;
689
690 fn requires_full_sync(&self) -> bool;
692}
693
694pub trait LocalBackend<Block: BlockT>: Backend<Block> {}