1#[cfg(feature = "std")]
21use crate::trie_backend::TrieBackend;
22use crate::{
23 trie_backend_essence::TrieBackendStorage, ChildStorageCollection, DeltaKeyOp,
24 StorageCollection, StorageKey, StorageValue, UsageInfo,
25};
26use alloc::{collections::BTreeMap, vec::Vec};
27use codec::Encode;
28use core::marker::PhantomData;
29use hash_db::Hasher;
30use sp_core::storage::{ChildInfo, StateVersion, TrackedStorageKey};
31#[cfg(feature = "std")]
32use sp_core::traits::RuntimeCode;
33use sp_trie::{
34 DetachedTrieDBMut, InvalidSnapshot, LayoutV0, LayoutV1, MerkleValue, PrefixedMemoryDB,
35 RandomState, TrieDBMutSnapshot,
36};
37
38#[derive(Default)]
40#[non_exhaustive]
41pub struct IterArgs<'a> {
42 pub prefix: Option<&'a [u8]>,
44
45 pub start_at: Option<&'a [u8]>,
49
50 pub start_at_exclusive: bool,
53
54 pub child_info: Option<ChildInfo>,
56
57 pub stop_on_incomplete_database: bool,
63}
64
65pub trait StorageIterator<H>
67where
68 H: Hasher,
69{
70 type Backend;
72
73 type Error;
75
76 fn next_key(
78 &mut self,
79 backend: &Self::Backend,
80 ) -> Option<core::result::Result<StorageKey, Self::Error>>;
81
82 fn next_pair(
84 &mut self,
85 backend: &Self::Backend,
86 ) -> Option<core::result::Result<(StorageKey, StorageValue), Self::Error>>;
87
88 fn was_complete(&self) -> bool;
90}
91
92pub struct PairsIter<'a, H, I>
94where
95 H: Hasher,
96 I: StorageIterator<H>,
97{
98 backend: Option<&'a I::Backend>,
99 raw_iter: I,
100 _phantom: PhantomData<H>,
101}
102
103impl<'a, H, I> Iterator for PairsIter<'a, H, I>
104where
105 H: Hasher,
106 I: StorageIterator<H>,
107{
108 type Item = Result<(Vec<u8>, Vec<u8>), <I as StorageIterator<H>>::Error>;
109 fn next(&mut self) -> Option<Self::Item> {
110 self.raw_iter.next_pair(self.backend.as_ref()?)
111 }
112}
113
114impl<'a, H, I> Default for PairsIter<'a, H, I>
115where
116 H: Hasher,
117 I: StorageIterator<H> + Default,
118{
119 fn default() -> Self {
120 Self {
121 backend: Default::default(),
122 raw_iter: Default::default(),
123 _phantom: Default::default(),
124 }
125 }
126}
127
128impl<'a, H, I> PairsIter<'a, H, I>
129where
130 H: Hasher,
131 I: StorageIterator<H> + Default,
132{
133 #[cfg(feature = "std")]
134 pub(crate) fn was_complete(&self) -> bool {
135 self.raw_iter.was_complete()
136 }
137}
138
139pub struct KeysIter<'a, H, I>
141where
142 H: Hasher,
143 I: StorageIterator<H>,
144{
145 backend: Option<&'a I::Backend>,
146 raw_iter: I,
147 _phantom: PhantomData<H>,
148}
149
150impl<'a, H, I> Iterator for KeysIter<'a, H, I>
151where
152 H: Hasher,
153 I: StorageIterator<H>,
154{
155 type Item = Result<Vec<u8>, <I as StorageIterator<H>>::Error>;
156 fn next(&mut self) -> Option<Self::Item> {
157 self.raw_iter.next_key(self.backend.as_ref()?)
158 }
159}
160
161impl<'a, H, I> Default for KeysIter<'a, H, I>
162where
163 H: Hasher,
164 I: StorageIterator<H> + Default,
165{
166 fn default() -> Self {
167 Self {
168 backend: Default::default(),
169 raw_iter: Default::default(),
170 _phantom: Default::default(),
171 }
172 }
173}
174
175pub type BackendTransaction<H> = PrefixedMemoryDB<H>;
180
181pub enum EstimationTrie<H: Hasher> {
183 V0(DetachedTrieDBMut<LayoutV0<H>>),
185 V1(DetachedTrieDBMut<LayoutV1<H>>),
187}
188
189pub enum EstimationTrieSnapshot<H: Hasher> {
191 V0(TrieDBMutSnapshot<LayoutV0<H>>),
193 V1(TrieDBMutSnapshot<LayoutV1<H>>),
195}
196
197impl<H: Hasher> EstimationTrie<H> {
198 pub fn new(state_version: StateVersion, root: H::Out) -> Self {
200 match state_version {
201 StateVersion::V0 => Self::V0(DetachedTrieDBMut::new(root)),
202 StateVersion::V1 => Self::V1(DetachedTrieDBMut::new(root)),
203 }
204 }
205
206 pub fn snapshot(&mut self) -> EstimationTrieSnapshot<H> {
208 match self {
209 Self::V0(trie) => EstimationTrieSnapshot::V0(trie.snapshot()),
210 Self::V1(trie) => EstimationTrieSnapshot::V1(trie.snapshot()),
211 }
212 }
213
214 pub fn rollback_to(
218 &mut self,
219 snapshot: &EstimationTrieSnapshot<H>,
220 ) -> Result<(), InvalidSnapshot> {
221 match (self, snapshot) {
222 (Self::V0(trie), EstimationTrieSnapshot::V0(snapshot)) => trie.rollback_to(snapshot),
223 (Self::V1(trie), EstimationTrieSnapshot::V1(snapshot)) => trie.rollback_to(snapshot),
224 _ => unreachable!(
225 "a snapshot is taken from the trie it is rolled back to, and a trie keeps its \
226 layout for its whole life; qed"
227 ),
228 }
229 }
230
231 pub fn discard_from(
235 &mut self,
236 snapshot: &EstimationTrieSnapshot<H>,
237 ) -> Result<(), InvalidSnapshot> {
238 match (self, snapshot) {
239 (Self::V0(trie), EstimationTrieSnapshot::V0(snapshot)) => trie.discard_from(snapshot),
240 (Self::V1(trie), EstimationTrieSnapshot::V1(snapshot)) => trie.discard_from(snapshot),
241 _ => unreachable!(
242 "a snapshot is taken from the trie it is discarded from, and a trie keeps its \
243 layout for its whole life; qed"
244 ),
245 }
246 }
247}
248
249pub trait Backend<H: Hasher>: core::fmt::Debug {
254 type Error: super::Error;
256
257 type TrieBackendStorage: TrieBackendStorage<H>;
259
260 type RawIter: StorageIterator<H, Backend = Self, Error = Self::Error>;
262
263 fn storage(&self, key: &[u8]) -> Result<Option<StorageValue>, Self::Error>;
265
266 fn storage_hash(&self, key: &[u8]) -> Result<Option<H::Out>, Self::Error>;
268
269 fn closest_merkle_value(&self, key: &[u8]) -> Result<Option<MerkleValue<H::Out>>, Self::Error>;
271
272 fn child_closest_merkle_value(
274 &self,
275 child_info: &ChildInfo,
276 key: &[u8],
277 ) -> Result<Option<MerkleValue<H::Out>>, Self::Error>;
278
279 fn child_storage(
281 &self,
282 child_info: &ChildInfo,
283 key: &[u8],
284 ) -> Result<Option<StorageValue>, Self::Error>;
285
286 fn child_storage_hash(
288 &self,
289 child_info: &ChildInfo,
290 key: &[u8],
291 ) -> Result<Option<H::Out>, Self::Error>;
292
293 fn exists_storage(&self, key: &[u8]) -> Result<bool, Self::Error> {
295 Ok(self.storage_hash(key)?.is_some())
296 }
297
298 fn exists_child_storage(
300 &self,
301 child_info: &ChildInfo,
302 key: &[u8],
303 ) -> Result<bool, Self::Error> {
304 Ok(self.child_storage_hash(child_info, key)?.is_some())
305 }
306
307 fn next_storage_key(&self, key: &[u8]) -> Result<Option<StorageKey>, Self::Error>;
309
310 fn next_child_storage_key(
312 &self,
313 child_info: &ChildInfo,
314 key: &[u8],
315 ) -> Result<Option<StorageKey>, Self::Error>;
316
317 fn storage_root<'a>(
321 &self,
322 delta: impl Iterator<Item = (&'a [u8], Option<&'a [u8]>)>,
323 state_version: StateVersion,
324 ) -> (H::Out, BackendTransaction<H>)
325 where
326 H::Out: Ord;
327
328 fn child_storage_root<'a>(
332 &self,
333 child_info: &ChildInfo,
334 delta: impl Iterator<Item = (&'a [u8], Option<&'a [u8]>)>,
335 state_version: StateVersion,
336 ) -> (H::Out, bool, BackendTransaction<H>)
337 where
338 H::Out: Ord;
339
340 fn record_proof_for_dirty_keys<'a>(
345 &self,
346 delta: impl Iterator<Item = (&'a [u8], DeltaKeyOp)>,
347 estimation_trie: &mut Option<EstimationTrie<H>>,
348 state_version: StateVersion,
349 ) where
350 H::Out: Ord;
351
352 fn record_proof_for_child_dirty_keys<'a>(
354 &self,
355 child_info: &ChildInfo,
356 delta: impl Iterator<Item = (&'a [u8], DeltaKeyOp)>,
357 estimation_trie: &mut Option<EstimationTrie<H>>,
358 state_version: StateVersion,
359 ) where
360 H::Out: Ord;
361
362 fn raw_iter(&self, args: IterArgs) -> Result<Self::RawIter, Self::Error>;
364
365 fn pairs<'a>(&'a self, args: IterArgs) -> Result<PairsIter<'a, H, Self::RawIter>, Self::Error> {
367 Ok(PairsIter {
368 backend: Some(self),
369 raw_iter: self.raw_iter(args)?,
370 _phantom: Default::default(),
371 })
372 }
373
374 fn keys<'a>(&'a self, args: IterArgs) -> Result<KeysIter<'a, H, Self::RawIter>, Self::Error> {
376 Ok(KeysIter {
377 backend: Some(self),
378 raw_iter: self.raw_iter(args)?,
379 _phantom: Default::default(),
380 })
381 }
382
383 fn full_storage_root<'a>(
387 &self,
388 delta: impl Iterator<Item = (&'a [u8], Option<&'a [u8]>)>,
389 child_deltas: impl Iterator<
390 Item = (&'a ChildInfo, impl Iterator<Item = (&'a [u8], Option<&'a [u8]>)>),
391 >,
392 state_version: StateVersion,
393 ) -> (H::Out, BackendTransaction<H>)
394 where
395 H::Out: Ord + Encode,
396 {
397 let (root, txs, _) =
398 self.full_storage_root_with_child_roots(delta, child_deltas, state_version);
399 (root, txs)
400 }
401
402 fn full_storage_root_with_child_roots<'a>(
405 &self,
406 delta: impl Iterator<Item = (&'a [u8], Option<&'a [u8]>)>,
407 child_deltas: impl Iterator<
408 Item = (&'a ChildInfo, impl Iterator<Item = (&'a [u8], Option<&'a [u8]>)>),
409 >,
410 state_version: StateVersion,
411 ) -> (H::Out, BackendTransaction<H>, BTreeMap<StorageKey, H::Out>)
412 where
413 H::Out: Ord + Encode,
414 {
415 let mut txs = BackendTransaction::with_hasher(RandomState::default());
416 let mut child_roots: Vec<_> = Default::default();
417 let mut child_roots_by_storage_key = BTreeMap::new();
418 for (child_info, child_delta) in child_deltas {
420 let (child_root, empty, child_txs) =
421 self.child_storage_root(child_info, child_delta, state_version);
422 let prefixed_storage_key = child_info.prefixed_storage_key();
423 txs.consolidate(child_txs);
424 if empty {
425 child_roots.push((prefixed_storage_key.into_inner(), None));
426 } else {
427 child_roots.push((prefixed_storage_key.into_inner(), Some(child_root.encode())));
428 }
429 child_roots_by_storage_key.insert(child_info.storage_key().to_vec(), child_root);
430 }
431 let (root, parent_txs) = self.storage_root(
432 delta
433 .map(|(k, v)| (k, v.as_ref().map(|v| &v[..])))
434 .chain(child_roots.iter().map(|(k, v)| (&k[..], v.as_ref().map(|v| &v[..])))),
435 state_version,
436 );
437 txs.consolidate(parent_txs);
438
439 (root, txs, child_roots_by_storage_key)
440 }
441
442 fn register_overlay_stats(&self, _stats: &crate::stats::StateMachineStats);
446
447 fn usage_info(&self) -> UsageInfo;
452
453 fn wipe(&self) -> Result<(), Self::Error> {
455 unimplemented!()
456 }
457
458 fn commit(
460 &self,
461 _: H::Out,
462 _: BackendTransaction<H>,
463 _: StorageCollection,
464 _: ChildStorageCollection,
465 ) -> Result<(), Self::Error> {
466 unimplemented!()
467 }
468
469 fn read_write_count(&self) -> (u32, u32, u32, u32) {
471 unimplemented!()
472 }
473
474 fn reset_read_write_count(&self) {
476 unimplemented!()
477 }
478
479 fn get_whitelist(&self) -> Vec<TrackedStorageKey> {
481 Default::default()
482 }
483
484 fn set_whitelist(&self, _: Vec<TrackedStorageKey>) {}
486
487 fn proof_size(&self) -> Option<u32> {
489 unimplemented!()
490 }
491
492 fn get_read_and_written_keys(&self) -> Vec<(Vec<u8>, u32, u32, bool)> {
494 unimplemented!()
495 }
496}
497
498#[cfg(feature = "std")]
500pub trait AsTrieBackend<H: Hasher, C = sp_trie::cache::LocalTrieCache<H>> {
501 type TrieBackendStorage: TrieBackendStorage<H>;
503
504 fn as_trie_backend(&self) -> &TrieBackend<Self::TrieBackendStorage, H, C>;
506}
507
508#[cfg(feature = "std")]
514pub enum TryPendingCode {
515 No,
517 Yes,
519}
520
521#[cfg(feature = "std")]
522impl From<sp_core::traits::CallContext> for TryPendingCode {
523 fn from(context: sp_core::traits::CallContext) -> Self {
524 match context {
525 sp_core::traits::CallContext::Onchain { .. } => TryPendingCode::Yes,
526 sp_core::traits::CallContext::Offchain => TryPendingCode::No,
527 }
528 }
529}
530
531#[cfg(feature = "std")]
533pub struct BackendRuntimeCode<'a, B, H> {
534 backend: &'a B,
535 try_pending_code: TryPendingCode,
536 _marker: PhantomData<H>,
537}
538
539#[cfg(feature = "std")]
540impl<'a, B: Backend<H>, H: Hasher> sp_core::traits::FetchRuntimeCode
541 for BackendRuntimeCode<'a, B, H>
542{
543 fn fetch_runtime_code(&self) -> Option<std::borrow::Cow<'_, [u8]>> {
544 if matches!(self.try_pending_code, TryPendingCode::Yes) {
545 let pending_code = self
546 .backend
547 .storage(sp_core::storage::well_known_keys::PENDING_CODE)
548 .ok()
549 .flatten()
550 .map(Into::into);
551
552 if pending_code.is_some() {
553 return pending_code;
554 }
555 }
556 self.backend
557 .storage(sp_core::storage::well_known_keys::CODE)
558 .ok()
559 .flatten()
560 .map(Into::into)
561 }
562}
563
564#[cfg(feature = "std")]
565impl<'a, B: Backend<H>, H: Hasher> BackendRuntimeCode<'a, B, H>
566where
567 H::Out: Encode,
568{
569 pub fn new(backend: &'a B, try_pending_code: TryPendingCode) -> Self {
571 Self { backend, try_pending_code, _marker: PhantomData }
572 }
573
574 pub fn runtime_code(&self) -> Result<RuntimeCode<'_>, &'static str> {
578 let maybe_pending_code_hash = match self.try_pending_code {
579 TryPendingCode::No => None,
580 TryPendingCode::Yes => self
581 .backend
582 .storage_hash(sp_core::storage::well_known_keys::PENDING_CODE)
583 .ok()
584 .flatten(),
585 };
586 let hash = if let Some(pending_code_hash) = maybe_pending_code_hash {
587 pending_code_hash.encode()
588 } else {
589 self.backend
590 .storage_hash(sp_core::storage::well_known_keys::CODE)
591 .ok()
592 .flatten()
593 .ok_or("`:code` hash not found")?
594 .encode()
595 };
596 let heap_pages = self
597 .backend
598 .storage(sp_core::storage::well_known_keys::HEAP_PAGES)
599 .ok()
600 .flatten()
601 .and_then(|d| codec::Decode::decode(&mut &d[..]).ok());
602
603 Ok(RuntimeCode { code_fetcher: self, hash, heap_pages })
604 }
605}