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
/
mod.rs
3399 lines (3004 loc) · 90.6 KB
/
mod.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.
//! This module provides a means for executing contracts
//! represented in wasm.
mod prepare;
mod runtime;
#[cfg(doc)]
pub use crate::wasm::runtime::api_doc;
#[cfg(test)]
pub use tests::MockExt;
pub use crate::wasm::{
prepare::TryInstantiate,
runtime::{
AllowDeprecatedInterface, AllowUnstableInterface, CallFlags, Environment, ReturnCode,
Runtime, RuntimeCosts,
},
};
use crate::{
exec::{ExecResult, Executable, ExportedFunction, Ext},
gas::{GasMeter, Token},
weights::WeightInfo,
AccountIdOf, BadOrigin, BalanceOf, CodeHash, CodeInfoOf, CodeVec, Config, Error, Event, Pallet,
PristineCode, Schedule, Weight, LOG_TARGET,
};
use codec::{Decode, Encode, MaxEncodedLen};
use frame_support::{
dispatch::{DispatchError, DispatchResult},
ensure,
traits::ReservableCurrency,
};
use sp_core::Get;
use sp_runtime::{traits::Hash, RuntimeDebug};
use sp_std::prelude::*;
use wasmi::{
Config as WasmiConfig, Engine, FuelConsumptionMode, Instance, Linker, Memory, MemoryType,
Module, StackLimits, Store,
};
/// Validated Wasm module ready for execution.
/// This data structure is immutable once created and stored.
#[derive(Encode, Decode, scale_info::TypeInfo)]
#[codec(mel_bound())]
#[scale_info(skip_type_params(T))]
pub struct WasmBlob<T: Config> {
code: CodeVec<T>,
// This isn't needed for contract execution and is not stored alongside it.
#[codec(skip)]
pub code_info: CodeInfo<T>,
}
/// Contract code related data, such as:
///
/// - owner of the contract, i.e. account uploaded its code,
/// - storage deposit amount,
/// - reference count,
/// - determinism marker.
///
/// It is stored in a separate storage entry to avoid loading the code when not necessary.
#[derive(Clone, Encode, Decode, scale_info::TypeInfo, MaxEncodedLen)]
#[codec(mel_bound())]
#[scale_info(skip_type_params(T))]
pub struct CodeInfo<T: Config> {
/// The account that has uploaded the contract code and hence is allowed to remove it.
owner: AccountIdOf<T>,
/// The amount of balance that was deposited by the owner in order to store it on-chain.
#[codec(compact)]
deposit: BalanceOf<T>,
/// The number of instantiated contracts that use this as their code.
#[codec(compact)]
refcount: u64,
/// Marks if the code might contain non-deterministic features and is therefore never allowed
/// to be run on-chain. Specifically, such a code can never be instantiated into a contract
/// and can just be used through a delegate call.
determinism: Determinism,
}
/// Defines the required determinism level of a wasm blob when either running or uploading code.
#[derive(
Clone, Copy, Encode, Decode, scale_info::TypeInfo, MaxEncodedLen, RuntimeDebug, PartialEq, Eq,
)]
pub enum Determinism {
/// The execution should be deterministic and hence no indeterministic instructions are
/// allowed.
///
/// Dispatchables always use this mode in order to make on-chain execution deterministic.
Enforced,
/// Allow calling or uploading an indeterministic code.
///
/// This is only possible when calling into `pallet-contracts` directly via
/// [`crate::Pallet::bare_call`].
///
/// # Note
///
/// **Never** use this mode for on-chain execution.
Relaxed,
}
impl ExportedFunction {
/// The wasm export name for the function.
fn identifier(&self) -> &str {
match self {
Self::Constructor => "deploy",
Self::Call => "call",
}
}
}
/// Costs for operations that are related to code handling.
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
#[derive(Clone, Copy)]
enum CodeToken {
/// Weight for loading a contract per byte.
Load(u32),
}
impl<T: Config> Token<T> for CodeToken {
fn weight(&self) -> Weight {
use self::CodeToken::*;
// In case of `Load` we already covered the general costs of
// calling the storage but still need to account for the actual size of the
// contract code. This is why we subtract `T::*::(0)`. We need to do this at this
// point because when charging the general weight for calling the contract we don't know the
// size of the contract.
match *self {
Load(len) => T::WeightInfo::call_with_code_per_byte(len)
.saturating_sub(T::WeightInfo::call_with_code_per_byte(0)),
}
}
}
impl<T: Config> WasmBlob<T> {
/// Create the module by checking the `code`.
///
/// This does **not** store the module. For this one need to either call [`Self::store`]
/// or [`<Self as Executable>::execute`][`Executable::execute`].
pub fn from_code(
code: Vec<u8>,
schedule: &Schedule<T>,
owner: AccountIdOf<T>,
determinism: Determinism,
try_instantiate: TryInstantiate,
) -> Result<Self, (DispatchError, &'static str)> {
prepare::prepare::<runtime::Env, T>(
code.try_into().map_err(|_| (<Error<T>>::CodeTooLarge.into(), ""))?,
schedule,
owner,
determinism,
try_instantiate,
)
}
/// Store the code without instantiating it.
///
/// Otherwise the code is stored when [`<Self as Executable>::execute`][`Executable::execute`]
/// is called.
pub fn store(self) -> DispatchResult {
Self::store_code(self, false)
}
/// Remove the code from storage and refund the deposit to its owner.
///
/// Applies all necessary checks before removing the code.
pub fn remove(origin: &T::AccountId, code_hash: CodeHash<T>) -> DispatchResult {
Self::try_remove_code(origin, code_hash)
}
/// Returns whether there is a deposit to be paid for this module.
///
/// Returns `0` if the module is already in storage and hence no deposit will
/// be charged when storing it.
pub fn open_deposit(&self, code_info: CodeInfo<T>) -> BalanceOf<T> {
<CodeInfoOf<T>>::try_get(self.code_hash()).map_or(code_info.deposit, |_| 0u32.into())
}
/// Creates and returns an instance of the supplied code.
///
/// This is either used for later executing a contract or for validation of a contract.
/// When validating we pass `()` as `host_state`. Please note that such a dummy instance must
/// **never** be called/executed, since it will panic the executor.
pub fn instantiate<E, H>(
code: &[u8],
host_state: H,
memory_limits: (u32, u32),
stack_limits: StackLimits,
allow_deprecated: AllowDeprecatedInterface,
) -> Result<(Store<H>, Memory, Instance), wasmi::Error>
where
E: Environment<H>,
{
let mut config = WasmiConfig::default();
config
.set_stack_limits(stack_limits)
.wasm_multi_value(false)
.wasm_mutable_global(false)
.wasm_sign_extension(false)
.wasm_saturating_float_to_int(false)
.consume_fuel(true)
.fuel_consumption_mode(FuelConsumptionMode::Eager);
let engine = Engine::new(&config);
let module = Module::new(&engine, code.clone())?;
let mut store = Store::new(&engine, host_state);
let mut linker = Linker::new(&engine);
E::define(
&mut store,
&mut linker,
if T::UnsafeUnstableInterface::get() {
AllowUnstableInterface::Yes
} else {
AllowUnstableInterface::No
},
allow_deprecated,
)?;
// Here we allocate this memory in the _store_. It allocates _inital_ value, but allows it
// to grow up to maximum number of memory pages, if neccesary.
let memory =
Memory::new(&mut store, MemoryType::new(memory_limits.0, Some(memory_limits.1))?)
.expect(
"We checked the limits versus our `Schedule`,
which specifies the max amount of memory pages
well below u16::MAX; qed",
);
linker
.define("env", "memory", memory)
.expect("We just created the linker. It has no define with this name attached; qed");
let instance = linker.instantiate(&mut store, &module)?.ensure_no_start(&mut store)?;
Ok((store, memory, instance))
}
/// Put the module blob into storage.
///
/// Increments the reference count of the in-storage `WasmBlob`, if it already exists in
/// storage.
fn store_code(mut module: Self, instantiated: bool) -> DispatchResult {
let code_hash = &module.code_hash();
<CodeInfoOf<T>>::mutate(code_hash, |stored_code_info| {
match stored_code_info {
// Instantiate existing contract.
Some(stored_code_info) if instantiated => {
stored_code_info.refcount = stored_code_info.refcount.checked_add(1).expect(
"
refcount is 64bit. Generating this overflow would require to store
_at least_ 18 exabyte of data assuming that a contract consumes only
one byte of data. Any node would run out of storage space before hitting
this overflow;
qed
",
);
Ok(())
},
// Contract code is already stored in storage. Nothing to be done here.
Some(_) => Ok(()),
// Upload a new contract code.
//
// We need to store the code and its code_info, and collect the deposit.
None => {
// This `None` case happens only in freshly uploaded modules. This means that
// the `owner` is always the origin of the current transaction.
T::Currency::reserve(&module.code_info.owner, module.code_info.deposit)
.map_err(|_| <Error<T>>::StorageDepositNotEnoughFunds)?;
module.code_info.refcount = if instantiated { 1 } else { 0 };
<PristineCode<T>>::insert(code_hash, module.code);
*stored_code_info = Some(module.code_info);
<Pallet<T>>::deposit_event(
vec![*code_hash],
Event::CodeStored { code_hash: *code_hash },
);
Ok(())
},
}
})
}
/// Try to remove code together with all associated information.
fn try_remove_code(origin: &T::AccountId, code_hash: CodeHash<T>) -> DispatchResult {
<CodeInfoOf<T>>::try_mutate_exists(&code_hash, |existing| {
if let Some(code_info) = existing {
ensure!(code_info.refcount == 0, <Error<T>>::CodeInUse);
ensure!(&code_info.owner == origin, BadOrigin); // TODO: what if origin is root?
T::Currency::unreserve(&code_info.owner, code_info.deposit);
*existing = None;
<PristineCode<T>>::remove(&code_hash);
<Pallet<T>>::deposit_event(vec![code_hash], Event::CodeRemoved { code_hash });
Ok(())
} else {
Err(<Error<T>>::CodeNotFound.into())
}
})
}
/// Load code with the given code hash.
fn load_code(
code_hash: CodeHash<T>,
gas_meter: &mut GasMeter<T>,
) -> Result<CodeVec<T>, DispatchError> {
let max_code_len = T::MaxCodeLen::get();
let charged = gas_meter.charge(CodeToken::Load(max_code_len))?;
let code = <PristineCode<T>>::get(code_hash).ok_or(Error::<T>::CodeNotFound)?;
let code_len = code.len() as u32;
gas_meter.adjust_gas(charged, CodeToken::Load(code_len));
Ok(code)
}
/// Decrement the reference count of a stored code by one.
///
/// # Note
///
/// A contract whose reference count dropped to zero isn't automatically removed. A
/// `remove_code` transaction must be submitted by the original uploader to do so.
fn decrement_refcount(code_hash: CodeHash<T>) {
<CodeInfoOf<T>>::mutate(code_hash, |existing| {
if let Some(info) = existing {
info.refcount = info.refcount.saturating_sub(1);
}
});
}
/// Increment the reference count of a of a stored code by one.
///
/// # Errors
///
/// [`Error::CodeNotFound`] is returned if no stored code found having the specified
/// `code_hash`.
fn increment_refcount(code_hash: CodeHash<T>) -> Result<(), DispatchError> {
<CodeInfoOf<T>>::mutate(code_hash, |existing| -> Result<(), DispatchError> {
if let Some(info) = existing {
info.refcount = info.refcount.saturating_add(1);
Ok(())
} else {
Err(Error::<T>::CodeNotFound.into())
}
})
}
/// See [`Self::from_code_unchecked`].
#[cfg(feature = "runtime-benchmarks")]
pub fn store_code_unchecked(
code: Vec<u8>,
schedule: &Schedule<T>,
owner: T::AccountId,
) -> DispatchResult {
let executable = Self::from_code_unchecked(code, schedule, owner)?;
Self::store_code(executable, false)
}
/// Create the module without checking the passed code.
///
/// # Note
///
/// This is useful for benchmarking where we don't want validation of the module to skew
/// our results. This also does not collect any deposit from the `owner`. Also useful
/// during testing when we want to deploy codes that do not pass the instantiation checks.
#[cfg(any(test, feature = "runtime-benchmarks"))]
fn from_code_unchecked(
code: Vec<u8>,
schedule: &Schedule<T>,
owner: T::AccountId,
) -> Result<Self, DispatchError> {
prepare::benchmarking::prepare(code, schedule, owner)
.map_err::<DispatchError, _>(Into::into)
}
}
impl<T: Config> CodeInfo<T> {
/// Return the refcount of the module.
#[cfg(test)]
pub fn refcount(&self) -> u64 {
self.refcount
}
}
impl<T: Config> Executable<T> for WasmBlob<T> {
fn from_storage(
code_hash: CodeHash<T>,
_schedule: &Schedule<T>,
gas_meter: &mut GasMeter<T>,
) -> Result<Self, DispatchError> {
let code = Self::load_code(code_hash, gas_meter)?;
let code_hash = T::Hashing::hash(&code);
// We store `code_info` at the same time as contract code,
// therefore this query shouldn't really fail.
// We consider its failure equal to `CodeNotFound`, as contract code without
// `code_info` is unusable in this pallet.
let code_info = <CodeInfoOf<T>>::get(code_hash).ok_or(Error::<T>::CodeNotFound)?;
Ok(Self { code, code_info })
}
fn add_user(code_hash: CodeHash<T>) -> Result<(), DispatchError> {
Self::increment_refcount(code_hash)
}
fn remove_user(code_hash: CodeHash<T>) {
Self::decrement_refcount(code_hash)
}
fn execute<E: Ext<T = T>>(
self,
ext: &mut E,
function: &ExportedFunction,
input_data: Vec<u8>,
) -> ExecResult {
let code = self.code.as_slice();
let contract_module = prepare::ContractModule::new(code)?;
// Extract memory limits from the module.
// This also checks that module's memory import satisfies the schedule.
let memory_limits =
prepare::get_memory_limits(contract_module.scan_imports::<T>(&[])?, ext.schedule())?;
// Instantiate the Wasm module to the engine.
let runtime = Runtime::new(ext, input_data);
let (mut store, memory, instance) = Self::instantiate::<crate::wasm::runtime::Env, _>(
code,
runtime,
memory_limits,
StackLimits::default(),
match function {
ExportedFunction::Call => AllowDeprecatedInterface::Yes,
ExportedFunction::Constructor => AllowDeprecatedInterface::No,
},
)
.map_err(|msg| {
log::debug!(target: LOG_TARGET, "failed to instantiate code: {}", msg);
Error::<T>::CodeRejected
})?;
store.data_mut().set_memory(memory);
// Set fuel limit for the wasmi execution.
// We normalize it by the base instruction weight, as its cost in wasmi engine is `1`.
let fuel_limit = store
.data_mut()
.ext()
.gas_meter_mut()
.gas_left()
.ref_time()
.checked_div(T::Schedule::get().instruction_weights.base as u64)
.ok_or(Error::<T>::InvalidSchedule)?;
store
.add_fuel(fuel_limit)
.expect("We've set up engine to fuel consuming mode; qed");
let exported_func = instance
.get_export(&store, function.identifier())
.and_then(|export| export.into_func())
.ok_or_else(|| {
log::error!(target: LOG_TARGET, "failed to find entry point");
Error::<T>::CodeRejected
})?;
// We store before executing so that the code hash is available in the constructor.
if let &ExportedFunction::Constructor = function {
Self::store_code(self, true)?;
}
let result = exported_func.call(&mut store, &[], &mut []);
let engine_consumed_total = store.fuel_consumed().expect("Fuel metering is enabled; qed");
// Sync this frame's gas meter with the engine's one.
let gas_meter = store.data_mut().ext().gas_meter_mut();
gas_meter.sync_fuel(engine_consumed_total)?;
store.into_data().to_execution_result(result)
}
fn code_hash(&self) -> CodeHash<T> {
T::Hashing::hash(&self.code)
}
fn code_len(&self) -> u32 {
self.code.len() as u32
}
fn is_deterministic(&self) -> bool {
matches!(self.code_info.determinism, Determinism::Enforced)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
exec::{AccountIdOf, BlockNumberOf, ErrorOrigin, ExecError, Executable, Ext, Key, SeedOf},
gas::GasMeter,
storage::WriteOutcome,
tests::{RuntimeCall, Test, ALICE, BOB},
BalanceOf, CodeHash, Error, Origin, Pallet as Contracts,
};
use assert_matches::assert_matches;
use frame_support::{
assert_err, assert_ok, dispatch::DispatchResultWithPostInfo, weights::Weight,
};
use pallet_contracts_primitives::{ExecReturnValue, ReturnFlags};
use pretty_assertions::assert_eq;
use sp_core::H256;
use sp_runtime::DispatchError;
use std::{
borrow::BorrowMut,
cell::RefCell,
collections::hash_map::{Entry, HashMap},
};
#[derive(Debug, PartialEq, Eq)]
struct InstantiateEntry {
code_hash: H256,
value: u64,
data: Vec<u8>,
gas_left: u64,
salt: Vec<u8>,
}
#[derive(Debug, PartialEq, Eq)]
struct TerminationEntry {
beneficiary: AccountIdOf<Test>,
}
#[derive(Debug, PartialEq, Eq)]
struct TransferEntry {
to: AccountIdOf<Test>,
value: u64,
}
#[derive(Debug, PartialEq, Eq)]
struct CallEntry {
to: AccountIdOf<Test>,
value: u64,
data: Vec<u8>,
allows_reentry: bool,
}
#[derive(Debug, PartialEq, Eq)]
struct CallCodeEntry {
code_hash: H256,
data: Vec<u8>,
}
pub struct MockExt {
storage: HashMap<Vec<u8>, Vec<u8>>,
instantiates: Vec<InstantiateEntry>,
terminations: Vec<TerminationEntry>,
calls: Vec<CallEntry>,
code_calls: Vec<CallCodeEntry>,
transfers: Vec<TransferEntry>,
// (topics, data)
events: Vec<(Vec<H256>, Vec<u8>)>,
runtime_calls: RefCell<Vec<RuntimeCall>>,
schedule: Schedule<Test>,
gas_meter: GasMeter<Test>,
debug_buffer: Vec<u8>,
ecdsa_recover: RefCell<Vec<([u8; 65], [u8; 32])>>,
sr25519_verify: RefCell<Vec<([u8; 64], Vec<u8>, [u8; 32])>>,
code_hashes: Vec<CodeHash<Test>>,
caller: Origin<Test>,
}
/// The call is mocked and just returns this hardcoded value.
fn call_return_data() -> Vec<u8> {
vec![0xDE, 0xAD, 0xBE, 0xEF]
}
impl Default for MockExt {
fn default() -> Self {
Self {
code_hashes: Default::default(),
storage: Default::default(),
instantiates: Default::default(),
terminations: Default::default(),
calls: Default::default(),
code_calls: Default::default(),
transfers: Default::default(),
events: Default::default(),
runtime_calls: Default::default(),
schedule: Default::default(),
gas_meter: GasMeter::new(Weight::from_parts(10_000_000_000, 10 * 1024 * 1024)),
debug_buffer: Default::default(),
ecdsa_recover: Default::default(),
caller: Default::default(),
sr25519_verify: Default::default(),
}
}
}
impl Ext for MockExt {
type T = Test;
fn call(
&mut self,
_gas_limit: Weight,
_deposit_limit: BalanceOf<Self::T>,
to: AccountIdOf<Self::T>,
value: u64,
data: Vec<u8>,
allows_reentry: bool,
) -> Result<ExecReturnValue, ExecError> {
self.calls.push(CallEntry { to, value, data, allows_reentry });
Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: call_return_data() })
}
fn delegate_call(
&mut self,
code_hash: CodeHash<Self::T>,
data: Vec<u8>,
) -> Result<ExecReturnValue, ExecError> {
self.code_calls.push(CallCodeEntry { code_hash, data });
Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: call_return_data() })
}
fn instantiate(
&mut self,
gas_limit: Weight,
_deposit_limit: BalanceOf<Self::T>,
code_hash: CodeHash<Test>,
value: u64,
data: Vec<u8>,
salt: &[u8],
) -> Result<(AccountIdOf<Self::T>, ExecReturnValue), ExecError> {
self.instantiates.push(InstantiateEntry {
code_hash,
value,
data: data.to_vec(),
gas_left: gas_limit.ref_time(),
salt: salt.to_vec(),
});
Ok((
Contracts::<Test>::contract_address(&ALICE, &code_hash, &data, salt),
ExecReturnValue { flags: ReturnFlags::empty(), data: Vec::new() },
))
}
fn set_code_hash(&mut self, hash: CodeHash<Self::T>) -> Result<(), DispatchError> {
self.code_hashes.push(hash);
Ok(())
}
fn transfer(&mut self, to: &AccountIdOf<Self::T>, value: u64) -> Result<(), DispatchError> {
self.transfers.push(TransferEntry { to: to.clone(), value });
Ok(())
}
fn terminate(&mut self, beneficiary: &AccountIdOf<Self::T>) -> Result<(), DispatchError> {
self.terminations.push(TerminationEntry { beneficiary: beneficiary.clone() });
Ok(())
}
fn get_storage(&mut self, key: &Key<Self::T>) -> Option<Vec<u8>> {
self.storage.get(&key.to_vec()).cloned()
}
fn get_storage_size(&mut self, key: &Key<Self::T>) -> Option<u32> {
self.storage.get(&key.to_vec()).map(|val| val.len() as u32)
}
fn set_storage(
&mut self,
key: &Key<Self::T>,
value: Option<Vec<u8>>,
take_old: bool,
) -> Result<WriteOutcome, DispatchError> {
let key = key.to_vec();
let entry = self.storage.entry(key.clone());
let result = match (entry, take_old) {
(Entry::Vacant(_), _) => WriteOutcome::New,
(Entry::Occupied(entry), false) =>
WriteOutcome::Overwritten(entry.remove().len() as u32),
(Entry::Occupied(entry), true) => WriteOutcome::Taken(entry.remove()),
};
if let Some(value) = value {
self.storage.insert(key, value);
}
Ok(result)
}
fn caller(&self) -> Origin<Self::T> {
self.caller.clone()
}
fn is_contract(&self, _address: &AccountIdOf<Self::T>) -> bool {
true
}
fn code_hash(&self, _address: &AccountIdOf<Self::T>) -> Option<CodeHash<Self::T>> {
Some(H256::from_slice(&[0x11; 32]))
}
fn own_code_hash(&mut self) -> &CodeHash<Self::T> {
const HASH: H256 = H256::repeat_byte(0x10);
&HASH
}
fn caller_is_origin(&self) -> bool {
false
}
fn caller_is_root(&self) -> bool {
&self.caller == &Origin::Root
}
fn address(&self) -> &AccountIdOf<Self::T> {
&BOB
}
fn balance(&self) -> u64 {
228
}
fn value_transferred(&self) -> u64 {
1337
}
fn now(&self) -> &u64 {
&1111
}
fn minimum_balance(&self) -> u64 {
666
}
fn random(&self, subject: &[u8]) -> (SeedOf<Self::T>, BlockNumberOf<Self::T>) {
(H256::from_slice(subject), 42)
}
fn deposit_event(&mut self, topics: Vec<H256>, data: Vec<u8>) {
self.events.push((topics, data))
}
fn block_number(&self) -> u64 {
121
}
fn max_value_size(&self) -> u32 {
16_384
}
fn get_weight_price(&self, weight: Weight) -> BalanceOf<Self::T> {
BalanceOf::<Self::T>::from(1312_u32)
.saturating_mul(weight.ref_time().into())
.saturating_add(
BalanceOf::<Self::T>::from(103_u32).saturating_mul(weight.proof_size()),
)
}
fn schedule(&self) -> &Schedule<Self::T> {
&self.schedule
}
fn gas_meter(&self) -> &GasMeter<Self::T> {
&self.gas_meter
}
fn gas_meter_mut(&mut self) -> &mut GasMeter<Self::T> {
&mut self.gas_meter
}
fn append_debug_buffer(&mut self, msg: &str) -> bool {
self.debug_buffer.extend(msg.as_bytes());
true
}
fn call_runtime(
&self,
call: <Self::T as Config>::RuntimeCall,
) -> DispatchResultWithPostInfo {
self.runtime_calls.borrow_mut().push(call);
Ok(Default::default())
}
fn ecdsa_recover(
&self,
signature: &[u8; 65],
message_hash: &[u8; 32],
) -> Result<[u8; 33], ()> {
self.ecdsa_recover.borrow_mut().push((*signature, *message_hash));
Ok([3; 33])
}
fn sr25519_verify(&self, signature: &[u8; 64], message: &[u8], pub_key: &[u8; 32]) -> bool {
self.sr25519_verify.borrow_mut().push((*signature, message.to_vec(), *pub_key));
true
}
fn contract_info(&mut self) -> &mut crate::ContractInfo<Self::T> {
unimplemented!()
}
fn ecdsa_to_eth_address(&self, _pk: &[u8; 33]) -> Result<[u8; 20], ()> {
Ok([2u8; 20])
}
fn reentrance_count(&self) -> u32 {
12
}
fn account_reentrance_count(&self, _account_id: &AccountIdOf<Self::T>) -> u32 {
12
}
fn nonce(&mut self) -> u64 {
995
}
}
/// Execute the supplied code.
///
/// Not used directly but through the wrapper functions defined below.
fn execute_internal<E: BorrowMut<MockExt>>(
wat: &str,
input_data: Vec<u8>,
mut ext: E,
entry_point: &ExportedFunction,
unstable_interface: bool,
skip_checks: bool,
) -> ExecResult {
type RuntimeConfig = <MockExt as Ext>::T;
RuntimeConfig::set_unstable_interface(unstable_interface);
let wasm = wat::parse_str(wat).unwrap();
let executable = if skip_checks {
WasmBlob::<RuntimeConfig>::from_code_unchecked(
wasm,
ext.borrow_mut().schedule(),
ALICE,
)?
} else {
WasmBlob::<RuntimeConfig>::from_code(
wasm,
ext.borrow_mut().schedule(),
ALICE,
Determinism::Enforced,
TryInstantiate::Instantiate,
)
.map_err(|err| err.0)?
};
executable.execute(ext.borrow_mut(), entry_point, input_data)
}
/// Execute the supplied code.
fn execute<E: BorrowMut<MockExt>>(wat: &str, input_data: Vec<u8>, ext: E) -> ExecResult {
execute_internal(wat, input_data, ext, &ExportedFunction::Call, true, false)
}
/// Execute the supplied code with disabled unstable functions.
///
/// In our test config unstable functions are disabled so that we can test them.
/// In order to test that code using them is properly rejected we temporarily disable
/// them when this test is run.
#[cfg(not(feature = "runtime-benchmarks"))]
fn execute_no_unstable<E: BorrowMut<MockExt>>(
wat: &str,
input_data: Vec<u8>,
ext: E,
) -> ExecResult {
execute_internal(wat, input_data, ext, &ExportedFunction::Call, false, false)
}
/// Execute code without validating it first.
///
/// This is mainly useful in order to test code which uses deprecated functions. Those
/// would fail when validating the code.
fn execute_unvalidated<E: BorrowMut<MockExt>>(
wat: &str,
input_data: Vec<u8>,
ext: E,
) -> ExecResult {
execute_internal(wat, input_data, ext, &ExportedFunction::Call, false, true)
}
/// Execute instantiation entry point of code without validating it first.
///
/// Same as `execute_unvalidated` except that the `deploy` entry point is ran.
#[cfg(not(feature = "runtime-benchmarks"))]
fn execute_instantiate_unvalidated<E: BorrowMut<MockExt>>(
wat: &str,
input_data: Vec<u8>,
ext: E,
) -> ExecResult {
execute_internal(wat, input_data, ext, &ExportedFunction::Constructor, false, true)
}
const CODE_TRANSFER: &str = r#"
(module
;; seal_transfer(
;; account_ptr: u32,
;; account_len: u32,
;; value_ptr: u32,
;; value_len: u32,
;;) -> u32
(import "seal0" "seal_transfer" (func $seal_transfer (param i32 i32 i32 i32) (result i32)))
(import "env" "memory" (memory 1 1))
(func (export "call")
(drop
(call $seal_transfer
(i32.const 4) ;; Pointer to "account" address.
(i32.const 32) ;; Length of "account" address.
(i32.const 36) ;; Pointer to the buffer with value to transfer
(i32.const 8) ;; Length of the buffer with value to transfer.
)
)
)
(func (export "deploy"))
;; Destination AccountId (ALICE)
(data (i32.const 4)
"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
)
;; Amount of value to transfer.
;; Represented by u64 (8 bytes long) in little endian.
(data (i32.const 36) "\99\00\00\00\00\00\00\00")
)
"#;
#[test]
fn contract_transfer() {
let mut mock_ext = MockExt::default();
assert_ok!(execute(CODE_TRANSFER, vec![], &mut mock_ext));
assert_eq!(&mock_ext.transfers, &[TransferEntry { to: ALICE, value: 153 }]);
}
const CODE_CALL: &str = r#"
(module
;; seal_call(
;; callee_ptr: u32,
;; callee_len: u32,
;; gas: u64,
;; value_ptr: u32,
;; value_len: u32,
;; input_data_ptr: u32,
;; input_data_len: u32,
;; output_ptr: u32,
;; output_len_ptr: u32
;;) -> u32
(import "seal0" "seal_call" (func $seal_call (param i32 i32 i64 i32 i32 i32 i32 i32 i32) (result i32)))
(import "env" "memory" (memory 1 1))
(func (export "call")
(drop
(call $seal_call
(i32.const 4) ;; Pointer to "callee" address.
(i32.const 32) ;; Length of "callee" address.
(i64.const 0) ;; How much gas to devote for the execution. 0 = all.
(i32.const 36) ;; Pointer to the buffer with value to transfer
(i32.const 8) ;; Length of the buffer with value to transfer.
(i32.const 44) ;; Pointer to input data buffer address
(i32.const 4) ;; Length of input data buffer
(i32.const 4294967295) ;; u32 max value is the sentinel value: do not copy output
(i32.const 0) ;; Length is ignored in this case
)
)
)
(func (export "deploy"))
;; Destination AccountId (ALICE)
(data (i32.const 4)
"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
)
;; Amount of value to transfer.
;; Represented by u64 (8 bytes long) in little endian.
(data (i32.const 36) "\06\00\00\00\00\00\00\00")
(data (i32.const 44) "\01\02\03\04")
)
"#;
#[test]
fn contract_call() {
let mut mock_ext = MockExt::default();
assert_ok!(execute(CODE_CALL, vec![], &mut mock_ext));
assert_eq!(
&mock_ext.calls,
&[CallEntry { to: ALICE, value: 6, data: vec![1, 2, 3, 4], allows_reentry: true }]
);
}
#[test]
fn contract_delegate_call() {
const CODE: &str = r#"
(module
;; seal_delegate_call(
;; flags: u32,
;; code_hash_ptr: u32,
;; input_data_ptr: u32,
;; input_data_len: u32,
;; output_ptr: u32,
;; output_len_ptr: u32
;;) -> u32
(import "seal0" "seal_delegate_call" (func $seal_delegate_call (param i32 i32 i32 i32 i32 i32) (result i32)))
(import "env" "memory" (memory 1 1))
(func (export "call")
(drop
(call $seal_delegate_call
(i32.const 0) ;; No flags are set
(i32.const 4) ;; Pointer to "callee" code_hash.
(i32.const 36) ;; Pointer to input data buffer address
(i32.const 4) ;; Length of input data buffer
(i32.const 4294967295) ;; u32 max value is the sentinel value: do not copy output
(i32.const 0) ;; Length is ignored in this case
)
)
)
(func (export "deploy"))
;; Callee code_hash
(data (i32.const 4)
"\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11"
"\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11"
)
(data (i32.const 36) "\01\02\03\04")
)
"#;
let mut mock_ext = MockExt::default();
assert_ok!(execute(CODE, vec![], &mut mock_ext));