This repository was archived by the owner on May 22, 2023. It is now read-only.
forked from paritytech/substrate
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathexec.rs
More file actions
1470 lines (1273 loc) · 41.2 KB
/
exec.rs
File metadata and controls
1470 lines (1273 loc) · 41.2 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
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) 2018-2021 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.
use crate::{
CodeHash, ConfigCache, Event, RawEvent, Config, Module as Contracts,
TrieId, BalanceOf, ContractInfo, gas::GasMeter, rent::Rent, storage::{self, Storage},
Error, ContractInfoOf, Schedule,
};
use sp_core::crypto::UncheckedFrom;
use sp_std::{
prelude::*,
marker::PhantomData,
};
use sp_runtime::traits::{Bounded, Zero, Convert, Saturating};
use frame_support::{
dispatch::{DispatchResult, DispatchError},
traits::{ExistenceRequirement, Currency, Time, Randomness},
weights::Weight,
ensure, StorageMap,
};
use pallet_contracts_primitives::{ErrorOrigin, ExecError, ExecReturnValue, ExecResult, ReturnFlags};
pub type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
pub type MomentOf<T> = <<T as Config>::Time as Time>::Moment;
pub type SeedOf<T> = <T as frame_system::Config>::Hash;
pub type BlockNumberOf<T> = <T as frame_system::Config>::BlockNumber;
pub type StorageKey = [u8; 32];
/// A type that represents a topic of an event. At the moment a hash is used.
pub type TopicOf<T> = <T as frame_system::Config>::Hash;
/// Describes whether we deal with a contract or a plain account.
pub enum TransactorKind {
/// Transaction was initiated from a plain account. That can be either be through a
/// signed transaction or through RPC.
PlainAccount,
/// The call was initiated by a contract account.
Contract,
}
/// An interface that provides access to the external environment in which the
/// smart-contract is executed.
///
/// This interface is specialized to an account of the executing code, so all
/// operations are implicitly performed on that account.
pub trait Ext {
type T: Config;
/// Returns the storage entry of the executing account by the given `key`.
///
/// Returns `None` if the `key` wasn't previously set by `set_storage` or
/// was deleted.
fn get_storage(&self, key: &StorageKey) -> Option<Vec<u8>>;
/// Sets the storage entry by the given key to the specified value. If `value` is `None` then
/// the storage entry is deleted.
fn set_storage(&mut self, key: StorageKey, value: Option<Vec<u8>>) -> DispatchResult;
/// Instantiate a contract from the given code.
///
/// The newly created account will be associated with `code`. `value` specifies the amount of value
/// transferred from this to the newly created account (also known as endowment).
fn instantiate(
&mut self,
code: CodeHash<Self::T>,
value: BalanceOf<Self::T>,
gas_meter: &mut GasMeter<Self::T>,
input_data: Vec<u8>,
salt: &[u8],
) -> Result<(AccountIdOf<Self::T>, ExecReturnValue), ExecError>;
/// Transfer some amount of funds into the specified account.
fn transfer(
&mut self,
to: &AccountIdOf<Self::T>,
value: BalanceOf<Self::T>,
) -> DispatchResult;
/// Transfer all funds to `beneficiary` and delete the contract.
///
/// Since this function removes the self contract eagerly, if succeeded, no further actions should
/// be performed on this `Ext` instance.
///
/// This function will fail if the same contract is present on the contract
/// call stack.
fn terminate(
&mut self,
beneficiary: &AccountIdOf<Self::T>,
) -> DispatchResult;
/// Call (possibly transferring some amount of funds) into the specified account.
fn call(
&mut self,
to: &AccountIdOf<Self::T>,
value: BalanceOf<Self::T>,
gas_meter: &mut GasMeter<Self::T>,
input_data: Vec<u8>,
) -> ExecResult;
/// Restores the given destination contract sacrificing the current one.
///
/// Since this function removes the self contract eagerly, if succeeded, no further actions should
/// be performed on this `Ext` instance.
///
/// This function will fail if the same contract is present
/// on the contract call stack.
fn restore_to(
&mut self,
dest: AccountIdOf<Self::T>,
code_hash: CodeHash<Self::T>,
rent_allowance: BalanceOf<Self::T>,
delta: Vec<StorageKey>,
) -> DispatchResult;
/// Returns a reference to the account id of the caller.
fn caller(&self) -> &AccountIdOf<Self::T>;
/// Returns a reference to the account id of the current contract.
fn address(&self) -> &AccountIdOf<Self::T>;
/// Returns the balance of the current contract.
///
/// The `value_transferred` is already added.
fn balance(&self) -> BalanceOf<Self::T>;
/// Returns the value transferred along with this call or as endowment.
fn value_transferred(&self) -> BalanceOf<Self::T>;
/// Returns a reference to the timestamp of the current block
fn now(&self) -> &MomentOf<Self::T>;
/// Returns the minimum balance that is required for creating an account.
fn minimum_balance(&self) -> BalanceOf<Self::T>;
/// Returns the deposit required to create a tombstone upon contract eviction.
fn tombstone_deposit(&self) -> BalanceOf<Self::T>;
/// Returns a random number for the current block with the given subject.
fn random(&self, subject: &[u8]) -> SeedOf<Self::T>;
/// Deposit an event with the given topics.
///
/// There should not be any duplicates in `topics`.
fn deposit_event(&mut self, topics: Vec<TopicOf<Self::T>>, data: Vec<u8>);
/// Set rent allowance of the contract
fn set_rent_allowance(&mut self, rent_allowance: BalanceOf<Self::T>);
/// Rent allowance of the contract
fn rent_allowance(&self) -> BalanceOf<Self::T>;
/// Returns the current block number.
fn block_number(&self) -> BlockNumberOf<Self::T>;
/// Returns the maximum allowed size of a storage item.
fn max_value_size(&self) -> u32;
/// Returns the price for the specified amount of weight.
fn get_weight_price(&self, weight: Weight) -> BalanceOf<Self::T>;
/// Get a reference to the schedule used by the current call.
fn schedule(&self) -> &Schedule<Self::T>;
}
/// Describes the different functions that can be exported by an [`Executable`].
pub enum ExportedFunction {
/// The constructor function which is executed on deployment of a contract.
Constructor,
/// The function which is executed when a contract is called.
Call,
}
/// A trait that represents something that can be executed.
///
/// In the on-chain environment this would be represented by a wasm module. This trait exists in
/// order to be able to mock the wasm logic for testing.
pub trait Executable<T: Config>: Sized {
/// Load the executable from storage.
fn from_storage(code_hash: CodeHash<T>, schedule: &Schedule<T>) -> Result<Self, DispatchError>;
/// Load the module from storage without re-instrumenting it.
///
/// A code module is re-instrumented on-load when it was originally instrumented with
/// an older schedule. This skips this step for cases where the code storage is
/// queried for purposes other than execution.
fn from_storage_noinstr(code_hash: CodeHash<T>) -> Result<Self, DispatchError>;
/// Decrements the refcount by one and deletes the code if it drops to zero.
fn drop_from_storage(self);
/// Increment the refcount by one. Fails if the code does not exist on-chain.
fn add_user(code_hash: CodeHash<T>) -> DispatchResult;
/// Decrement the refcount by one and remove the code when it drops to zero.
fn remove_user(code_hash: CodeHash<T>);
/// Execute the specified exported function and return the result.
///
/// When the specified function is `Constructor` the executable is stored and its
/// refcount incremented.
///
/// # Note
///
/// This functions expects to be executed in a storage transaction that rolls back
/// all of its emitted storage changes.
fn execute<E: Ext<T = T>>(
self,
ext: E,
function: &ExportedFunction,
input_data: Vec<u8>,
gas_meter: &mut GasMeter<T>,
) -> ExecResult;
/// The code hash of the executable.
fn code_hash(&self) -> &CodeHash<T>;
/// The storage that is occupied by the instrumented executable and its pristine source.
///
/// The returned size is already divided by the number of users who share the code.
///
/// # Note
///
/// This works with the current in-memory value of refcount. When calling any contract
/// without refetching this from storage the result can be inaccurate as it might be
/// working with a stale value. Usually this inaccuracy is tolerable.
fn occupied_storage(&self) -> u32;
}
pub struct ExecutionContext<'a, T: Config + 'a, E> {
pub caller: Option<&'a ExecutionContext<'a, T, E>>,
pub self_account: T::AccountId,
pub self_trie_id: Option<TrieId>,
pub depth: usize,
pub config: &'a ConfigCache<T>,
pub timestamp: MomentOf<T>,
pub block_number: T::BlockNumber,
_phantom: PhantomData<E>,
}
impl<'a, T, E> ExecutionContext<'a, T, E>
where
T: Config,
T::AccountId: UncheckedFrom<T::Hash> + AsRef<[u8]>,
E: Executable<T>,
{
/// Create the top level execution context.
///
/// The specified `origin` address will be used as `sender` for. The `origin` must be a regular
/// account (not a contract).
pub fn top_level(origin: T::AccountId, cfg: &'a ConfigCache<T>) -> Self {
ExecutionContext {
caller: None,
self_trie_id: None,
self_account: origin,
depth: 0,
config: &cfg,
timestamp: T::Time::now(),
block_number: <frame_system::Module<T>>::block_number(),
_phantom: Default::default(),
}
}
fn nested<'b, 'c: 'b>(&'c self, dest: T::AccountId, trie_id: TrieId)
-> ExecutionContext<'b, T, E>
{
ExecutionContext {
caller: Some(self),
self_trie_id: Some(trie_id),
self_account: dest,
depth: self.depth + 1,
config: self.config,
timestamp: self.timestamp.clone(),
block_number: self.block_number.clone(),
_phantom: Default::default(),
}
}
/// Make a call to the specified address, optionally transferring some funds.
pub fn call(
&mut self,
dest: T::AccountId,
value: BalanceOf<T>,
gas_meter: &mut GasMeter<T>,
input_data: Vec<u8>,
) -> ExecResult {
if self.depth == self.config.max_depth as usize {
Err(Error::<T>::MaxCallDepthReached)?
}
let contract = <ContractInfoOf<T>>::get(&dest)
.and_then(|contract| contract.get_alive())
.ok_or(Error::<T>::NotCallable)?;
let executable = E::from_storage(contract.code_hash, &self.config.schedule)?;
// This charges the rent and denies access to a contract that is in need of
// eviction by returning `None`. We cannot evict eagerly here because those
// changes would be rolled back in case this contract is called by another
// contract.
// See: https://github.com/paritytech/substrate/issues/6439#issuecomment-648754324
let contract = Rent::<T, E>::charge(&dest, contract, executable.occupied_storage())?
.ok_or(Error::<T>::NotCallable)?;
let transactor_kind = self.transactor_kind();
let caller = self.self_account.clone();
self.with_nested_context(dest.clone(), contract.trie_id.clone(), |nested| {
if value > BalanceOf::<T>::zero() {
transfer(
TransferCause::Call,
transactor_kind,
&caller,
&dest,
value,
nested,
)?
}
let output = executable.execute(
nested.new_call_context(caller, value),
&ExportedFunction::Call,
input_data,
gas_meter,
).map_err(|e| ExecError { error: e.error, origin: ErrorOrigin::Callee })?;
Ok(output)
})
}
pub fn instantiate(
&mut self,
endowment: BalanceOf<T>,
gas_meter: &mut GasMeter<T>,
executable: E,
input_data: Vec<u8>,
salt: &[u8],
) -> Result<(T::AccountId, ExecReturnValue), ExecError> {
if self.depth == self.config.max_depth as usize {
Err(Error::<T>::MaxCallDepthReached)?
}
let transactor_kind = self.transactor_kind();
let caller = self.self_account.clone();
let dest = Contracts::<T>::contract_address(&caller, executable.code_hash(), salt);
let output = frame_support::storage::with_transaction(|| {
// Generate the trie id in a new transaction to only increment the counter on success.
let dest_trie_id = Storage::<T>::generate_trie_id(&dest);
let output = self.with_nested_context(dest.clone(), dest_trie_id, |nested| {
Storage::<T>::place_contract(
&dest,
nested
.self_trie_id
.clone()
.expect("the nested context always has to have self_trie_id"),
executable.code_hash().clone()
)?;
// Send funds unconditionally here. If the `endowment` is below existential_deposit
// then error will be returned here.
transfer(
TransferCause::Instantiate,
transactor_kind,
&caller,
&dest,
endowment,
nested,
)?;
// Cache the value before calling into the constructor because that
// consumes the value. If the constructor creates additional contracts using
// the same code hash we still charge the "1 block rent" as if they weren't
// spawned. This is OK as overcharging is always safe.
let occupied_storage = executable.occupied_storage();
let output = executable.execute(
nested.new_call_context(caller.clone(), endowment),
&ExportedFunction::Constructor,
input_data,
gas_meter,
).map_err(|e| ExecError { error: e.error, origin: ErrorOrigin::Callee })?;
// We need to re-fetch the contract because changes are written to storage
// eagerly during execution.
let contract = <ContractInfoOf<T>>::get(&dest)
.and_then(|contract| contract.get_alive())
.ok_or(Error::<T>::NotCallable)?;
// Collect the rent for the first block to prevent the creation of very large
// contracts that never intended to pay for even one block.
// This also makes sure that it is above the subsistence threshold
// in order to keep up the guarantuee that we always leave a tombstone behind
// with the exception of a contract that called `seal_terminate`.
Rent::<T, E>::charge(&dest, contract, occupied_storage)?
.ok_or(Error::<T>::NewContractNotFunded)?;
// Deposit an instantiation event.
deposit_event::<T>(vec![], RawEvent::Instantiated(caller.clone(), dest.clone()));
Ok(output)
});
use frame_support::storage::TransactionOutcome::*;
match output {
Ok(_) => Commit(output),
Err(_) => Rollback(output),
}
})?;
Ok((dest, output))
}
fn new_call_context<'b>(
&'b mut self,
caller: T::AccountId,
value: BalanceOf<T>,
) -> CallContext<'b, 'a, T, E> {
let timestamp = self.timestamp.clone();
let block_number = self.block_number.clone();
CallContext {
ctx: self,
caller,
value_transferred: value,
timestamp,
block_number,
_phantom: Default::default(),
}
}
/// Execute the given closure within a nested execution context.
fn with_nested_context<F>(&mut self, dest: T::AccountId, trie_id: TrieId, func: F)
-> ExecResult
where F: FnOnce(&mut ExecutionContext<T, E>) -> ExecResult
{
use frame_support::storage::TransactionOutcome::*;
let mut nested = self.nested(dest, trie_id);
frame_support::storage::with_transaction(|| {
let output = func(&mut nested);
match output {
Ok(ref rv) if !rv.flags.contains(ReturnFlags::REVERT) => Commit(output),
_ => Rollback(output),
}
})
}
/// Returns whether a contract, identified by address, is currently live in the execution
/// stack, meaning it is in the middle of an execution.
fn is_live(&self, account: &T::AccountId) -> bool {
&self.self_account == account ||
self.caller.map_or(false, |caller| caller.is_live(account))
}
fn transactor_kind(&self) -> TransactorKind {
if self.depth == 0 {
debug_assert!(self.self_trie_id.is_none());
debug_assert!(self.caller.is_none());
debug_assert!(ContractInfoOf::<T>::get(&self.self_account).is_none());
TransactorKind::PlainAccount
} else {
TransactorKind::Contract
}
}
}
/// Describes possible transfer causes.
enum TransferCause {
Call,
Instantiate,
Terminate,
}
/// Transfer some funds from `transactor` to `dest`.
///
/// We only allow allow for draining all funds of the sender if `cause` is
/// is specified as `Terminate`. Otherwise, any transfer that would bring the sender below the
/// subsistence threshold (for contracts) or the existential deposit (for plain accounts)
/// results in an error.
fn transfer<'a, T: Config, E>(
cause: TransferCause,
origin: TransactorKind,
transactor: &T::AccountId,
dest: &T::AccountId,
value: BalanceOf<T>,
ctx: &mut ExecutionContext<'a, T, E>,
) -> DispatchResult
where
T::AccountId: UncheckedFrom<T::Hash> + AsRef<[u8]>,
E: Executable<T>,
{
use self::TransferCause::*;
use self::TransactorKind::*;
// Only seal_terminate is allowed to bring the sender below the subsistence
// threshold or even existential deposit.
let existence_requirement = match (cause, origin) {
(Terminate, _) => ExistenceRequirement::AllowDeath,
(_, Contract) => {
ensure!(
T::Currency::total_balance(transactor).saturating_sub(value) >=
ctx.config.subsistence_threshold(),
Error::<T>::BelowSubsistenceThreshold,
);
ExistenceRequirement::KeepAlive
},
(_, PlainAccount) => ExistenceRequirement::KeepAlive,
};
T::Currency::transfer(transactor, dest, value, existence_requirement)
.map_err(|_| Error::<T>::TransferFailed)?;
Ok(())
}
/// A context that is active within a call.
///
/// This context has some invariants that must be held at all times. Specifically:
///`ctx` always points to a context of an alive contract. That implies that it has an existent
/// `self_trie_id`.
///
/// Be advised that there are brief time spans where these invariants could be invalidated.
/// For example, when a contract requests self-termination the contract is removed eagerly. That
/// implies that the control won't be returned to the contract anymore, but there is still some code
/// on the path of the return from that call context. Therefore, care must be taken in these
/// situations.
struct CallContext<'a, 'b: 'a, T: Config + 'b, E> {
ctx: &'a mut ExecutionContext<'b, T, E>,
caller: T::AccountId,
value_transferred: BalanceOf<T>,
timestamp: MomentOf<T>,
block_number: T::BlockNumber,
_phantom: PhantomData<E>,
}
impl<'a, 'b: 'a, T, E> Ext for CallContext<'a, 'b, T, E>
where
T: Config + 'b,
T::AccountId: UncheckedFrom<T::Hash> + AsRef<[u8]>,
E: Executable<T>,
{
type T = T;
fn get_storage(&self, key: &StorageKey) -> Option<Vec<u8>> {
let trie_id = self.ctx.self_trie_id.as_ref().expect(
"`ctx.self_trie_id` points to an alive contract within the `CallContext`;\
it cannot be `None`;\
expect can't fail;\
qed",
);
Storage::<T>::read(trie_id, key)
}
fn set_storage(&mut self, key: StorageKey, value: Option<Vec<u8>>) -> DispatchResult {
let trie_id = self.ctx.self_trie_id.as_ref().expect(
"`ctx.self_trie_id` points to an alive contract within the `CallContext`;\
it cannot be `None`;\
expect can't fail;\
qed",
);
// write panics if the passed account is not alive.
// the contract must be in the alive state within the `CallContext`;\
// the contract cannot be absent in storage;
// write cannot return `None`;
// qed
Storage::<T>::write(&self.ctx.self_account, trie_id, &key, value)
}
fn instantiate(
&mut self,
code_hash: CodeHash<T>,
endowment: BalanceOf<T>,
gas_meter: &mut GasMeter<T>,
input_data: Vec<u8>,
salt: &[u8],
) -> Result<(AccountIdOf<T>, ExecReturnValue), ExecError> {
let executable = E::from_storage(code_hash, &self.ctx.config.schedule)?;
let result = self.ctx.instantiate(endowment, gas_meter, executable, input_data, salt)?;
Ok(result)
}
fn transfer(
&mut self,
to: &T::AccountId,
value: BalanceOf<T>,
) -> DispatchResult {
transfer(
TransferCause::Call,
TransactorKind::Contract,
&self.ctx.self_account.clone(),
to,
value,
self.ctx,
)
}
fn terminate(
&mut self,
beneficiary: &AccountIdOf<Self::T>,
) -> DispatchResult {
let self_id = self.ctx.self_account.clone();
let value = T::Currency::free_balance(&self_id);
if let Some(caller_ctx) = self.ctx.caller {
if caller_ctx.is_live(&self_id) {
return Err(Error::<T>::ReentranceDenied.into());
}
}
transfer(
TransferCause::Terminate,
TransactorKind::Contract,
&self_id,
beneficiary,
value,
self.ctx,
)?;
if let Some(ContractInfo::Alive(info)) = ContractInfoOf::<T>::take(&self_id) {
Storage::<T>::queue_trie_for_deletion(&info)?;
E::remove_user(info.code_hash);
Contracts::<T>::deposit_event(RawEvent::Terminated(self_id, beneficiary.clone()));
Ok(())
} else {
panic!(
"this function is only invoked by in the context of a contract;\
this contract is therefore alive;\
qed"
);
}
}
fn call(
&mut self,
to: &T::AccountId,
value: BalanceOf<T>,
gas_meter: &mut GasMeter<T>,
input_data: Vec<u8>,
) -> ExecResult {
self.ctx.call(to.clone(), value, gas_meter, input_data)
}
fn restore_to(
&mut self,
dest: AccountIdOf<Self::T>,
code_hash: CodeHash<Self::T>,
rent_allowance: BalanceOf<Self::T>,
delta: Vec<StorageKey>,
) -> DispatchResult {
if let Some(caller_ctx) = self.ctx.caller {
if caller_ctx.is_live(&self.ctx.self_account) {
return Err(Error::<T>::ReentranceDenied.into());
}
}
let result = Rent::<T, E>::restore_to(
self.ctx.self_account.clone(),
dest.clone(),
code_hash.clone(),
rent_allowance,
delta,
);
if let Ok(_) = result {
deposit_event::<Self::T>(
vec![],
RawEvent::Restored(
self.ctx.self_account.clone(),
dest,
code_hash,
rent_allowance,
),
);
}
result
}
fn address(&self) -> &T::AccountId {
&self.ctx.self_account
}
fn caller(&self) -> &T::AccountId {
&self.caller
}
fn balance(&self) -> BalanceOf<T> {
T::Currency::free_balance(&self.ctx.self_account)
}
fn value_transferred(&self) -> BalanceOf<T> {
self.value_transferred
}
fn random(&self, subject: &[u8]) -> SeedOf<T> {
T::Randomness::random(subject)
}
fn now(&self) -> &MomentOf<T> {
&self.timestamp
}
fn minimum_balance(&self) -> BalanceOf<T> {
self.ctx.config.existential_deposit
}
fn tombstone_deposit(&self) -> BalanceOf<T> {
self.ctx.config.tombstone_deposit
}
fn deposit_event(&mut self, topics: Vec<T::Hash>, data: Vec<u8>) {
deposit_event::<Self::T>(
topics,
RawEvent::ContractEmitted(self.ctx.self_account.clone(), data)
);
}
fn set_rent_allowance(&mut self, rent_allowance: BalanceOf<T>) {
if let Err(storage::ContractAbsentError) =
Storage::<T>::set_rent_allowance(&self.ctx.self_account, rent_allowance)
{
panic!(
"`self_account` points to an alive contract within the `CallContext`;
set_rent_allowance cannot return `Err`; qed"
);
}
}
fn rent_allowance(&self) -> BalanceOf<T> {
Storage::<T>::rent_allowance(&self.ctx.self_account)
.unwrap_or_else(|_| <BalanceOf<T>>::max_value()) // Must never be triggered actually
}
fn block_number(&self) -> T::BlockNumber { self.block_number }
fn max_value_size(&self) -> u32 {
self.ctx.config.max_value_size
}
fn get_weight_price(&self, weight: Weight) -> BalanceOf<Self::T> {
T::WeightPrice::convert(weight)
}
fn schedule(&self) -> &Schedule<Self::T> {
&self.ctx.config.schedule
}
}
fn deposit_event<T: Config>(
topics: Vec<T::Hash>,
event: Event<T>,
) {
<frame_system::Module<T>>::deposit_event_indexed(
&*topics,
<T as Config>::Event::from(event).into(),
)
}
/// These tests exercise the executive layer.
///
/// In these tests the VM/loader are mocked. Instead of dealing with wasm bytecode they use simple closures.
/// This allows you to tackle executive logic more thoroughly without writing a
/// wasm VM code.
#[cfg(test)]
mod tests {
use super::*;
use crate::{
gas::GasMeter, tests::{ExtBuilder, Test, Event as MetaEvent},
gas::Gas,
storage::Storage,
tests::{
ALICE, BOB, CHARLIE,
test_utils::{place_contract, set_balance, get_balance},
},
Error,
};
use sp_runtime::DispatchError;
use assert_matches::assert_matches;
use std::{cell::RefCell, collections::HashMap, rc::Rc};
type MockContext<'a> = ExecutionContext<'a, Test, MockExecutable>;
const GAS_LIMIT: Gas = 10_000_000_000;
thread_local! {
static LOADER: RefCell<MockLoader> = RefCell::new(MockLoader::default());
}
fn events() -> Vec<Event<Test>> {
<frame_system::Module<Test>>::events()
.into_iter()
.filter_map(|meta| match meta.event {
MetaEvent::pallet_contracts(contract_event) => Some(contract_event),
_ => None,
})
.collect()
}
struct MockCtx<'a> {
ext: &'a mut dyn Ext<T = Test>,
input_data: Vec<u8>,
gas_meter: &'a mut GasMeter<Test>,
}
#[derive(Clone)]
struct MockExecutable(Rc<dyn Fn(MockCtx) -> ExecResult + 'static>, CodeHash<Test>);
#[derive(Default)]
struct MockLoader {
map: HashMap<CodeHash<Test>, MockExecutable>,
counter: u64,
}
impl MockLoader {
fn insert(f: impl Fn(MockCtx) -> ExecResult + 'static) -> CodeHash<Test> {
LOADER.with(|loader| {
let mut loader = loader.borrow_mut();
// Generate code hashes as monotonically increasing values.
let hash = <Test as frame_system::Config>::Hash::from_low_u64_be(loader.counter);
loader.counter += 1;
loader.map.insert(hash, MockExecutable (Rc::new(f), hash.clone()));
hash
})
}
}
impl Executable<Test> for MockExecutable {
fn from_storage(
code_hash: CodeHash<Test>,
_schedule: &Schedule<Test>
) -> Result<Self, DispatchError> {
Self::from_storage_noinstr(code_hash)
}
fn from_storage_noinstr(code_hash: CodeHash<Test>) -> Result<Self, DispatchError> {
LOADER.with(|loader| {
loader.borrow_mut()
.map
.get(&code_hash)
.cloned()
.ok_or(Error::<Test>::CodeNotFound.into())
})
}
fn drop_from_storage(self) {}
fn add_user(_code_hash: CodeHash<Test>) -> DispatchResult {
Ok(())
}
fn remove_user(_code_hash: CodeHash<Test>) {}
fn execute<E: Ext<T = Test>>(
self,
mut ext: E,
_function: &ExportedFunction,
input_data: Vec<u8>,
gas_meter: &mut GasMeter<Test>,
) -> ExecResult {
(self.0)(MockCtx {
ext: &mut ext,
input_data,
gas_meter,
})
}
fn code_hash(&self) -> &CodeHash<Test> {
&self.1
}
fn occupied_storage(&self) -> u32 {
0
}
}
fn exec_success() -> ExecResult {
Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: Vec::new() })
}
#[test]
fn it_works() {
thread_local! {
static TEST_DATA: RefCell<Vec<usize>> = RefCell::new(vec![0]);
}
let value = Default::default();
let mut gas_meter = GasMeter::<Test>::new(GAS_LIMIT);
let exec_ch = MockLoader::insert(|_ctx| {
TEST_DATA.with(|data| data.borrow_mut().push(1));
exec_success()
});
ExtBuilder::default().build().execute_with(|| {
let cfg = ConfigCache::preload();
let mut ctx = MockContext::top_level(ALICE, &cfg);
place_contract(&BOB, exec_ch);
assert_matches!(
ctx.call(BOB, value, &mut gas_meter, vec![]),
Ok(_)
);
});
TEST_DATA.with(|data| assert_eq!(*data.borrow(), vec![0, 1]));
}
#[test]
fn transfer_works() {
// This test verifies that a contract is able to transfer
// some funds to another account.
let origin = ALICE;
let dest = BOB;
ExtBuilder::default().build().execute_with(|| {
let cfg = ConfigCache::preload();
let mut ctx = MockContext::top_level(origin.clone(), &cfg);
set_balance(&origin, 100);
set_balance(&dest, 0);
super::transfer(
super::TransferCause::Call,
super::TransactorKind::PlainAccount,
&origin,
&dest,
55,
&mut ctx,
).unwrap();
assert_eq!(get_balance(&origin), 45);
assert_eq!(get_balance(&dest), 55);
});
}
#[test]
fn changes_are_reverted_on_failing_call() {
// This test verifies that changes are reverted on a call which fails (or equally, returns
// a non-zero status code).
let origin = ALICE;
let dest = BOB;
let return_ch = MockLoader::insert(
|_| Ok(ExecReturnValue { flags: ReturnFlags::REVERT, data: Vec::new() })
);
ExtBuilder::default().build().execute_with(|| {
let cfg = ConfigCache::preload();
let mut ctx = MockContext::top_level(origin.clone(), &cfg);
place_contract(&BOB, return_ch);
set_balance(&origin, 100);
let balance = get_balance(&dest);
let output = ctx.call(
dest.clone(),
55,
&mut GasMeter::<Test>::new(GAS_LIMIT),
vec![],
).unwrap();
assert!(!output.is_success());
assert_eq!(get_balance(&origin), 100);
// the rent is still charged
assert!(get_balance(&dest) < balance);
});
}
#[test]
fn balance_too_low() {
// This test verifies that a contract can't send value if it's
// balance is too low.
let origin = ALICE;
let dest = BOB;
ExtBuilder::default().build().execute_with(|| {
let cfg = ConfigCache::preload();
let mut ctx = MockContext::top_level(origin.clone(), &cfg);
set_balance(&origin, 0);
let result = super::transfer(
super::TransferCause::Call,
super::TransactorKind::PlainAccount,
&origin,
&dest,
100,
&mut ctx,
);
assert_eq!(
result,
Err(Error::<Test>::TransferFailed.into())
);
assert_eq!(get_balance(&origin), 0);
assert_eq!(get_balance(&dest), 0);