This repository has been archived by the owner on Nov 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathlib.rs
2228 lines (2038 loc) · 65.8 KB
/
lib.rs
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Substrate state machine implementation.
#![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
pub mod backend;
#[cfg(feature = "std")]
mod basic;
mod error;
mod ext;
#[cfg(feature = "std")]
mod in_memory_backend;
pub(crate) mod overlayed_changes;
#[cfg(feature = "std")]
mod read_only;
mod stats;
#[cfg(feature = "std")]
mod testing;
mod trie_backend;
mod trie_backend_essence;
#[cfg(feature = "std")]
pub use std_reexport::*;
#[cfg(feature = "std")]
pub use execution::*;
#[cfg(feature = "std")]
pub use log::{debug, error as log_error, warn};
#[cfg(feature = "std")]
pub use tracing::trace;
/// In no_std we skip logs for state_machine, this macro
/// is a noops.
#[cfg(not(feature = "std"))]
#[macro_export]
macro_rules! warn {
(target: $target:expr, $message:expr $( , $arg:ident )* $( , )?) => {
{
$(
let _ = &$arg;
)*
}
};
($message:expr, $( $arg:expr, )*) => {
{
$(
let _ = &$arg;
)*
}
};
}
/// In no_std we skip logs for state_machine, this macro
/// is a noops.
#[cfg(not(feature = "std"))]
#[macro_export]
macro_rules! debug {
(target: $target:expr, $message:expr $( , $arg:ident )* $( , )?) => {
{
$(
let _ = &$arg;
)*
}
};
}
/// In no_std we skip logs for state_machine, this macro
/// is a noops.
#[cfg(not(feature = "std"))]
#[macro_export]
macro_rules! trace {
(target: $target:expr, $($arg:tt)+) => {
()
};
($($arg:tt)+) => {
()
};
}
/// In no_std we skip logs for state_machine, this macro
/// is a noops.
#[cfg(not(feature = "std"))]
#[macro_export]
macro_rules! log_error {
(target: $target:expr, $($arg:tt)+) => {
()
};
($($arg:tt)+) => {
()
};
}
/// Default error type to use with state machine trie backend.
#[cfg(feature = "std")]
pub type DefaultError = String;
/// Error type to use with state machine trie backend.
#[cfg(not(feature = "std"))]
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq)]
pub struct DefaultError;
#[cfg(not(feature = "std"))]
impl sp_std::fmt::Display for DefaultError {
fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
write!(f, "DefaultError")
}
}
pub use crate::{
backend::{Backend, IterArgs, KeysIter, PairsIter, StorageIterator},
error::{Error, ExecutionError},
ext::Ext,
overlayed_changes::{
ChildStorageCollection, IndexOperation, OffchainChangesCollection,
OffchainOverlayedChanges, OverlayedChanges, StorageChanges, StorageCollection, StorageKey,
StorageTransactionCache, StorageValue,
},
stats::{StateMachineStats, UsageInfo, UsageUnit},
trie_backend::{TrieBackend, TrieBackendBuilder},
trie_backend_essence::{Storage, TrieBackendStorage},
};
#[cfg(feature = "std")]
mod std_reexport {
pub use crate::{
basic::BasicExternalities,
error::{Error, ExecutionError},
in_memory_backend::{new_in_mem, new_in_mem_hash_key},
read_only::{InspectState, ReadOnlyExternalities},
testing::TestExternalities,
trie_backend::create_proof_check_backend,
};
pub use sp_trie::{
trie_types::{TrieDBMutV0, TrieDBMutV1},
CompactProof, DBValue, LayoutV0, LayoutV1, MemoryDB, StorageProof, TrieMut,
};
}
#[cfg(feature = "std")]
mod execution {
use crate::backend::AsTrieBackend;
use super::*;
use codec::Codec;
use hash_db::Hasher;
use smallvec::SmallVec;
use sp_core::{
hexdisplay::HexDisplay,
storage::{ChildInfo, ChildType, PrefixedStorageKey},
traits::{CallContext, CodeExecutor, ReadRuntimeVersionExt, RuntimeCode, SpawnNamed},
};
use sp_externalities::Extensions;
use std::{
collections::{HashMap, HashSet},
fmt,
};
const PROOF_CLOSE_TRANSACTION: &str = "\
Closing a transaction that was started in this function. Client initiated transactions
are protected from being closed by the runtime. qed";
pub(crate) type CallResult<E> = Result<Vec<u8>, E>;
/// Default handler of the execution manager.
pub type DefaultHandler<E> = fn(CallResult<E>, CallResult<E>) -> CallResult<E>;
/// Trie backend with in-memory storage.
pub type InMemoryBackend<H> = TrieBackend<MemoryDB<H>, H>;
/// Strategy for executing a call into the runtime.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum ExecutionStrategy {
/// Execute with the native equivalent if it is compatible with the given wasm module;
/// otherwise fall back to the wasm.
NativeWhenPossible,
/// Use the given wasm module.
AlwaysWasm,
/// Run with both the wasm and the native variant (if compatible). Report any discrepancy
/// as an error.
Both,
/// First native, then if that fails or is not possible, wasm.
NativeElseWasm,
}
/// Storage backend trust level.
#[derive(Debug, Clone)]
pub enum BackendTrustLevel {
/// Panics from trusted backends are considered justified, and never caught.
Trusted,
/// Panics from untrusted backend are caught and interpreted as runtime error.
/// Untrusted backend may be missing some parts of the trie, so panics are not considered
/// fatal.
Untrusted,
}
/// Like `ExecutionStrategy` only it also stores a handler in case of consensus failure.
#[derive(Clone)]
pub enum ExecutionManager<F> {
/// Execute with the native equivalent if it is compatible with the given wasm module;
/// otherwise fall back to the wasm.
NativeWhenPossible,
/// Use the given wasm module. The backend on which code is executed code could be
/// trusted to provide all storage or not (i.e. the light client cannot be trusted to
/// provide for all storage queries since the storage entries it has come from an external
/// node).
AlwaysWasm(BackendTrustLevel),
/// Run with both the wasm and the native variant (if compatible). Call `F` in the case of
/// any discrepancy.
Both(F),
/// First native, then if that fails or is not possible, wasm.
NativeElseWasm,
}
impl<'a, F> From<&'a ExecutionManager<F>> for ExecutionStrategy {
fn from(s: &'a ExecutionManager<F>) -> Self {
match *s {
ExecutionManager::NativeWhenPossible => ExecutionStrategy::NativeWhenPossible,
ExecutionManager::AlwaysWasm(_) => ExecutionStrategy::AlwaysWasm,
ExecutionManager::NativeElseWasm => ExecutionStrategy::NativeElseWasm,
ExecutionManager::Both(_) => ExecutionStrategy::Both,
}
}
}
impl ExecutionStrategy {
/// Gets the corresponding manager for the execution strategy.
pub fn get_manager<E: fmt::Debug>(self) -> ExecutionManager<DefaultHandler<E>> {
match self {
ExecutionStrategy::AlwaysWasm =>
ExecutionManager::AlwaysWasm(BackendTrustLevel::Trusted),
ExecutionStrategy::NativeWhenPossible => ExecutionManager::NativeWhenPossible,
ExecutionStrategy::NativeElseWasm => ExecutionManager::NativeElseWasm,
ExecutionStrategy::Both => ExecutionManager::Both(|wasm_result, native_result| {
warn!(
"Consensus error between wasm {:?} and native {:?}. Using wasm.",
wasm_result, native_result,
);
warn!(" Native result {:?}", native_result);
warn!(" Wasm result {:?}", wasm_result);
wasm_result
}),
}
}
}
/// Evaluate to ExecutionManager::NativeElseWasm, without having to figure out the type.
pub fn native_else_wasm<E>() -> ExecutionManager<DefaultHandler<E>> {
ExecutionManager::NativeElseWasm
}
/// Evaluate to ExecutionManager::AlwaysWasm with trusted backend, without having to figure out
/// the type.
fn always_wasm<E>() -> ExecutionManager<DefaultHandler<E>> {
ExecutionManager::AlwaysWasm(BackendTrustLevel::Trusted)
}
/// Evaluate ExecutionManager::AlwaysWasm with untrusted backend, without having to figure out
/// the type.
fn always_untrusted_wasm<E>() -> ExecutionManager<DefaultHandler<E>> {
ExecutionManager::AlwaysWasm(BackendTrustLevel::Untrusted)
}
/// The substrate state machine.
pub struct StateMachine<'a, B, H, Exec>
where
H: Hasher,
B: Backend<H>,
{
backend: &'a B,
exec: &'a Exec,
method: &'a str,
call_data: &'a [u8],
overlay: &'a mut OverlayedChanges,
extensions: Extensions,
storage_transaction_cache: Option<&'a mut StorageTransactionCache<B::Transaction, H>>,
runtime_code: &'a RuntimeCode<'a>,
stats: StateMachineStats,
/// The hash of the block the state machine will be executed on.
///
/// Used for logging.
parent_hash: Option<H::Out>,
context: CallContext,
}
impl<'a, B, H, Exec> Drop for StateMachine<'a, B, H, Exec>
where
H: Hasher,
B: Backend<H>,
{
fn drop(&mut self) {
self.backend.register_overlay_stats(&self.stats);
}
}
impl<'a, B, H, Exec> StateMachine<'a, B, H, Exec>
where
H: Hasher,
H::Out: Ord + 'static + codec::Codec,
Exec: CodeExecutor + Clone + 'static,
B: Backend<H>,
{
/// Creates new substrate state machine.
pub fn new(
backend: &'a B,
overlay: &'a mut OverlayedChanges,
exec: &'a Exec,
method: &'a str,
call_data: &'a [u8],
mut extensions: Extensions,
runtime_code: &'a RuntimeCode,
spawn_handle: impl SpawnNamed + Send + 'static,
context: CallContext,
) -> Self {
extensions.register(ReadRuntimeVersionExt::new(exec.clone()));
extensions.register(sp_core::traits::TaskExecutorExt::new(spawn_handle));
Self {
backend,
exec,
method,
call_data,
extensions,
overlay,
storage_transaction_cache: None,
runtime_code,
stats: StateMachineStats::default(),
parent_hash: None,
context,
}
}
/// Use given `cache` as storage transaction cache.
///
/// The cache will be used to cache storage transactions that can be build while executing a
/// function in the runtime. For example, when calculating the storage root a transaction is
/// build that will be cached.
pub fn with_storage_transaction_cache(
mut self,
cache: Option<&'a mut StorageTransactionCache<B::Transaction, H>>,
) -> Self {
self.storage_transaction_cache = cache;
self
}
/// Set the given `parent_hash` as the hash of the parent block.
///
/// This will be used for improved logging.
pub fn set_parent_hash(mut self, parent_hash: H::Out) -> Self {
self.parent_hash = Some(parent_hash);
self
}
/// Execute a call using the given state backend, overlayed changes, and call executor.
///
/// On an error, no prospective changes are written to the overlay.
///
/// Note: changes to code will be in place if this call is made again. For running partial
/// blocks (e.g. a transaction at a time), ensure a different method is used.
///
/// Returns the SCALE encoded result of the executed function.
pub fn execute(&mut self, strategy: ExecutionStrategy) -> Result<Vec<u8>, Box<dyn Error>> {
// We are not giving a native call and thus we are sure that the result can never be a
// native value.
self.execute_using_consensus_failure_handler(strategy.get_manager())
}
fn execute_aux(&mut self, use_native: bool) -> (CallResult<Exec::Error>, bool) {
let mut cache = StorageTransactionCache::default();
let cache = match self.storage_transaction_cache.as_mut() {
Some(cache) => cache,
None => &mut cache,
};
self.overlay
.enter_runtime()
.expect("StateMachine is never called from the runtime; qed");
let mut ext = Ext::new(self.overlay, cache, self.backend, Some(&mut self.extensions));
let ext_id = ext.id;
trace!(
target: "state",
ext_id = %HexDisplay::from(&ext_id.to_le_bytes()),
method = %self.method,
parent_hash = %self.parent_hash.map(|h| format!("{:?}", h)).unwrap_or_else(|| String::from("None")),
input = ?HexDisplay::from(&self.call_data),
"Call",
);
let (result, was_native) = self.exec.call(
&mut ext,
self.runtime_code,
self.method,
self.call_data,
use_native,
self.context,
);
self.overlay
.exit_runtime()
.expect("Runtime is not able to call this function in the overlay; qed");
trace!(
target: "state",
ext_id = %HexDisplay::from(&ext_id.to_le_bytes()),
?was_native,
?result,
"Return",
);
(result, was_native)
}
fn execute_call_with_both_strategy<Handler>(
&mut self,
on_consensus_failure: Handler,
) -> CallResult<Exec::Error>
where
Handler:
FnOnce(CallResult<Exec::Error>, CallResult<Exec::Error>) -> CallResult<Exec::Error>,
{
self.overlay.start_transaction();
let (result, was_native) = self.execute_aux(true);
if was_native {
self.overlay.rollback_transaction().expect(PROOF_CLOSE_TRANSACTION);
let (wasm_result, _) = self.execute_aux(false);
if (result.is_ok() &&
wasm_result.is_ok() && result.as_ref().ok() == wasm_result.as_ref().ok()) ||
result.is_err() && wasm_result.is_err()
{
result
} else {
on_consensus_failure(wasm_result, result)
}
} else {
self.overlay.commit_transaction().expect(PROOF_CLOSE_TRANSACTION);
result
}
}
fn execute_call_with_native_else_wasm_strategy(&mut self) -> CallResult<Exec::Error> {
self.overlay.start_transaction();
let (result, was_native) = self.execute_aux(true);
if !was_native || result.is_ok() {
self.overlay.commit_transaction().expect(PROOF_CLOSE_TRANSACTION);
result
} else {
self.overlay.rollback_transaction().expect(PROOF_CLOSE_TRANSACTION);
self.execute_aux(false).0
}
}
/// Execute a call using the given state backend, overlayed changes, and call executor.
///
/// On an error, no prospective changes are written to the overlay.
///
/// Note: changes to code will be in place if this call is made again. For running partial
/// blocks (e.g. a transaction at a time), ensure a different method is used.
///
/// Returns the result of the executed function either in native representation `R` or
/// in SCALE encoded representation.
pub fn execute_using_consensus_failure_handler<Handler>(
&mut self,
manager: ExecutionManager<Handler>,
) -> Result<Vec<u8>, Box<dyn Error>>
where
Handler:
FnOnce(CallResult<Exec::Error>, CallResult<Exec::Error>) -> CallResult<Exec::Error>,
{
let result = {
match manager {
ExecutionManager::Both(on_consensus_failure) =>
self.execute_call_with_both_strategy(on_consensus_failure),
ExecutionManager::NativeElseWasm =>
self.execute_call_with_native_else_wasm_strategy(),
ExecutionManager::AlwaysWasm(trust_level) => {
let _abort_guard = match trust_level {
BackendTrustLevel::Trusted => None,
BackendTrustLevel::Untrusted =>
Some(sp_panic_handler::AbortGuard::never_abort()),
};
self.execute_aux(false).0
},
ExecutionManager::NativeWhenPossible => self.execute_aux(true).0,
}
};
result.map_err(|e| Box::new(e) as _)
}
}
/// Prove execution using the given state backend, overlayed changes, and call executor.
pub fn prove_execution<B, H, Exec, Spawn>(
backend: &mut B,
overlay: &mut OverlayedChanges,
exec: &Exec,
spawn_handle: Spawn,
method: &str,
call_data: &[u8],
runtime_code: &RuntimeCode,
) -> Result<(Vec<u8>, StorageProof), Box<dyn Error>>
where
B: AsTrieBackend<H>,
H: Hasher,
H::Out: Ord + 'static + codec::Codec,
Exec: CodeExecutor + Clone + 'static,
Spawn: SpawnNamed + Send + 'static,
{
let trie_backend = backend.as_trie_backend();
prove_execution_on_trie_backend::<_, _, _, _>(
trie_backend,
overlay,
exec,
spawn_handle,
method,
call_data,
runtime_code,
Default::default(),
)
}
/// Prove execution using the given trie backend, overlayed changes, and call executor.
/// Produces a state-backend-specific "transaction" which can be used to apply the changes
/// to the backing store, such as the disk.
/// Execution proof is the set of all 'touched' storage DBValues from the backend.
///
/// On an error, no prospective changes are written to the overlay.
///
/// Note: changes to code will be in place if this call is made again. For running partial
/// blocks (e.g. a transaction at a time), ensure a different method is used.
pub fn prove_execution_on_trie_backend<S, H, Exec, Spawn>(
trie_backend: &TrieBackend<S, H>,
overlay: &mut OverlayedChanges,
exec: &Exec,
spawn_handle: Spawn,
method: &str,
call_data: &[u8],
runtime_code: &RuntimeCode,
extensions: Extensions,
) -> Result<(Vec<u8>, StorageProof), Box<dyn Error>>
where
S: trie_backend_essence::TrieBackendStorage<H>,
H: Hasher,
H::Out: Ord + 'static + codec::Codec,
Exec: CodeExecutor + 'static + Clone,
Spawn: SpawnNamed + Send + 'static,
{
let proving_backend =
TrieBackendBuilder::wrap(trie_backend).with_recorder(Default::default()).build();
let result = StateMachine::<_, H, Exec>::new(
&proving_backend,
overlay,
exec,
method,
call_data,
extensions,
runtime_code,
spawn_handle,
CallContext::Offchain,
)
.execute_using_consensus_failure_handler::<_>(always_wasm())?;
let proof = proving_backend
.extract_proof()
.expect("A recorder was set and thus, a storage proof can be extracted; qed");
Ok((result, proof))
}
/// Check execution proof, generated by `prove_execution` call.
pub fn execution_proof_check<H, Exec, Spawn>(
root: H::Out,
proof: StorageProof,
overlay: &mut OverlayedChanges,
exec: &Exec,
spawn_handle: Spawn,
method: &str,
call_data: &[u8],
runtime_code: &RuntimeCode,
) -> Result<Vec<u8>, Box<dyn Error>>
where
H: Hasher + 'static,
Exec: CodeExecutor + Clone + 'static,
H::Out: Ord + 'static + codec::Codec,
Spawn: SpawnNamed + Send + 'static,
{
let trie_backend = create_proof_check_backend::<H>(root, proof)?;
execution_proof_check_on_trie_backend::<_, _, _>(
&trie_backend,
overlay,
exec,
spawn_handle,
method,
call_data,
runtime_code,
)
}
/// Check execution proof on proving backend, generated by `prove_execution` call.
pub fn execution_proof_check_on_trie_backend<H, Exec, Spawn>(
trie_backend: &TrieBackend<MemoryDB<H>, H>,
overlay: &mut OverlayedChanges,
exec: &Exec,
spawn_handle: Spawn,
method: &str,
call_data: &[u8],
runtime_code: &RuntimeCode,
) -> Result<Vec<u8>, Box<dyn Error>>
where
H: Hasher,
H::Out: Ord + 'static + codec::Codec,
Exec: CodeExecutor + Clone + 'static,
Spawn: SpawnNamed + Send + 'static,
{
StateMachine::<_, H, Exec>::new(
trie_backend,
overlay,
exec,
method,
call_data,
Extensions::default(),
runtime_code,
spawn_handle,
CallContext::Offchain,
)
.execute_using_consensus_failure_handler(always_untrusted_wasm())
}
/// Generate storage read proof.
pub fn prove_read<B, H, I>(backend: B, keys: I) -> Result<StorageProof, Box<dyn Error>>
where
B: AsTrieBackend<H>,
H: Hasher,
H::Out: Ord + Codec,
I: IntoIterator,
I::Item: AsRef<[u8]>,
{
let trie_backend = backend.as_trie_backend();
prove_read_on_trie_backend(trie_backend, keys)
}
/// State machine only allows a single level
/// of child trie.
pub const MAX_NESTED_TRIE_DEPTH: usize = 2;
/// Multiple key value state.
/// States are ordered by root storage key.
#[derive(PartialEq, Eq, Clone)]
pub struct KeyValueStates(pub Vec<KeyValueStorageLevel>);
/// A key value state at any storage level.
#[derive(PartialEq, Eq, Clone)]
pub struct KeyValueStorageLevel {
/// State root of the level, for
/// top trie it is as an empty byte array.
pub state_root: Vec<u8>,
/// Storage of parents, empty for top root or
/// when exporting (building proof).
pub parent_storage_keys: Vec<Vec<u8>>,
/// Pair of key and values from this state.
pub key_values: Vec<(Vec<u8>, Vec<u8>)>,
}
impl<I> From<I> for KeyValueStates
where
I: IntoIterator<Item = (Vec<u8>, (Vec<(Vec<u8>, Vec<u8>)>, Vec<Vec<u8>>))>,
{
fn from(b: I) -> Self {
let mut result = Vec::new();
for (state_root, (key_values, storage_paths)) in b.into_iter() {
result.push(KeyValueStorageLevel {
state_root,
key_values,
parent_storage_keys: storage_paths,
})
}
KeyValueStates(result)
}
}
impl KeyValueStates {
/// Return total number of key values in states.
pub fn len(&self) -> usize {
self.0.iter().fold(0, |nb, state| nb + state.key_values.len())
}
/// Update last keys accessed from this state.
pub fn update_last_key(
&self,
stopped_at: usize,
last: &mut SmallVec<[Vec<u8>; 2]>,
) -> bool {
if stopped_at == 0 || stopped_at > MAX_NESTED_TRIE_DEPTH {
return false
}
match stopped_at {
1 => {
let top_last =
self.0.get(0).and_then(|s| s.key_values.last().map(|kv| kv.0.clone()));
if let Some(top_last) = top_last {
match last.len() {
0 => {
last.push(top_last);
return true
},
2 => {
last.pop();
},
_ => (),
}
// update top trie access.
last[0] = top_last;
return true
} else {
// No change in top trie accesses.
// Indicates end of reading of a child trie.
last.truncate(1);
return true
}
},
2 => {
let top_last =
self.0.get(0).and_then(|s| s.key_values.last().map(|kv| kv.0.clone()));
let child_last =
self.0.last().and_then(|s| s.key_values.last().map(|kv| kv.0.clone()));
if let Some(child_last) = child_last {
if last.is_empty() {
if let Some(top_last) = top_last {
last.push(top_last)
} else {
return false
}
} else if let Some(top_last) = top_last {
last[0] = top_last;
}
if last.len() == 2 {
last.pop();
}
last.push(child_last);
return true
} else {
// stopped at level 2 so child last is define.
return false
}
},
_ => (),
}
false
}
}
/// Generate range storage read proof, with child tries
/// content.
/// A size limit is applied to the proof with the
/// exception that `start_at` and its following element
/// are always part of the proof.
/// If a key different than `start_at` is a child trie root,
/// the child trie content will be included in the proof.
pub fn prove_range_read_with_child_with_size<B, H>(
backend: B,
size_limit: usize,
start_at: &[Vec<u8>],
) -> Result<(StorageProof, u32), Box<dyn Error>>
where
B: AsTrieBackend<H>,
H: Hasher,
H::Out: Ord + Codec,
{
let trie_backend = backend.as_trie_backend();
prove_range_read_with_child_with_size_on_trie_backend(trie_backend, size_limit, start_at)
}
/// Generate range storage read proof, with child tries
/// content.
/// See `prove_range_read_with_child_with_size`.
pub fn prove_range_read_with_child_with_size_on_trie_backend<S, H>(
trie_backend: &TrieBackend<S, H>,
size_limit: usize,
start_at: &[Vec<u8>],
) -> Result<(StorageProof, u32), Box<dyn Error>>
where
S: trie_backend_essence::TrieBackendStorage<H>,
H: Hasher,
H::Out: Ord + Codec,
{
if start_at.len() > MAX_NESTED_TRIE_DEPTH {
return Err(Box::new("Invalid start of range."))
}
let recorder = sp_trie::recorder::Recorder::default();
let proving_backend =
TrieBackendBuilder::wrap(trie_backend).with_recorder(recorder.clone()).build();
let mut count = 0;
let mut child_roots = HashSet::new();
let (mut child_key, mut start_at) = if start_at.len() == 2 {
let storage_key = start_at.get(0).expect("Checked length.").clone();
if let Some(state_root) = proving_backend
.storage(&storage_key)
.map_err(|e| Box::new(e) as Box<dyn Error>)?
{
child_roots.insert(state_root);
} else {
return Err(Box::new("Invalid range start child trie key."))
}
(Some(storage_key), start_at.get(1).cloned())
} else {
(None, start_at.get(0).cloned())
};
loop {
let (child_info, depth) = if let Some(storage_key) = child_key.as_ref() {
let storage_key = PrefixedStorageKey::new_ref(storage_key);
(
Some(match ChildType::from_prefixed_key(storage_key) {
Some((ChildType::ParentKeyId, storage_key)) =>
ChildInfo::new_default(storage_key),
None => return Err(Box::new("Invalid range start child trie key.")),
}),
2,
)
} else {
(None, 1)
};
let start_at_ref = start_at.as_ref().map(AsRef::as_ref);
let mut switch_child_key = None;
let mut iter = proving_backend
.pairs(IterArgs {
child_info,
start_at: start_at_ref,
start_at_exclusive: true,
..IterArgs::default()
})
.map_err(|e| Box::new(e) as Box<dyn Error>)?;
while let Some(item) = iter.next() {
let (key, value) = item.map_err(|e| Box::new(e) as Box<dyn Error>)?;
if depth < MAX_NESTED_TRIE_DEPTH &&
sp_core::storage::well_known_keys::is_child_storage_key(key.as_slice())
{
count += 1;
// do not add two child trie with same root
if !child_roots.contains(value.as_slice()) {
child_roots.insert(value);
switch_child_key = Some(key);
break
}
} else if recorder.estimate_encoded_size() <= size_limit {
count += 1;
} else {
break
}
}
let completed = iter.was_complete();
if switch_child_key.is_none() {
if depth == 1 {
break
} else if completed {
start_at = child_key.take();
} else {
break
}
} else {
child_key = switch_child_key;
start_at = None;
}
}
let proof = proving_backend
.extract_proof()
.expect("A recorder was set and thus, a storage proof can be extracted; qed");
Ok((proof, count))
}
/// Generate range storage read proof.
pub fn prove_range_read_with_size<B, H>(
backend: B,
child_info: Option<&ChildInfo>,
prefix: Option<&[u8]>,
size_limit: usize,
start_at: Option<&[u8]>,
) -> Result<(StorageProof, u32), Box<dyn Error>>
where
B: AsTrieBackend<H>,
H: Hasher,
H::Out: Ord + Codec,
{
let trie_backend = backend.as_trie_backend();
prove_range_read_with_size_on_trie_backend(
trie_backend,
child_info,
prefix,
size_limit,
start_at,
)
}
/// Generate range storage read proof on an existing trie backend.
pub fn prove_range_read_with_size_on_trie_backend<S, H>(
trie_backend: &TrieBackend<S, H>,
child_info: Option<&ChildInfo>,
prefix: Option<&[u8]>,
size_limit: usize,
start_at: Option<&[u8]>,
) -> Result<(StorageProof, u32), Box<dyn Error>>
where
S: trie_backend_essence::TrieBackendStorage<H>,
H: Hasher,
H::Out: Ord + Codec,
{
let recorder = sp_trie::recorder::Recorder::default();
let proving_backend =
TrieBackendBuilder::wrap(trie_backend).with_recorder(recorder.clone()).build();
let mut count = 0;
let iter = proving_backend
// NOTE: Even though the loop below doesn't use these values
// this *must* fetch both the keys and the values so that
// the proof is correct.
.pairs(IterArgs {
child_info: child_info.cloned(),
prefix,
start_at,
..IterArgs::default()
})
.map_err(|e| Box::new(e) as Box<dyn Error>)?;
for item in iter {
item.map_err(|e| Box::new(e) as Box<dyn Error>)?;
if count == 0 || recorder.estimate_encoded_size() <= size_limit {
count += 1;
} else {
break
}
}
let proof = proving_backend
.extract_proof()
.expect("A recorder was set and thus, a storage proof can be extracted; qed");
Ok((proof, count))
}
/// Generate child storage read proof.
pub fn prove_child_read<B, H, I>(
backend: B,
child_info: &ChildInfo,
keys: I,
) -> Result<StorageProof, Box<dyn Error>>
where
B: AsTrieBackend<H>,
H: Hasher,
H::Out: Ord + Codec,
I: IntoIterator,
I::Item: AsRef<[u8]>,
{
let trie_backend = backend.as_trie_backend();
prove_child_read_on_trie_backend(trie_backend, child_info, keys)
}
/// Generate storage read proof on pre-created trie backend.
pub fn prove_read_on_trie_backend<S, H, I>(
trie_backend: &TrieBackend<S, H>,
keys: I,
) -> Result<StorageProof, Box<dyn Error>>
where
S: trie_backend_essence::TrieBackendStorage<H>,
H: Hasher,
H::Out: Ord + Codec,
I: IntoIterator,
I::Item: AsRef<[u8]>,
{
let proving_backend =
TrieBackendBuilder::wrap(trie_backend).with_recorder(Default::default()).build();