forked from paritytech/substrate
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwith_std.rs
More file actions
366 lines (309 loc) · 10.1 KB
/
with_std.rs
File metadata and controls
366 lines (309 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
// Copyright 2017-2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
// re-export hashing functions.
pub use primitives::{
blake2_128, blake2_256, twox_128, twox_256, twox_64, ed25519, Blake2Hasher,
sr25519, Pair, subtrie::{SubTrie, SubTrieReadRef, KeySpace},
};
// Switch to this after PoC-3
// pub use primitives::BlakeHasher;
pub use substrate_state_machine::{
Externalities,
BasicExternalities,
TestExternalities,
ChildStorageKey
};
use environmental::environmental;
use primitives::{hexdisplay::HexDisplay, H256};
#[cfg(feature = "std")]
use std::collections::HashMap;
environmental!(ext: trait Externalities<Blake2Hasher>);
/// Additional bounds for `Hasher` trait for with_std.
pub trait HasherBounds {}
impl<T: Hasher> HasherBounds for T {}
/// Returns a `ChildStorageKey` if the given `storage_key` slice is a valid storage
/// key or panics otherwise.
///
/// Panicking here is aligned with what the `without_std` environment would do
/// in the case of an invalid child storage key.
fn child_storage_key_or_panic(storage_key: &[u8]) -> ChildStorageKey<Blake2Hasher> {
match ChildStorageKey::from_slice(storage_key) {
Some(storage_key) => storage_key,
None => panic!("child storage key is invalid"),
}
}
impl StorageApi for () {
fn storage(key: &[u8]) -> Option<Vec<u8>> {
ext::with(|ext| ext.storage(key).map(|s| s.to_vec()))
.expect("storage cannot be called outside of an Externalities-provided environment.")
}
fn read_storage(key: &[u8], value_out: &mut [u8], value_offset: usize) -> Option<usize> {
ext::with(|ext| ext.storage(key).map(|value| {
let value = &value[value_offset..];
let written = std::cmp::min(value.len(), value_out.len());
value_out[..written].copy_from_slice(&value[..written]);
value.len()
})).expect("read_storage cannot be called outside of an Externalities-provided environment.")
}
fn child_trie(storage_key: &[u8]) -> Option<SubTrie> {
ext::with(|ext| ext.child_trie(storage_key))
.expect("storage cannot be called outside of an Externalities-provided environment.")
}
fn child_storage(subtrie: SubTrieReadRef, key: &[u8]) -> Option<Vec<u8>> {
ext::with(|ext| {
ext.child_storage(subtrie, key).map(|s| s.to_vec())
})
.expect("storage cannot be called outside of an Externalities-provided environment.")
}
fn set_storage(key: &[u8], value: &[u8]) {
ext::with(|ext|
ext.set_storage(key.to_vec(), value.to_vec())
);
}
fn read_child_storage(
subtrie: SubTrieReadRef,
key: &[u8],
value_out: &mut [u8],
value_offset: usize,
) -> Option<usize> {
ext::with(|ext| {
ext.child_storage(subtrie, key)
.map(|value| {
let value = &value[value_offset..];
let written = std::cmp::min(value.len(), value_out.len());
value_out[..written].copy_from_slice(&value[..written]);
value.len()
})
})
.expect("read_child_storage cannot be called outside of an Externalities-provided environment.")
}
fn set_child_storage(subtrie: &SubTrie, key: &[u8], value: &[u8]) {
ext::with(|ext| {
ext.set_child_storage(subtrie, key.to_vec(), value.to_vec())
});
}
fn clear_storage(key: &[u8]) {
ext::with(|ext|
ext.clear_storage(key)
);
}
fn clear_child_storage(subtrie: &SubTrie, key: &[u8]) {
ext::with(|ext| {
ext.clear_child_storage(subtrie, key)
});
}
fn kill_child_storage(subtrie: &SubTrie) {
ext::with(|ext| {
ext.kill_child_storage(subtrie)
});
}
fn exists_storage(key: &[u8]) -> bool {
ext::with(|ext|
ext.exists_storage(key)
).unwrap_or(false)
}
fn exists_child_storage(subtrie: SubTrieReadRef, key: &[u8]) -> bool {
ext::with(|ext| {
ext.exists_child_storage(subtrie, key)
}).unwrap_or(false)
}
fn clear_prefix(prefix: &[u8]) {
ext::with(|ext|
ext.clear_prefix(prefix)
);
}
fn storage_root() -> [u8; 32] {
ext::with(|ext|
ext.storage_root()
).unwrap_or(H256::zero()).into()
}
fn child_storage_root(subtrie: &SubTrie) -> Vec<u8> {
ext::with(|ext| {
ext.child_storage_root(subtrie)
}).expect("child_storage_root cannot be called outside of an Externalities-provided environment.")
}
fn storage_changes_root(parent_hash: [u8; 32]) -> Option<[u8; 32]> {
ext::with(|ext|
ext.storage_changes_root(parent_hash.into()).map(|h| h.map(|h| h.into()))
).unwrap_or(Ok(None)).expect("Invalid parent hash passed to storage_changes_root")
}
fn enumerated_trie_root<H>(input: &[&[u8]]) -> H::Out
where
H: Hasher,
H::Out: Ord,
{
trie::ordered_trie_root::<H, _, _>(input.iter())
}
fn trie_root<H, I, A, B>(input: I) -> H::Out
where
I: IntoIterator<Item = (A, B)>,
A: AsRef<[u8]> + Ord,
B: AsRef<[u8]>,
H: Hasher,
H::Out: Ord,
{
trie::trie_root::<H, _, _, _>(input)
}
fn ordered_trie_root<H, I, A>(input: I) -> H::Out
where
I: IntoIterator<Item = A>,
A: AsRef<[u8]>,
H: Hasher,
H::Out: Ord,
{
trie::ordered_trie_root::<H, _, _>(input)
}
}
impl OtherApi for () {
fn chain_id() -> u64 {
ext::with(|ext|
ext.chain_id()
).unwrap_or(0)
}
fn print<T: Printable + Sized>(value: T) {
value.print()
}
}
impl CryptoApi for () {
fn ed25519_verify<P: AsRef<[u8]>>(sig: &[u8; 64], msg: &[u8], pubkey: P) -> bool {
ed25519::Pair::verify_weak(sig, msg, pubkey)
}
fn sr25519_verify<P: AsRef<[u8]>>(sig: &[u8; 64], msg: &[u8], pubkey: P) -> bool {
sr25519::Pair::verify_weak(sig, msg, pubkey)
}
fn secp256k1_ecdsa_recover(sig: &[u8; 65], msg: &[u8; 32]) -> Result<[u8; 64], EcdsaVerifyError> {
let rs = secp256k1::Signature::parse_slice(&sig[0..64]).map_err(|_| EcdsaVerifyError::BadRS)?;
let v = secp256k1::RecoveryId::parse(if sig[64] > 26 { sig[64] - 27 } else { sig[64] } as u8).map_err(|_| EcdsaVerifyError::BadV)?;
let pubkey = secp256k1::recover(&secp256k1::Message::parse(msg), &rs, &v).map_err(|_| EcdsaVerifyError::BadSignature)?;
let mut res = [0u8; 64];
res.copy_from_slice(&pubkey.serialize()[1..65]);
Ok(res)
}
}
impl HashingApi for () {
fn keccak_256(data: &[u8]) -> [u8; 32] {
tiny_keccak::keccak256(data)
}
fn blake2_128(data: &[u8]) -> [u8; 16] {
blake2_128(data)
}
fn blake2_256(data: &[u8]) -> [u8; 32] {
blake2_256(data)
}
fn twox_256(data: &[u8]) -> [u8; 32] {
twox_256(data)
}
fn twox_128(data: &[u8]) -> [u8; 16] {
twox_128(data)
}
fn twox_64(data: &[u8]) -> [u8; 8] {
twox_64(data)
}
}
impl OffchainApi for () {
fn submit_extrinsic<T: codec::Encode>(data: &T) {
ext::with(|ext| ext
.submit_extrinsic(codec::Encode::encode(data))
.expect("submit_extrinsic can be called only in offchain worker context")
).expect("submit_extrinsic cannot be called outside of an Externalities-provided environment.")
}
}
impl Api for () {}
/// Execute the given closure with global function available whose functionality routes into the
/// externalities `ext`. Forwards the value that the closure returns.
// NOTE: need a concrete hasher here due to limitations of the `environmental!` macro, otherwise a type param would have been fine I think.
pub fn with_externalities<R, F: FnOnce() -> R>(ext: &mut Externalities<Blake2Hasher>, f: F) -> R {
ext::using(ext, f)
}
/// A set of key value pairs for storage.
pub type StorageOverlay = HashMap<Vec<u8>, Vec<u8>>;
/// A set of key value pairs for children storage;
pub type ChildrenStorageOverlay = HashMap<KeySpace, (StorageOverlay, SubTrie)>;
/// Execute the given closure with global functions available whose functionality routes into
/// externalities that draw from and populate `storage`. Forwards the value that the closure returns.
pub fn with_storage<R, F: FnOnce() -> R>(storage: &mut StorageOverlay, f: F) -> R {
let mut alt_storage = Default::default();
rstd::mem::swap(&mut alt_storage, storage);
let mut ext: BasicExternalities = alt_storage.into();
let r = ext::using(&mut ext, f);
*storage = ext.into();
r
}
impl<'a> Printable for &'a [u8] {
fn print(self) {
println!("Runtime: {}", HexDisplay::from(&self));
}
}
impl<'a> Printable for &'a str {
fn print(self) {
println!("Runtime: {}", self);
}
}
impl Printable for u64 {
fn print(self) {
println!("Runtime: {}", self);
}
}
#[cfg(test)]
mod std_tests {
use super::*;
use primitives::map;
#[test]
fn storage_works() {
let mut t = BasicExternalities::default();
assert!(with_externalities(&mut t, || {
assert_eq!(storage(b"hello"), None);
set_storage(b"hello", b"world");
assert_eq!(storage(b"hello"), Some(b"world".to_vec()));
assert_eq!(storage(b"foo"), None);
set_storage(b"foo", &[1, 2, 3][..]);
true
}));
t = BasicExternalities::new(map![b"foo".to_vec() => b"bar".to_vec()]);
assert!(!with_externalities(&mut t, || {
assert_eq!(storage(b"hello"), None);
assert_eq!(storage(b"foo"), Some(b"bar".to_vec()));
false
}));
}
#[test]
fn read_storage_works() {
let mut t = BasicExternalities::new(map![
b":test".to_vec() => b"\x0b\0\0\0Hello world".to_vec()
]);
with_externalities(&mut t, || {
let mut v = [0u8; 4];
assert!(read_storage(b":test", &mut v[..], 0).unwrap() >= 4);
assert_eq!(v, [11u8, 0, 0, 0]);
let mut w = [0u8; 11];
assert!(read_storage(b":test", &mut w[..], 4).unwrap() >= 11);
assert_eq!(&w, b"Hello world");
});
}
#[test]
fn clear_prefix_works() {
let mut t = BasicExternalities::new(map![
b":a".to_vec() => b"\x0b\0\0\0Hello world".to_vec(),
b":abcd".to_vec() => b"\x0b\0\0\0Hello world".to_vec(),
b":abc".to_vec() => b"\x0b\0\0\0Hello world".to_vec(),
b":abdd".to_vec() => b"\x0b\0\0\0Hello world".to_vec()
]);
with_externalities(&mut t, || {
clear_prefix(b":abc");
assert!(storage(b":a").is_some());
assert!(storage(b":abdd").is_some());
assert!(storage(b":abcd").is_none());
assert!(storage(b":abc").is_none());
});
}
}