1use tetsy_hash_db::Hasher;
21use codec::{Decode, Encode};
22use tet_core::{
23 storage::{ChildInfo, well_known_keys, TrackedStorageKey}
24};
25use crate::{
26 trie_backend::TrieBackend,
27 trie_backend_essence::TrieBackendStorage,
28 UsageInfo, StorageKey, StorageValue, StorageCollection, ChildStorageCollection,
29};
30use tetcore_std::vec::Vec;
31#[cfg(feature = "std")]
32use tet_core::traits::RuntimeCode;
33
34pub trait Backend<H: Hasher>: tetcore_std::fmt::Debug {
39 type Error: super::Error;
41
42 type Transaction: Consolidate + Default + Send;
44
45 type TrieBackendStorage: TrieBackendStorage<H>;
47
48 fn storage(&self, key: &[u8]) -> Result<Option<StorageValue>, Self::Error>;
50
51 fn storage_hash(&self, key: &[u8]) -> Result<Option<H::Out>, Self::Error> {
53 self.storage(key).map(|v| v.map(|v| H::hash(&v)))
54 }
55
56 fn child_storage(
58 &self,
59 child_info: &ChildInfo,
60 key: &[u8],
61 ) -> Result<Option<StorageValue>, Self::Error>;
62
63 fn child_storage_hash(
65 &self,
66 child_info: &ChildInfo,
67 key: &[u8],
68 ) -> Result<Option<H::Out>, Self::Error> {
69 self.child_storage(child_info, key).map(|v| v.map(|v| H::hash(&v)))
70 }
71
72 fn exists_storage(&self, key: &[u8]) -> Result<bool, Self::Error> {
74 Ok(self.storage(key)?.is_some())
75 }
76
77 fn exists_child_storage(
79 &self,
80 child_info: &ChildInfo,
81 key: &[u8],
82 ) -> Result<bool, Self::Error> {
83 Ok(self.child_storage(child_info, key)?.is_some())
84 }
85
86 fn next_storage_key(&self, key: &[u8]) -> Result<Option<StorageKey>, Self::Error>;
88
89 fn next_child_storage_key(
91 &self,
92 child_info: &ChildInfo,
93 key: &[u8]
94 ) -> Result<Option<StorageKey>, Self::Error>;
95
96 fn apply_to_child_keys_while<F: FnMut(&[u8]) -> bool>(
99 &self,
100 child_info: &ChildInfo,
101 f: F,
102 );
103
104 fn for_keys_with_prefix<F: FnMut(&[u8])>(&self, prefix: &[u8], mut f: F) {
107 self.for_key_values_with_prefix(prefix, |k, _v| f(k))
108 }
109
110 fn for_key_values_with_prefix<F: FnMut(&[u8], &[u8])>(&self, prefix: &[u8], f: F);
113
114
115 fn for_child_keys_with_prefix<F: FnMut(&[u8])>(
118 &self,
119 child_info: &ChildInfo,
120 prefix: &[u8],
121 f: F,
122 );
123
124 fn storage_root<'a>(
128 &self,
129 delta: impl Iterator<Item=(&'a [u8], Option<&'a [u8]>)>,
130 ) -> (H::Out, Self::Transaction) where H::Out: Ord;
131
132 fn child_storage_root<'a>(
136 &self,
137 child_info: &ChildInfo,
138 delta: impl Iterator<Item=(&'a [u8], Option<&'a [u8]>)>,
139 ) -> (H::Out, bool, Self::Transaction) where H::Out: Ord;
140
141 fn pairs(&self) -> Vec<(StorageKey, StorageValue)>;
143
144 fn keys(&self, prefix: &[u8]) -> Vec<StorageKey> {
146 let mut all = Vec::new();
147 self.for_keys_with_prefix(prefix, |k| all.push(k.to_vec()));
148 all
149 }
150
151 fn child_keys(
153 &self,
154 child_info: &ChildInfo,
155 prefix: &[u8],
156 ) -> Vec<StorageKey> {
157 let mut all = Vec::new();
158 self.for_child_keys_with_prefix(child_info, prefix, |k| all.push(k.to_vec()));
159 all
160 }
161
162 fn as_trie_backend(&mut self) -> Option<&TrieBackend<Self::TrieBackendStorage, H>> {
164 None
165 }
166
167 fn full_storage_root<'a>(
171 &self,
172 delta: impl Iterator<Item=(&'a [u8], Option<&'a [u8]>)>,
173 child_deltas: impl Iterator<Item = (
174 &'a ChildInfo,
175 impl Iterator<Item=(&'a [u8], Option<&'a [u8]>)>,
176 )>,
177 ) -> (H::Out, Self::Transaction) where H::Out: Ord + Encode {
178 let mut txs: Self::Transaction = Default::default();
179 let mut child_roots: Vec<_> = Default::default();
180 for (child_info, child_delta) in child_deltas {
182 let (child_root, empty, child_txs) =
183 self.child_storage_root(&child_info, child_delta);
184 let prefixed_storage_key = child_info.prefixed_storage_key();
185 txs.consolidate(child_txs);
186 if empty {
187 child_roots.push((prefixed_storage_key.into_inner(), None));
188 } else {
189 child_roots.push((prefixed_storage_key.into_inner(), Some(child_root.encode())));
190 }
191 }
192 let (root, parent_txs) = self.storage_root(delta
193 .map(|(k, v)| (&k[..], v.as_ref().map(|v| &v[..])))
194 .chain(
195 child_roots
196 .iter()
197 .map(|(k, v)| (&k[..], v.as_ref().map(|v| &v[..])))
198 )
199 );
200 txs.consolidate(parent_txs);
201 (root, txs)
202 }
203
204 fn register_overlay_stats(&mut self, _stats: &crate::stats::StateMachineStats);
208
209 fn usage_info(&self) -> UsageInfo;
214
215 fn wipe(&self) -> Result<(), Self::Error> {
217 unimplemented!()
218 }
219
220 fn commit(
222 &self,
223 _: H::Out,
224 _: Self::Transaction,
225 _: StorageCollection,
226 _: ChildStorageCollection,
227 ) -> Result<(), Self::Error> {
228 unimplemented!()
229 }
230
231 fn read_write_count(&self) -> (u32, u32, u32, u32) {
233 unimplemented!()
234 }
235
236 fn reset_read_write_count(&self) {
238 unimplemented!()
239 }
240
241 fn get_whitelist(&self) -> Vec<TrackedStorageKey> {
243 Default::default()
244 }
245
246 fn set_whitelist(&self, _: Vec<TrackedStorageKey>) {}
248}
249
250impl<'a, T: Backend<H>, H: Hasher> Backend<H> for &'a T {
251 type Error = T::Error;
252 type Transaction = T::Transaction;
253 type TrieBackendStorage = T::TrieBackendStorage;
254
255 fn storage(&self, key: &[u8]) -> Result<Option<StorageKey>, Self::Error> {
256 (*self).storage(key)
257 }
258
259 fn child_storage(
260 &self,
261 child_info: &ChildInfo,
262 key: &[u8],
263 ) -> Result<Option<StorageKey>, Self::Error> {
264 (*self).child_storage(child_info, key)
265 }
266
267 fn apply_to_child_keys_while<F: FnMut(&[u8]) -> bool>(
268 &self,
269 child_info: &ChildInfo,
270 f: F,
271 ) {
272 (*self).apply_to_child_keys_while(child_info, f)
273 }
274
275 fn next_storage_key(&self, key: &[u8]) -> Result<Option<StorageKey>, Self::Error> {
276 (*self).next_storage_key(key)
277 }
278
279 fn next_child_storage_key(
280 &self,
281 child_info: &ChildInfo,
282 key: &[u8],
283 ) -> Result<Option<StorageKey>, Self::Error> {
284 (*self).next_child_storage_key(child_info, key)
285 }
286
287 fn for_keys_with_prefix<F: FnMut(&[u8])>(&self, prefix: &[u8], f: F) {
288 (*self).for_keys_with_prefix(prefix, f)
289 }
290
291 fn for_child_keys_with_prefix<F: FnMut(&[u8])>(
292 &self,
293 child_info: &ChildInfo,
294 prefix: &[u8],
295 f: F,
296 ) {
297 (*self).for_child_keys_with_prefix(child_info, prefix, f)
298 }
299
300 fn storage_root<'b>(
301 &self,
302 delta: impl Iterator<Item=(&'b [u8], Option<&'b [u8]>)>,
303 ) -> (H::Out, Self::Transaction) where H::Out: Ord {
304 (*self).storage_root(delta)
305 }
306
307 fn child_storage_root<'b>(
308 &self,
309 child_info: &ChildInfo,
310 delta: impl Iterator<Item=(&'b [u8], Option<&'b [u8]>)>,
311 ) -> (H::Out, bool, Self::Transaction) where H::Out: Ord {
312 (*self).child_storage_root(child_info, delta)
313 }
314
315 fn pairs(&self) -> Vec<(StorageKey, StorageValue)> {
316 (*self).pairs()
317 }
318
319 fn for_key_values_with_prefix<F: FnMut(&[u8], &[u8])>(&self, prefix: &[u8], f: F) {
320 (*self).for_key_values_with_prefix(prefix, f);
321 }
322
323 fn register_overlay_stats(&mut self, _stats: &crate::stats::StateMachineStats) { }
324
325 fn usage_info(&self) -> UsageInfo {
326 (*self).usage_info()
327 }
328}
329
330pub trait Consolidate {
332 fn consolidate(&mut self, other: Self);
334}
335
336impl Consolidate for () {
337 fn consolidate(&mut self, _: Self) {
338 ()
339 }
340}
341
342impl Consolidate for Vec<(
343 Option<ChildInfo>,
344 StorageCollection,
345 )> {
346 fn consolidate(&mut self, mut other: Self) {
347 self.append(&mut other);
348 }
349}
350
351impl<H: Hasher, KF: tp_trie::KeyFunction<H>> Consolidate for tp_trie::GenericMemoryDB<H, KF> {
352 fn consolidate(&mut self, other: Self) {
353 tp_trie::GenericMemoryDB::consolidate(self, other)
354 }
355}
356
357#[cfg(test)]
359pub(crate) fn insert_into_memory_db<H, I>(mdb: &mut tp_trie::MemoryDB<H>, input: I) -> Option<H::Out>
360 where
361 H: Hasher,
362 I: IntoIterator<Item=(StorageKey, StorageValue)>,
363{
364 use tp_trie::{TrieMut, trie_types::TrieDBMut};
365
366 let mut root = <H as Hasher>::Out::default();
367 {
368 let mut trie = TrieDBMut::<H>::new(mdb, &mut root);
369 for (key, value) in input {
370 if let Err(e) = trie.insert(&key, &value) {
371 log::warn!(target: "trie", "Failed to write to trie: {}", e);
372 return None;
373 }
374 }
375 }
376
377 Some(root)
378}
379
380#[cfg(feature = "std")]
382pub struct BackendRuntimeCode<'a, B, H> {
383 backend: &'a B,
384 _marker: std::marker::PhantomData<H>,
385}
386
387#[cfg(feature = "std")]
388impl<'a, B: Backend<H>, H: Hasher> tet_core::traits::FetchRuntimeCode for
389 BackendRuntimeCode<'a, B, H>
390{
391 fn fetch_runtime_code<'b>(&'b self) -> Option<std::borrow::Cow<'b, [u8]>> {
392 self.backend.storage(well_known_keys::CODE).ok().flatten().map(Into::into)
393 }
394}
395
396#[cfg(feature = "std")]
397impl<'a, B: Backend<H>, H: Hasher> BackendRuntimeCode<'a, B, H> where H::Out: Encode {
398 pub fn new(backend: &'a B) -> Self {
400 Self {
401 backend,
402 _marker: std::marker::PhantomData,
403 }
404 }
405
406 pub fn runtime_code(&self) -> Result<RuntimeCode, &'static str> {
408 let hash = self.backend.storage_hash(well_known_keys::CODE)
409 .ok()
410 .flatten()
411 .ok_or("`:code` hash not found")?
412 .encode();
413 let heap_pages = self.backend.storage(well_known_keys::HEAP_PAGES)
414 .ok()
415 .flatten()
416 .and_then(|d| Decode::decode(&mut &d[..]).ok());
417
418 Ok(RuntimeCode { code_fetcher: self, hash, heap_pages })
419 }
420}