gp_externalities/lib.rs
1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18#![cfg_attr(not(feature = "std"), no_std)]
19
20//! Substrate externalities abstraction
21//!
22//! The externalities mainly provide access to storage and to registered extensions. Extensions
23//! are for example the keystore or the offchain externalities. These externalities are used to
24//! access the node from the runtime via the runtime interfaces.
25//!
26//! This crate exposes the main [`Externalities`] trait.
27
28use sp_std::{
29 any::{Any, TypeId},
30 boxed::Box,
31 vec::Vec,
32};
33
34use sp_storage::{ChildInfo, StateVersion, TrackedStorageKey};
35
36pub use extensions::{Extension, ExtensionStore, Extensions};
37pub use scope_limited::{set_and_run_with_externalities, with_externalities};
38
39mod extensions;
40mod scope_limited;
41
42/// Externalities error.
43#[derive(Debug)]
44pub enum Error {
45 /// Same extension cannot be registered twice.
46 ExtensionAlreadyRegistered,
47 /// Extensions are not supported.
48 ExtensionsAreNotSupported,
49 /// Extension `TypeId` is not registered.
50 ExtensionIsNotRegistered(TypeId),
51 /// Failed to update storage,
52 StorageUpdateFailed(&'static str),
53}
54
55/// Results concerning an operation to remove many keys.
56#[derive(codec::Encode, codec::Decode)]
57#[must_use]
58pub struct MultiRemovalResults {
59 /// A continuation cursor which, if `Some` must be provided to the subsequent removal call.
60 /// If `None` then all removals are complete and no further calls are needed.
61 pub maybe_cursor: Option<Vec<u8>>,
62 /// The number of items removed from the backend database.
63 pub backend: u32,
64 /// The number of unique keys removed, taking into account both the backend and the overlay.
65 pub unique: u32,
66 /// The number of iterations (each requiring a storage seek/read) which were done.
67 pub loops: u32,
68}
69
70impl MultiRemovalResults {
71 /// Deconstruct into the internal components.
72 ///
73 /// Returns `(maybe_cursor, backend, unique, loops)`.
74 pub fn deconstruct(self) -> (Option<Vec<u8>>, u32, u32, u32) {
75 (self.maybe_cursor, self.backend, self.unique, self.loops)
76 }
77}
78
79/// The Substrate externalities.
80///
81/// Provides access to the storage and to other registered extensions.
82pub trait Externalities: ExtensionStore {
83 /// Write a key value pair to the offchain storage database.
84 fn set_offchain_storage(&mut self, key: &[u8], value: Option<&[u8]>);
85
86 /// Read runtime storage.
87 fn storage(&self, key: &[u8]) -> Option<Vec<u8>>;
88
89 /// Get storage value hash.
90 ///
91 /// This may be optimized for large values.
92 fn storage_hash(&self, key: &[u8]) -> Option<Vec<u8>>;
93
94 /// Get child storage value hash.
95 ///
96 /// This may be optimized for large values.
97 ///
98 /// Returns an `Option` that holds the SCALE encoded hash.
99 fn child_storage_hash(&self, child_info: &ChildInfo, key: &[u8]) -> Option<Vec<u8>>;
100
101 /// Read child runtime storage.
102 ///
103 /// Returns an `Option` that holds the SCALE encoded hash.
104 fn child_storage(&self, child_info: &ChildInfo, key: &[u8]) -> Option<Vec<u8>>;
105
106 /// Set storage entry `key` of current contract being called (effective immediately).
107 fn set_storage(&mut self, key: Vec<u8>, value: Vec<u8>) {
108 self.place_storage(key, Some(value));
109 }
110
111 /// Set child storage entry `key` of current contract being called (effective immediately).
112 fn set_child_storage(&mut self, child_info: &ChildInfo, key: Vec<u8>, value: Vec<u8>) {
113 self.place_child_storage(child_info, key, Some(value))
114 }
115
116 /// Clear a storage entry (`key`) of current contract being called (effective immediately).
117 fn clear_storage(&mut self, key: &[u8]) {
118 self.place_storage(key.to_vec(), None);
119 }
120
121 /// Clear a child storage entry (`key`) of current contract being called (effective
122 /// immediately).
123 fn clear_child_storage(&mut self, child_info: &ChildInfo, key: &[u8]) {
124 self.place_child_storage(child_info, key.to_vec(), None)
125 }
126
127 /// Whether a storage entry exists.
128 fn exists_storage(&self, key: &[u8]) -> bool {
129 self.storage(key).is_some()
130 }
131
132 /// Whether a child storage entry exists.
133 fn exists_child_storage(&self, child_info: &ChildInfo, key: &[u8]) -> bool {
134 self.child_storage(child_info, key).is_some()
135 }
136
137 /// Returns the key immediately following the given key, if it exists.
138 fn next_storage_key(&self, key: &[u8]) -> Option<Vec<u8>>;
139
140 /// Returns the key immediately following the given key, if it exists, in child storage.
141 fn next_child_storage_key(&self, child_info: &ChildInfo, key: &[u8]) -> Option<Vec<u8>>;
142
143 /// Clear an entire child storage.
144 ///
145 /// Deletes all keys from the overlay and up to `maybe_limit` keys from the backend. No
146 /// limit is applied if `maybe_limit` is `None`. Returns the cursor for the next call as `Some`
147 /// if the child trie deletion operation is incomplete. In this case, it should be passed into
148 /// the next call to avoid unaccounted iterations on the backend. Returns also the the number
149 /// of keys that were removed from the backend, the number of unique keys removed in total
150 /// (including from the overlay) and the number of backend iterations done.
151 ///
152 /// As long as `maybe_cursor` is passed from the result of the previous call, then the number of
153 /// iterations done will only ever be one more than the number of keys removed.
154 ///
155 /// # Note
156 ///
157 /// An implementation is free to delete more keys than the specified limit as long as
158 /// it is able to do that in constant time.
159 fn kill_child_storage(
160 &mut self,
161 child_info: &ChildInfo,
162 maybe_limit: Option<u32>,
163 maybe_cursor: Option<&[u8]>,
164 ) -> MultiRemovalResults;
165
166 /// Clear storage entries which keys are start with the given prefix.
167 ///
168 /// `maybe_limit`, `maybe_cursor` and result works as for `kill_child_storage`.
169 fn clear_prefix(
170 &mut self,
171 prefix: &[u8],
172 maybe_limit: Option<u32>,
173 maybe_cursor: Option<&[u8]>,
174 ) -> MultiRemovalResults;
175
176 /// Clear child storage entries which keys are start with the given prefix.
177 ///
178 /// `maybe_limit`, `maybe_cursor` and result works as for `kill_child_storage`.
179 fn clear_child_prefix(
180 &mut self,
181 child_info: &ChildInfo,
182 prefix: &[u8],
183 maybe_limit: Option<u32>,
184 maybe_cursor: Option<&[u8]>,
185 ) -> MultiRemovalResults;
186
187 /// Set or clear a storage entry (`key`) of current contract being called (effective
188 /// immediately).
189 fn place_storage(&mut self, key: Vec<u8>, value: Option<Vec<u8>>);
190
191 /// Set or clear a child storage entry.
192 fn place_child_storage(&mut self, child_info: &ChildInfo, key: Vec<u8>, value: Option<Vec<u8>>);
193
194 /// Get the trie root of the current storage map.
195 ///
196 /// This will also update all child storage keys in the top-level storage map.
197 ///
198 /// The returned hash is defined by the `Block` and is SCALE encoded.
199 fn storage_root(&mut self, state_version: StateVersion) -> Vec<u8>;
200
201 /// Get the trie root of a child storage map.
202 ///
203 /// This will also update the value of the child storage keys in the top-level storage map.
204 ///
205 /// If the storage root equals the default hash as defined by the trie, the key in the top-level
206 /// storage map will be removed.
207 fn child_storage_root(
208 &mut self,
209 child_info: &ChildInfo,
210 state_version: StateVersion,
211 ) -> Vec<u8>;
212
213 /// Append storage item.
214 ///
215 /// This assumes specific format of the storage item. Also there is no way to undo this
216 /// operation.
217 fn storage_append(&mut self, key: Vec<u8>, value: Vec<u8>);
218
219 /// Start a new nested transaction.
220 ///
221 /// This allows to either commit or roll back all changes made after this call to the
222 /// top changes or the default child changes. For every transaction there cam be a
223 /// matching call to either `storage_rollback_transaction` or `storage_commit_transaction`.
224 /// Any transactions that are still open after returning from runtime are committed
225 /// automatically.
226 ///
227 /// Changes made without any open transaction are committed immediately.
228 fn storage_start_transaction(&mut self);
229
230 /// Rollback the last transaction started by `storage_start_transaction`.
231 ///
232 /// Any changes made during that storage transaction are discarded. Returns an error when
233 /// no transaction is open that can be closed.
234 fn storage_rollback_transaction(&mut self) -> Result<(), ()>;
235
236 /// Commit the last transaction started by `storage_start_transaction`.
237 ///
238 /// Any changes made during that storage transaction are committed. Returns an error when
239 /// no transaction is open that can be closed.
240 fn storage_commit_transaction(&mut self) -> Result<(), ()>;
241
242 /// Index specified transaction slice and store it.
243 fn storage_index_transaction(&mut self, _index: u32, _hash: &[u8], _size: u32) {
244 unimplemented!("storage_index_transaction");
245 }
246
247 /// Renew existing piece of transaction storage.
248 fn storage_renew_transaction_index(&mut self, _index: u32, _hash: &[u8]) {
249 unimplemented!("storage_renew_transaction_index");
250 }
251
252 /// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
253 /// Benchmarking related functionality and shouldn't be used anywhere else!
254 /// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
255 ///
256 /// Wipes all changes from caches and the database.
257 ///
258 /// The state will be reset to genesis.
259 fn wipe(&mut self);
260
261 /// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
262 /// Benchmarking related functionality and shouldn't be used anywhere else!
263 /// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
264 ///
265 /// Commits all changes to the database and clears all caches.
266 fn commit(&mut self);
267
268 /// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
269 /// Benchmarking related functionality and shouldn't be used anywhere else!
270 /// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
271 ///
272 /// Gets the current read/write count for the benchmarking process.
273 fn read_write_count(&self) -> (u32, u32, u32, u32);
274
275 /// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
276 /// Benchmarking related functionality and shouldn't be used anywhere else!
277 /// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
278 ///
279 /// Resets read/write count for the benchmarking process.
280 fn reset_read_write_count(&mut self);
281
282 /// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
283 /// Benchmarking related functionality and shouldn't be used anywhere else!
284 /// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
285 ///
286 /// Gets the current DB tracking whitelist.
287 fn get_whitelist(&self) -> Vec<TrackedStorageKey>;
288
289 /// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
290 /// Benchmarking related functionality and shouldn't be used anywhere else!
291 /// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
292 ///
293 /// Adds new storage keys to the DB tracking whitelist.
294 fn set_whitelist(&mut self, new: Vec<TrackedStorageKey>);
295
296 /// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
297 /// Benchmarking related functionality and shouldn't be used anywhere else!
298 /// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
299 ///
300 /// Returns estimated proof size for the state queries so far.
301 /// Proof is reset on commit and wipe.
302 fn proof_size(&self) -> Option<u32> {
303 None
304 }
305
306 /// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
307 /// Benchmarking related functionality and shouldn't be used anywhere else!
308 /// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
309 ///
310 /// Get all the keys that have been read or written to during the benchmark.
311 fn get_read_and_written_keys(&self) -> Vec<(Vec<u8>, u32, u32, bool)>;
312}
313
314/// Extension for the [`Externalities`] trait.
315pub trait ExternalitiesExt {
316 /// Tries to find a registered extension and returns a mutable reference.
317 fn extension<T: Any + Extension>(&mut self) -> Option<&mut T>;
318
319 /// Register extension `ext`.
320 ///
321 /// Should return error if extension is already registered or extensions are not supported.
322 fn register_extension<T: Extension>(&mut self, ext: T) -> Result<(), Error>;
323
324 /// Deregister and drop extension of `T` type.
325 ///
326 /// Should return error if extension of type `T` is not registered or
327 /// extensions are not supported.
328 fn deregister_extension<T: Extension>(&mut self) -> Result<(), Error>;
329}
330
331impl ExternalitiesExt for &mut dyn Externalities {
332 fn extension<T: Any + Extension>(&mut self) -> Option<&mut T> {
333 self.extension_by_type_id(TypeId::of::<T>()).and_then(<dyn Any>::downcast_mut)
334 }
335
336 fn register_extension<T: Extension>(&mut self, ext: T) -> Result<(), Error> {
337 self.register_extension_with_type_id(TypeId::of::<T>(), Box::new(ext))
338 }
339
340 fn deregister_extension<T: Extension>(&mut self) -> Result<(), Error> {
341 self.deregister_extension_by_type_id(TypeId::of::<T>())
342 }
343}