-
Notifications
You must be signed in to change notification settings - Fork 798
/
Copy pathtests.rs
4573 lines (3923 loc) · 148 KB
/
tests.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.
mod pallet_dummy;
mod test_debug;
use self::{
test_debug::TestDebug,
test_utils::{ensure_stored, expected_deposit},
};
use crate::{
self as pallet_revive,
address::{create1, create2, AddressMapper},
chain_extension::{
ChainExtension, Environment, Ext, RegisteredChainExtension, Result as ExtensionResult,
RetVal, ReturnFlags,
},
exec::Key,
limits,
primitives::CodeUploadReturnValue,
storage::DeletionQueueManager,
test_utils::*,
tests::test_utils::{get_contract, get_contract_checked},
wasm::Memory,
weights::WeightInfo,
AccountId32Mapper, BalanceOf, Code, CodeInfoOf, CollectEvents, Config, ContractInfo,
ContractInfoOf, DebugInfo, DeletionQueueCounter, Error, HoldReason, Origin, Pallet,
PristineCode, H160,
};
use crate::test_utils::builder::Contract;
use assert_matches::assert_matches;
use codec::{Decode, Encode};
use frame_support::{
assert_err, assert_err_ignore_postinfo, assert_err_with_weight, assert_noop, assert_ok,
derive_impl,
pallet_prelude::EnsureOrigin,
parameter_types,
storage::child,
traits::{
fungible::{BalancedHold, Inspect, Mutate, MutateHold},
tokens::Preservation,
ConstU32, ConstU64, Contains, OnIdle, OnInitialize, StorageVersion,
},
weights::{constants::WEIGHT_REF_TIME_PER_SECOND, FixedFee, IdentityFee, Weight, WeightMeter},
};
use frame_system::{EventRecord, Phase};
use pallet_revive_fixtures::{bench::dummy_unique, compile_module};
use pallet_revive_uapi::ReturnErrorCode as RuntimeReturnCode;
use pallet_transaction_payment::{ConstFeeMultiplier, Multiplier};
use pretty_assertions::{assert_eq, assert_ne};
use sp_core::U256;
use sp_io::hashing::blake2_256;
use sp_keystore::{testing::MemoryKeystore, KeystoreExt};
use sp_runtime::{
testing::H256,
traits::{BlakeTwo256, Convert, IdentityLookup, One},
AccountId32, BuildStorage, DispatchError, Perbill, TokenError,
};
type Block = frame_system::mocking::MockBlock<Test>;
frame_support::construct_runtime!(
pub enum Test
{
System: frame_system,
Balances: pallet_balances,
Timestamp: pallet_timestamp,
Utility: pallet_utility,
Contracts: pallet_revive,
Proxy: pallet_proxy,
TransactionPayment: pallet_transaction_payment,
Dummy: pallet_dummy
}
);
macro_rules! assert_return_code {
( $x:expr , $y:expr $(,)? ) => {{
assert_eq!(u32::from_le_bytes($x.data[..].try_into().unwrap()), $y as u32);
}};
}
macro_rules! assert_refcount {
( $code_hash:expr , $should:expr $(,)? ) => {{
let is = crate::CodeInfoOf::<Test>::get($code_hash).map(|m| m.refcount()).unwrap();
assert_eq!(is, $should);
}};
}
pub mod test_utils {
use super::{Contracts, DepositPerByte, DepositPerItem, Test};
use crate::{
address::AddressMapper, exec::AccountIdOf, BalanceOf, CodeInfo, CodeInfoOf, Config,
ContractInfo, ContractInfoOf, PristineCode,
};
use codec::{Encode, MaxEncodedLen};
use frame_support::traits::fungible::{InspectHold, Mutate};
use sp_core::H160;
pub fn place_contract(address: &AccountIdOf<Test>, code_hash: sp_core::H256) {
set_balance(address, Contracts::min_balance() * 10);
<CodeInfoOf<Test>>::insert(code_hash, CodeInfo::new(address.clone()));
let address =
<<Test as Config>::AddressMapper as AddressMapper<Test>>::to_address(&address);
let contract = <ContractInfo<Test>>::new(&address, 0, code_hash).unwrap();
<ContractInfoOf<Test>>::insert(address, contract);
}
pub fn set_balance(who: &AccountIdOf<Test>, amount: u64) {
let _ = <Test as Config>::Currency::set_balance(who, amount);
}
pub fn get_balance(who: &AccountIdOf<Test>) -> u64 {
<Test as Config>::Currency::free_balance(who)
}
pub fn get_balance_on_hold(
reason: &<Test as Config>::RuntimeHoldReason,
who: &AccountIdOf<Test>,
) -> u64 {
<Test as Config>::Currency::balance_on_hold(reason.into(), who)
}
pub fn get_contract(addr: &H160) -> ContractInfo<Test> {
get_contract_checked(addr).unwrap()
}
pub fn get_contract_checked(addr: &H160) -> Option<ContractInfo<Test>> {
ContractInfoOf::<Test>::get(addr)
}
pub fn get_code_deposit(code_hash: &sp_core::H256) -> BalanceOf<Test> {
crate::CodeInfoOf::<Test>::get(code_hash).unwrap().deposit()
}
pub fn contract_info_storage_deposit(addr: &H160) -> BalanceOf<Test> {
let contract_info = self::get_contract(&addr);
let info_size = contract_info.encoded_size() as u64;
let info_deposit = DepositPerByte::get()
.saturating_mul(info_size)
.saturating_add(DepositPerItem::get());
let immutable_size = contract_info.immutable_data_len() as u64;
if immutable_size > 0 {
let immutable_deposit = DepositPerByte::get()
.saturating_mul(immutable_size)
.saturating_add(DepositPerItem::get());
info_deposit.saturating_add(immutable_deposit)
} else {
info_deposit
}
}
pub fn expected_deposit(code_len: usize) -> u64 {
// For code_info, the deposit for max_encoded_len is taken.
let code_info_len = CodeInfo::<Test>::max_encoded_len() as u64;
// Calculate deposit to be reserved.
// We add 2 storage items: one for code, other for code_info
DepositPerByte::get().saturating_mul(code_len as u64 + code_info_len) +
DepositPerItem::get().saturating_mul(2)
}
pub fn ensure_stored(code_hash: sp_core::H256) -> usize {
// Assert that code_info is stored
assert!(CodeInfoOf::<Test>::contains_key(&code_hash));
// Assert that contract code is stored, and get its size.
PristineCode::<Test>::try_get(&code_hash).unwrap().len()
}
pub fn u256_bytes(u: u64) -> [u8; 32] {
let mut buffer = [0u8; 32];
let bytes = u.to_le_bytes();
buffer[..8].copy_from_slice(&bytes);
buffer
}
}
mod builder {
use super::Test;
use crate::{
test_utils::{builder::*, ALICE},
tests::RuntimeOrigin,
Code,
};
use sp_core::{H160, H256};
pub fn bare_instantiate(code: Code) -> BareInstantiateBuilder<Test> {
BareInstantiateBuilder::<Test>::bare_instantiate(RuntimeOrigin::signed(ALICE), code)
}
pub fn bare_call(dest: H160) -> BareCallBuilder<Test> {
BareCallBuilder::<Test>::bare_call(RuntimeOrigin::signed(ALICE), dest)
}
pub fn instantiate_with_code(code: Vec<u8>) -> InstantiateWithCodeBuilder<Test> {
InstantiateWithCodeBuilder::<Test>::instantiate_with_code(
RuntimeOrigin::signed(ALICE),
code,
)
}
pub fn instantiate(code_hash: H256) -> InstantiateBuilder<Test> {
InstantiateBuilder::<Test>::instantiate(RuntimeOrigin::signed(ALICE), code_hash)
}
pub fn call(dest: H160) -> CallBuilder<Test> {
CallBuilder::<Test>::call(RuntimeOrigin::signed(ALICE), dest)
}
}
impl Test {
pub fn set_unstable_interface(unstable_interface: bool) {
UNSTABLE_INTERFACE.with(|v| *v.borrow_mut() = unstable_interface);
}
}
parameter_types! {
static TestExtensionTestValue: TestExtension = Default::default();
}
#[derive(Clone)]
pub struct TestExtension {
enabled: bool,
last_seen_buffer: Vec<u8>,
last_seen_input_len: u32,
}
#[derive(Default)]
pub struct RevertingExtension;
#[derive(Default)]
pub struct DisabledExtension;
#[derive(Default)]
pub struct TempStorageExtension {
storage: u32,
}
impl TestExtension {
fn disable() {
TestExtensionTestValue::mutate(|e| e.enabled = false)
}
fn last_seen_buffer() -> Vec<u8> {
TestExtensionTestValue::get().last_seen_buffer.clone()
}
fn last_seen_input_len() -> u32 {
TestExtensionTestValue::get().last_seen_input_len
}
}
impl Default for TestExtension {
fn default() -> Self {
Self { enabled: true, last_seen_buffer: vec![], last_seen_input_len: 0 }
}
}
impl ChainExtension<Test> for TestExtension {
fn call<E, M>(&mut self, mut env: Environment<E, M>) -> ExtensionResult<RetVal>
where
E: Ext<T = Test>,
M: ?Sized + Memory<E::T>,
{
let func_id = env.func_id();
let id = env.ext_id() as u32 | func_id as u32;
match func_id {
0 => {
let input = env.read(8)?;
env.write(&input, false, None)?;
TestExtensionTestValue::mutate(|e| e.last_seen_buffer = input);
Ok(RetVal::Converging(id))
},
1 => {
TestExtensionTestValue::mutate(|e| e.last_seen_input_len = env.in_len());
Ok(RetVal::Converging(id))
},
2 => {
let mut enc = &env.read(9)?[4..8];
let weight = Weight::from_parts(
u32::decode(&mut enc).map_err(|_| Error::<Test>::ContractTrapped)?.into(),
0,
);
env.charge_weight(weight)?;
Ok(RetVal::Converging(id))
},
3 => Ok(RetVal::Diverging { flags: ReturnFlags::REVERT, data: vec![42, 99] }),
_ => {
panic!("Passed unknown id to test chain extension: {}", func_id);
},
}
}
fn enabled() -> bool {
TestExtensionTestValue::get().enabled
}
}
impl RegisteredChainExtension<Test> for TestExtension {
const ID: u16 = 0;
}
impl ChainExtension<Test> for RevertingExtension {
fn call<E, M>(&mut self, _env: Environment<E, M>) -> ExtensionResult<RetVal>
where
E: Ext<T = Test>,
M: ?Sized + Memory<E::T>,
{
Ok(RetVal::Diverging { flags: ReturnFlags::REVERT, data: vec![0x4B, 0x1D] })
}
fn enabled() -> bool {
TestExtensionTestValue::get().enabled
}
}
impl RegisteredChainExtension<Test> for RevertingExtension {
const ID: u16 = 1;
}
impl ChainExtension<Test> for DisabledExtension {
fn call<E, M>(&mut self, _env: Environment<E, M>) -> ExtensionResult<RetVal>
where
E: Ext<T = Test>,
M: ?Sized + Memory<E::T>,
{
panic!("Disabled chain extensions are never called")
}
fn enabled() -> bool {
false
}
}
impl RegisteredChainExtension<Test> for DisabledExtension {
const ID: u16 = 2;
}
impl ChainExtension<Test> for TempStorageExtension {
fn call<E, M>(&mut self, env: Environment<E, M>) -> ExtensionResult<RetVal>
where
E: Ext<T = Test>,
M: ?Sized + Memory<E::T>,
{
let func_id = env.func_id();
match func_id {
0 => self.storage = 42,
1 => assert_eq!(self.storage, 42, "Storage is preserved inside the same call."),
2 => {
assert_eq!(self.storage, 0, "Storage is different for different calls.");
self.storage = 99;
},
3 => assert_eq!(self.storage, 99, "Storage is preserved inside the same call."),
_ => {
panic!("Passed unknown id to test chain extension: {}", func_id);
},
}
Ok(RetVal::Converging(0))
}
fn enabled() -> bool {
TestExtensionTestValue::get().enabled
}
}
impl RegisteredChainExtension<Test> for TempStorageExtension {
const ID: u16 = 3;
}
parameter_types! {
pub BlockWeights: frame_system::limits::BlockWeights =
frame_system::limits::BlockWeights::simple_max(
Weight::from_parts(2u64 * WEIGHT_REF_TIME_PER_SECOND, u64::MAX),
);
pub static ExistentialDeposit: u64 = 1;
}
#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
impl frame_system::Config for Test {
type Block = Block;
type AccountId = AccountId32;
type Lookup = IdentityLookup<Self::AccountId>;
type AccountData = pallet_balances::AccountData<u64>;
}
#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)]
impl pallet_balances::Config for Test {
type ExistentialDeposit = ExistentialDeposit;
type ReserveIdentifier = [u8; 8];
type AccountStore = System;
}
#[derive_impl(pallet_timestamp::config_preludes::TestDefaultConfig)]
impl pallet_timestamp::Config for Test {}
impl pallet_utility::Config for Test {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type PalletsOrigin = OriginCaller;
type WeightInfo = ();
}
impl pallet_proxy::Config for Test {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type Currency = Balances;
type ProxyType = ();
type ProxyDepositBase = ConstU64<1>;
type ProxyDepositFactor = ConstU64<1>;
type MaxProxies = ConstU32<32>;
type WeightInfo = ();
type MaxPending = ConstU32<32>;
type CallHasher = BlakeTwo256;
type AnnouncementDepositBase = ConstU64<1>;
type AnnouncementDepositFactor = ConstU64<1>;
}
parameter_types! {
pub FeeMultiplier: Multiplier = Multiplier::one();
}
#[derive_impl(pallet_transaction_payment::config_preludes::TestDefaultConfig)]
impl pallet_transaction_payment::Config for Test {
type OnChargeTransaction = pallet_transaction_payment::FungibleAdapter<Balances, ()>;
type WeightToFee = IdentityFee<<Self as pallet_balances::Config>::Balance>;
type LengthToFee = FixedFee<100, <Self as pallet_balances::Config>::Balance>;
type FeeMultiplierUpdate = ConstFeeMultiplier<FeeMultiplier>;
}
impl pallet_dummy::Config for Test {}
parameter_types! {
pub static DepositPerByte: BalanceOf<Test> = 1;
pub const DepositPerItem: BalanceOf<Test> = 2;
pub static CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(0);
pub static ChainId: u64 = 384;
}
impl Convert<Weight, BalanceOf<Self>> for Test {
fn convert(w: Weight) -> BalanceOf<Self> {
w.ref_time()
}
}
/// A filter whose filter function can be swapped at runtime.
pub struct TestFilter;
#[derive(Clone)]
pub struct Filters {
filter: fn(&RuntimeCall) -> bool,
}
impl Default for Filters {
fn default() -> Self {
Filters { filter: (|_| true) }
}
}
parameter_types! {
static CallFilter: Filters = Default::default();
}
impl TestFilter {
pub fn set_filter(filter: fn(&RuntimeCall) -> bool) {
CallFilter::mutate(|fltr| fltr.filter = filter);
}
}
impl Contains<RuntimeCall> for TestFilter {
fn contains(call: &RuntimeCall) -> bool {
(CallFilter::get().filter)(call)
}
}
parameter_types! {
pub static UploadAccount: Option<<Test as frame_system::Config>::AccountId> = None;
pub static InstantiateAccount: Option<<Test as frame_system::Config>::AccountId> = None;
}
pub struct EnsureAccount<T, A>(core::marker::PhantomData<(T, A)>);
impl<T: Config, A: sp_core::Get<Option<crate::AccountIdOf<T>>>>
EnsureOrigin<<T as frame_system::Config>::RuntimeOrigin> for EnsureAccount<T, A>
where
<T as frame_system::Config>::AccountId: From<AccountId32>,
{
type Success = T::AccountId;
fn try_origin(o: T::RuntimeOrigin) -> Result<Self::Success, T::RuntimeOrigin> {
let who = <frame_system::EnsureSigned<_> as EnsureOrigin<_>>::try_origin(o.clone())?;
if matches!(A::get(), Some(a) if who != a) {
return Err(o);
}
Ok(who)
}
#[cfg(feature = "runtime-benchmarks")]
fn try_successful_origin() -> Result<T::RuntimeOrigin, ()> {
Err(())
}
}
parameter_types! {
pub static UnstableInterface: bool = true;
}
#[derive_impl(crate::config_preludes::TestDefaultConfig)]
impl Config for Test {
type Time = Timestamp;
type AddressMapper = AccountId32Mapper<Self>;
type Currency = Balances;
type CallFilter = TestFilter;
type ChainExtension =
(TestExtension, DisabledExtension, RevertingExtension, TempStorageExtension);
type DepositPerByte = DepositPerByte;
type DepositPerItem = DepositPerItem;
type UnsafeUnstableInterface = UnstableInterface;
type UploadOrigin = EnsureAccount<Self, UploadAccount>;
type InstantiateOrigin = EnsureAccount<Self, InstantiateAccount>;
type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent;
type Debug = TestDebug;
type ChainId = ChainId;
}
impl TryFrom<RuntimeCall> for crate::Call<Test> {
type Error = ();
fn try_from(value: RuntimeCall) -> Result<Self, Self::Error> {
match value {
RuntimeCall::Contracts(call) => Ok(call),
_ => Err(()),
}
}
}
pub struct ExtBuilder {
existential_deposit: u64,
storage_version: Option<StorageVersion>,
code_hashes: Vec<sp_core::H256>,
}
impl Default for ExtBuilder {
fn default() -> Self {
Self {
existential_deposit: ExistentialDeposit::get(),
storage_version: None,
code_hashes: vec![],
}
}
}
impl ExtBuilder {
pub fn existential_deposit(mut self, existential_deposit: u64) -> Self {
self.existential_deposit = existential_deposit;
self
}
pub fn with_code_hashes(mut self, code_hashes: Vec<sp_core::H256>) -> Self {
self.code_hashes = code_hashes;
self
}
pub fn set_associated_consts(&self) {
EXISTENTIAL_DEPOSIT.with(|v| *v.borrow_mut() = self.existential_deposit);
}
pub fn build(self) -> sp_io::TestExternalities {
sp_tracing::try_init_simple();
self.set_associated_consts();
let mut t = frame_system::GenesisConfig::<Test>::default().build_storage().unwrap();
pallet_balances::GenesisConfig::<Test> { balances: vec![] }
.assimilate_storage(&mut t)
.unwrap();
let mut ext = sp_io::TestExternalities::new(t);
ext.register_extension(KeystoreExt::new(MemoryKeystore::new()));
ext.execute_with(|| {
use frame_support::traits::OnGenesis;
Pallet::<Test>::on_genesis();
if let Some(storage_version) = self.storage_version {
storage_version.put::<Pallet<Test>>();
}
System::set_block_number(1)
});
ext.execute_with(|| {
for code_hash in self.code_hashes {
CodeInfoOf::<Test>::insert(code_hash, crate::CodeInfo::new(ALICE));
}
});
ext
}
}
fn initialize_block(number: u64) {
System::reset_events();
System::initialize(&number, &[0u8; 32].into(), &Default::default());
}
struct ExtensionInput<'a> {
extension_id: u16,
func_id: u16,
extra: &'a [u8],
}
impl<'a> ExtensionInput<'a> {
fn to_vec(&self) -> Vec<u8> {
((self.extension_id as u32) << 16 | (self.func_id as u32))
.to_le_bytes()
.iter()
.chain(self.extra)
.cloned()
.collect()
}
}
impl<'a> From<ExtensionInput<'a>> for Vec<u8> {
fn from(input: ExtensionInput) -> Vec<u8> {
input.to_vec()
}
}
impl Default for Origin<Test> {
fn default() -> Self {
Self::Signed(ALICE)
}
}
#[test]
fn calling_plain_account_is_balance_transfer() {
ExtBuilder::default().build().execute_with(|| {
let _ = <Test as Config>::Currency::set_balance(&ALICE, 100_000_000);
assert!(!<ContractInfoOf<Test>>::contains_key(BOB_ADDR));
assert_eq!(test_utils::get_balance(&BOB_FALLBACK), 0);
let result = builder::bare_call(BOB_ADDR).value(42).build_and_unwrap_result();
assert_eq!(
test_utils::get_balance(&BOB_FALLBACK),
42 + <Test as Config>::Currency::minimum_balance()
);
assert_eq!(result, Default::default());
});
}
#[test]
fn instantiate_and_call_and_deposit_event() {
let (wasm, code_hash) = compile_module("event_and_return_on_deploy").unwrap();
ExtBuilder::default().existential_deposit(1).build().execute_with(|| {
let _ = <Test as Config>::Currency::set_balance(&ALICE, 1_000_000);
let min_balance = Contracts::min_balance();
let value = 100;
// We determine the storage deposit limit after uploading because it depends on ALICEs
// free balance which is changed by uploading a module.
assert_ok!(Contracts::upload_code(
RuntimeOrigin::signed(ALICE),
wasm,
deposit_limit::<Test>(),
));
// Drop previous events
initialize_block(2);
// Check at the end to get hash on error easily
let Contract { addr, account_id } = builder::bare_instantiate(Code::Existing(code_hash))
.value(value)
.build_and_unwrap_contract();
assert!(ContractInfoOf::<Test>::contains_key(&addr));
assert_eq!(
System::events(),
vec![
EventRecord {
phase: Phase::Initialization,
event: RuntimeEvent::System(frame_system::Event::NewAccount {
account: account_id.clone()
}),
topics: vec![],
},
EventRecord {
phase: Phase::Initialization,
event: RuntimeEvent::Balances(pallet_balances::Event::Endowed {
account: account_id.clone(),
free_balance: min_balance,
}),
topics: vec![],
},
EventRecord {
phase: Phase::Initialization,
event: RuntimeEvent::Balances(pallet_balances::Event::Transfer {
from: ALICE,
to: account_id.clone(),
amount: min_balance,
}),
topics: vec![],
},
EventRecord {
phase: Phase::Initialization,
event: RuntimeEvent::Balances(pallet_balances::Event::Transfer {
from: ALICE,
to: account_id.clone(),
amount: value,
}),
topics: vec![],
},
EventRecord {
phase: Phase::Initialization,
event: RuntimeEvent::Contracts(crate::Event::ContractEmitted {
contract: addr,
data: vec![1, 2, 3, 4],
topics: vec![H256::repeat_byte(42)],
}),
topics: vec![],
},
EventRecord {
phase: Phase::Initialization,
event: RuntimeEvent::Contracts(crate::Event::Instantiated {
deployer: ALICE_ADDR,
contract: addr
}),
topics: vec![],
},
EventRecord {
phase: Phase::Initialization,
event: RuntimeEvent::Contracts(
pallet_revive::Event::StorageDepositTransferredAndHeld {
from: ALICE_ADDR,
to: addr,
amount: test_utils::contract_info_storage_deposit(&addr),
}
),
topics: vec![],
},
]
);
});
}
#[test]
fn create1_address_from_extrinsic() {
let (wasm, code_hash) = compile_module("dummy").unwrap();
ExtBuilder::default().existential_deposit(1).build().execute_with(|| {
let _ = <Test as Config>::Currency::set_balance(&ALICE, 1_000_000);
assert_ok!(Contracts::upload_code(
RuntimeOrigin::signed(ALICE),
wasm.clone(),
deposit_limit::<Test>(),
));
assert_eq!(System::account_nonce(&ALICE), 0);
System::inc_account_nonce(&ALICE);
for nonce in 1..3 {
let Contract { addr, .. } = builder::bare_instantiate(Code::Existing(code_hash))
.salt(None)
.build_and_unwrap_contract();
assert!(ContractInfoOf::<Test>::contains_key(&addr));
assert_eq!(
addr,
create1(&<Test as Config>::AddressMapper::to_address(&ALICE), nonce - 1)
);
}
assert_eq!(System::account_nonce(&ALICE), 3);
for nonce in 3..6 {
let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm.clone()))
.salt(None)
.build_and_unwrap_contract();
assert!(ContractInfoOf::<Test>::contains_key(&addr));
assert_eq!(
addr,
create1(&<Test as Config>::AddressMapper::to_address(&ALICE), nonce - 1)
);
}
assert_eq!(System::account_nonce(&ALICE), 6);
});
}
#[test]
fn deposit_event_max_value_limit() {
let (wasm, _code_hash) = compile_module("event_size").unwrap();
ExtBuilder::default().existential_deposit(50).build().execute_with(|| {
// Create
let _ = <Test as Config>::Currency::set_balance(&ALICE, 1_000_000);
let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm))
.value(30_000)
.build_and_unwrap_contract();
// Call contract with allowed storage value.
assert_ok!(builder::call(addr)
.gas_limit(GAS_LIMIT.set_ref_time(GAS_LIMIT.ref_time() * 2)) // we are copying a huge buffer,
.data(limits::PAYLOAD_BYTES.encode())
.build());
// Call contract with too large a storage value.
assert_err_ignore_postinfo!(
builder::call(addr).data((limits::PAYLOAD_BYTES + 1).encode()).build(),
Error::<Test>::ValueTooLarge,
);
});
}
// Fail out of fuel (ref_time weight) in the engine.
#[test]
fn run_out_of_fuel_engine() {
let (wasm, _code_hash) = compile_module("run_out_of_gas").unwrap();
ExtBuilder::default().existential_deposit(50).build().execute_with(|| {
let min_balance = Contracts::min_balance();
let _ = <Test as Config>::Currency::set_balance(&ALICE, 1_000_000);
let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm))
.value(100 * min_balance)
.build_and_unwrap_contract();
// Call the contract with a fixed gas limit. It must run out of gas because it just
// loops forever.
assert_err_ignore_postinfo!(
builder::call(addr)
.gas_limit(Weight::from_parts(10_000_000_000, u64::MAX))
.build(),
Error::<Test>::OutOfGas,
);
});
}
// Fail out of fuel (ref_time weight) in the host.
#[test]
fn run_out_of_fuel_host() {
let (code, _hash) = compile_module("chain_extension").unwrap();
ExtBuilder::default().existential_deposit(50).build().execute_with(|| {
let min_balance = Contracts::min_balance();
let _ = <Test as Config>::Currency::set_balance(&ALICE, 1000 * min_balance);
let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(code))
.value(min_balance * 100)
.build_and_unwrap_contract();
let gas_limit = Weight::from_parts(u32::MAX as u64, GAS_LIMIT.proof_size());
// Use chain extension to charge more ref_time than it is available.
let result = builder::bare_call(addr)
.gas_limit(gas_limit)
.data(ExtensionInput { extension_id: 0, func_id: 2, extra: &u32::MAX.encode() }.into())
.build()
.result;
assert_err!(result, <Error<Test>>::OutOfGas);
});
}
#[test]
fn gas_syncs_work() {
let (code, _code_hash) = compile_module("caller_is_origin_n").unwrap();
ExtBuilder::default().existential_deposit(200).build().execute_with(|| {
let _ = <Test as Config>::Currency::set_balance(&ALICE, 1_000_000);
let contract = builder::bare_instantiate(Code::Upload(code)).build_and_unwrap_contract();
let result = builder::bare_call(contract.addr).data(0u32.encode()).build();
assert_ok!(result.result);
let engine_consumed_noop = result.gas_consumed.ref_time();
let result = builder::bare_call(contract.addr).data(1u32.encode()).build();
assert_ok!(result.result);
let gas_consumed_once = result.gas_consumed.ref_time();
let host_consumed_once = <Test as Config>::WeightInfo::seal_caller_is_origin().ref_time();
let engine_consumed_once = gas_consumed_once - host_consumed_once - engine_consumed_noop;
let result = builder::bare_call(contract.addr).data(2u32.encode()).build();
assert_ok!(result.result);
let gas_consumed_twice = result.gas_consumed.ref_time();
let host_consumed_twice = host_consumed_once * 2;
let engine_consumed_twice = gas_consumed_twice - host_consumed_twice - engine_consumed_noop;
// Second contract just repeats first contract's instructions twice.
// If runtime syncs gas with the engine properly, this should pass.
assert_eq!(engine_consumed_twice, engine_consumed_once * 2);
});
}
/// Check that contracts with the same account id have different trie ids.
/// Check the `Nonce` storage item for more information.
#[test]
fn instantiate_unique_trie_id() {
let (wasm, code_hash) = compile_module("self_destruct").unwrap();
ExtBuilder::default().existential_deposit(500).build().execute_with(|| {
let _ = <Test as Config>::Currency::set_balance(&ALICE, 1_000_000);
Contracts::upload_code(RuntimeOrigin::signed(ALICE), wasm, deposit_limit::<Test>())
.unwrap();
// Instantiate the contract and store its trie id for later comparison.
let Contract { addr, .. } =
builder::bare_instantiate(Code::Existing(code_hash)).build_and_unwrap_contract();
let trie_id = get_contract(&addr).trie_id;
// Try to instantiate it again without termination should yield an error.
assert_err_ignore_postinfo!(
builder::instantiate(code_hash).build(),
<Error<Test>>::DuplicateContract,
);
// Terminate the contract.
assert_ok!(builder::call(addr).build());
// Re-Instantiate after termination.
assert_ok!(builder::instantiate(code_hash).build());
// Trie ids shouldn't match or we might have a collision
assert_ne!(trie_id, get_contract(&addr).trie_id);
});
}
#[test]
fn storage_work() {
let (code, _code_hash) = compile_module("storage").unwrap();
ExtBuilder::default().build().execute_with(|| {
let _ = <Test as Config>::Currency::set_balance(&ALICE, 1_000_000);
let min_balance = Contracts::min_balance();
let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(code))
.value(min_balance * 100)
.build_and_unwrap_contract();
builder::bare_call(addr).build_and_unwrap_result();
});
}
#[test]
fn storage_max_value_limit() {
let (wasm, _code_hash) = compile_module("storage_size").unwrap();
ExtBuilder::default().existential_deposit(50).build().execute_with(|| {
// Create
let _ = <Test as Config>::Currency::set_balance(&ALICE, 1_000_000);
let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm))
.value(30_000)
.build_and_unwrap_contract();
get_contract(&addr);
// Call contract with allowed storage value.
assert_ok!(builder::call(addr)
.gas_limit(GAS_LIMIT.set_ref_time(GAS_LIMIT.ref_time() * 2)) // we are copying a huge buffer
.data(limits::PAYLOAD_BYTES.encode())
.build());
// Call contract with too large a storage value.
assert_err_ignore_postinfo!(
builder::call(addr).data((limits::PAYLOAD_BYTES + 1).encode()).build(),
Error::<Test>::ValueTooLarge,
);
});
}
#[test]
fn transient_storage_work() {
let (code, _code_hash) = compile_module("transient_storage").unwrap();
ExtBuilder::default().build().execute_with(|| {
let _ = <Test as Config>::Currency::set_balance(&ALICE, 1_000_000);
let min_balance = Contracts::min_balance();
let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(code))
.value(min_balance * 100)
.build_and_unwrap_contract();
builder::bare_call(addr).build_and_unwrap_result();
});
}
#[test]
fn transient_storage_limit_in_call() {
let (wasm_caller, _code_hash_caller) =
compile_module("create_transient_storage_and_call").unwrap();
let (wasm_callee, _code_hash_callee) = compile_module("set_transient_storage").unwrap();
ExtBuilder::default().build().execute_with(|| {
let _ = <Test as Config>::Currency::set_balance(&ALICE, 1_000_000);
// Create both contracts: Constructors do nothing.
let Contract { addr: addr_caller, .. } =
builder::bare_instantiate(Code::Upload(wasm_caller)).build_and_unwrap_contract();
let Contract { addr: addr_callee, .. } =
builder::bare_instantiate(Code::Upload(wasm_callee)).build_and_unwrap_contract();
// Call contracts with storage values within the limit.
// Caller and Callee contracts each set a transient storage value of size 100.
assert_ok!(builder::call(addr_caller)
.data((100u32, 100u32, &addr_callee).encode())
.build(),);
// Call a contract with a storage value that is too large.
// Limit exceeded in the caller contract.
assert_err_ignore_postinfo!(
builder::call(addr_caller)
.data((4u32 * 1024u32, 200u32, &addr_callee).encode())
.build(),
<Error<Test>>::OutOfTransientStorage,
);
// Call a contract with a storage value that is too large.
// Limit exceeded in the callee contract.
assert_err_ignore_postinfo!(