This repository was 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.7k
Expand file tree
/
Copy pathmod.rs
More file actions
1773 lines (1555 loc) · 40.4 KB
/
mod.rs
File metadata and controls
1773 lines (1555 loc) · 40.4 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.
//! This module provides a means for executing contracts
//! represented in wasm.
use crate::{
CodeHash, Schedule, Config,
wasm::env_def::FunctionImplProvider,
exec::Ext,
gas::GasMeter,
};
use sp_std::prelude::*;
use sp_core::crypto::UncheckedFrom;
use codec::{Encode, Decode};
#[macro_use]
mod env_def;
mod code_cache;
mod prepare;
mod runtime;
use self::code_cache::load as load_code;
use pallet_contracts_primitives::ExecResult;
pub use self::code_cache::save as save_code;
#[cfg(feature = "runtime-benchmarks")]
pub use self::code_cache::save_raw as save_code_raw;
pub use self::runtime::{ReturnCode, Runtime, RuntimeToken};
/// A prepared wasm module ready for execution.
#[derive(Clone, Encode, Decode)]
pub struct PrefabWasmModule {
/// Version of the schedule with which the code was instrumented.
#[codec(compact)]
schedule_version: u32,
#[codec(compact)]
initial: u32,
#[codec(compact)]
maximum: u32,
/// This field is reserved for future evolution of format.
///
/// Basically, for now this field will be serialized as `None`. In the future
/// we would be able to extend this structure with.
_reserved: Option<()>,
/// Code instrumented with the latest schedule.
code: Vec<u8>,
}
/// Wasm executable loaded by `WasmLoader` and executed by `WasmVm`.
pub struct WasmExecutable {
entrypoint_name: &'static str,
prefab_module: PrefabWasmModule,
}
/// Loader which fetches `WasmExecutable` from the code cache.
pub struct WasmLoader<'a, T: Config> {
schedule: &'a Schedule<T>,
}
impl<'a, T: Config> WasmLoader<'a, T> where T::AccountId: UncheckedFrom<T::Hash> + AsRef<[u8]> {
pub fn new(schedule: &'a Schedule<T>) -> Self {
WasmLoader { schedule }
}
}
impl<'a, T: Config> crate::exec::Loader<T> for WasmLoader<'a, T>
where
T::AccountId: UncheckedFrom<T::Hash> + AsRef<[u8]>
{
type Executable = WasmExecutable;
fn load_init(&self, code_hash: &CodeHash<T>) -> Result<WasmExecutable, &'static str> {
let prefab_module = load_code::<T>(code_hash, self.schedule)?;
Ok(WasmExecutable {
entrypoint_name: "deploy",
prefab_module,
})
}
fn load_main(&self, code_hash: &CodeHash<T>) -> Result<WasmExecutable, &'static str> {
let prefab_module = load_code::<T>(code_hash, self.schedule)?;
Ok(WasmExecutable {
entrypoint_name: "call",
prefab_module,
})
}
}
/// Implementation of `Vm` that takes `WasmExecutable` and executes it.
pub struct WasmVm<'a, T: Config> where T::AccountId: UncheckedFrom<T::Hash> + AsRef<[u8]> {
schedule: &'a Schedule<T>,
}
impl<'a, T: Config> WasmVm<'a, T> where T::AccountId: UncheckedFrom<T::Hash> + AsRef<[u8]> {
pub fn new(schedule: &'a Schedule<T>) -> Self {
WasmVm { schedule }
}
}
impl<'a, T: Config> crate::exec::Vm<T> for WasmVm<'a, T>
where
T::AccountId: UncheckedFrom<T::Hash> + AsRef<[u8]>
{
type Executable = WasmExecutable;
fn execute<E: Ext<T = T>>(
&self,
exec: &WasmExecutable,
mut ext: E,
input_data: Vec<u8>,
gas_meter: &mut GasMeter<E::T>,
) -> ExecResult {
let memory =
sp_sandbox::Memory::new(exec.prefab_module.initial, Some(exec.prefab_module.maximum))
.unwrap_or_else(|_| {
// unlike `.expect`, explicit panic preserves the source location.
// Needed as we can't use `RUST_BACKTRACE` in here.
panic!(
"exec.prefab_module.initial can't be greater than exec.prefab_module.maximum;
thus Memory::new must not fail;
qed"
)
});
let mut imports = sp_sandbox::EnvironmentDefinitionBuilder::new();
imports.add_memory(self::prepare::IMPORT_MODULE_MEMORY, "memory", memory.clone());
runtime::Env::impls(&mut |name, func_ptr| {
imports.add_host_func(self::prepare::IMPORT_MODULE_FN, name, func_ptr);
});
let mut runtime = Runtime::new(
&mut ext,
input_data,
&self.schedule,
memory,
gas_meter,
);
// Instantiate the instance from the instrumented module code and invoke the contract
// entrypoint.
let result = sp_sandbox::Instance::new(&exec.prefab_module.code, &imports, &mut runtime)
.and_then(|mut instance| instance.invoke(exec.entrypoint_name, &[], &mut runtime));
runtime.to_execution_result(result)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
CodeHash, BalanceOf, Error, Module as Contracts,
exec::{Ext, StorageKey, AccountIdOf},
gas::{Gas, GasMeter},
tests::{Test, Call, ALICE, BOB},
wasm::prepare::prepare_contract,
};
use std::collections::HashMap;
use sp_core::H256;
use hex_literal::hex;
use sp_runtime::DispatchError;
use frame_support::{dispatch::DispatchResult, weights::Weight};
use assert_matches::assert_matches;
use pallet_contracts_primitives::{ExecReturnValue, ReturnFlags, ExecError, ErrorOrigin};
const GAS_LIMIT: Gas = 10_000_000_000;
#[derive(Debug, PartialEq, Eq)]
struct DispatchEntry(Call);
#[derive(Debug, PartialEq, Eq)]
struct RestoreEntry {
dest: AccountIdOf<Test>,
code_hash: H256,
rent_allowance: u64,
delta: Vec<StorageKey>,
}
#[derive(Debug, PartialEq, Eq)]
struct InstantiateEntry {
code_hash: H256,
endowment: 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,
data: Vec<u8>,
}
#[derive(Default)]
pub struct MockExt {
storage: HashMap<StorageKey, Vec<u8>>,
rent_allowance: u64,
instantiates: Vec<InstantiateEntry>,
terminations: Vec<TerminationEntry>,
transfers: Vec<TransferEntry>,
restores: Vec<RestoreEntry>,
// (topics, data)
events: Vec<(Vec<H256>, Vec<u8>)>,
}
impl Ext for MockExt {
type T = Test;
fn get_storage(&self, key: &StorageKey) -> Option<Vec<u8>> {
self.storage.get(key).cloned()
}
fn set_storage(&mut self, key: StorageKey, value: Option<Vec<u8>>) -> DispatchResult {
*self.storage.entry(key).or_insert(Vec::new()) = value.unwrap_or(Vec::new());
Ok(())
}
fn instantiate(
&mut self,
code_hash: &CodeHash<Test>,
endowment: u64,
gas_meter: &mut GasMeter<Test>,
data: Vec<u8>,
salt: &[u8],
) -> Result<(AccountIdOf<Self::T>, ExecReturnValue), ExecError> {
self.instantiates.push(InstantiateEntry {
code_hash: code_hash.clone(),
endowment,
data: data.to_vec(),
gas_left: gas_meter.gas_left(),
salt: salt.to_vec(),
});
Ok((
Contracts::<Test>::contract_address(&ALICE, code_hash, salt),
ExecReturnValue {
flags: ReturnFlags::empty(),
data: Vec::new(),
},
))
}
fn transfer(
&mut self,
to: &AccountIdOf<Self::T>,
value: u64,
) -> Result<(), DispatchError> {
self.transfers.push(TransferEntry {
to: to.clone(),
value,
data: Vec::new(),
});
Ok(())
}
fn call(
&mut self,
to: &AccountIdOf<Self::T>,
value: u64,
_gas_meter: &mut GasMeter<Test>,
data: Vec<u8>,
) -> ExecResult {
self.transfers.push(TransferEntry {
to: to.clone(),
value,
data: data,
});
// Assume for now that it was just a plain transfer.
// TODO: Add tests for different call outcomes.
Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: Vec::new() })
}
fn terminate(
&mut self,
beneficiary: &AccountIdOf<Self::T>,
) -> Result<(), DispatchError> {
self.terminations.push(TerminationEntry {
beneficiary: beneficiary.clone(),
});
Ok(())
}
fn restore_to(
&mut self,
dest: AccountIdOf<Self::T>,
code_hash: H256,
rent_allowance: u64,
delta: Vec<StorageKey>,
) -> Result<(), DispatchError> {
self.restores.push(RestoreEntry {
dest,
code_hash,
rent_allowance,
delta,
});
Ok(())
}
fn caller(&self) -> &AccountIdOf<Self::T> {
&ALICE
}
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 tombstone_deposit(&self) -> u64 {
16
}
fn random(&self, subject: &[u8]) -> H256 {
H256::from_slice(subject)
}
fn deposit_event(&mut self, topics: Vec<H256>, data: Vec<u8>) {
self.events.push((topics, data))
}
fn set_rent_allowance(&mut self, rent_allowance: u64) {
self.rent_allowance = rent_allowance;
}
fn rent_allowance(&self) -> u64 {
self.rent_allowance
}
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.into())
}
}
impl Ext for &mut MockExt {
type T = <MockExt as Ext>::T;
fn get_storage(&self, key: &[u8; 32]) -> Option<Vec<u8>> {
(**self).get_storage(key)
}
fn set_storage(&mut self, key: [u8; 32], value: Option<Vec<u8>>) -> DispatchResult {
(**self).set_storage(key, value)
}
fn instantiate(
&mut self,
code: &CodeHash<Test>,
value: u64,
gas_meter: &mut GasMeter<Test>,
input_data: Vec<u8>,
salt: &[u8],
) -> Result<(AccountIdOf<Self::T>, ExecReturnValue), ExecError> {
(**self).instantiate(code, value, gas_meter, input_data, salt)
}
fn transfer(
&mut self,
to: &AccountIdOf<Self::T>,
value: u64,
) -> Result<(), DispatchError> {
(**self).transfer(to, value)
}
fn terminate(
&mut self,
beneficiary: &AccountIdOf<Self::T>,
) -> Result<(), DispatchError> {
(**self).terminate(beneficiary)
}
fn call(
&mut self,
to: &AccountIdOf<Self::T>,
value: u64,
gas_meter: &mut GasMeter<Test>,
input_data: Vec<u8>,
) -> ExecResult {
(**self).call(to, value, gas_meter, input_data)
}
fn restore_to(
&mut self,
dest: AccountIdOf<Self::T>,
code_hash: H256,
rent_allowance: u64,
delta: Vec<StorageKey>,
) -> Result<(), DispatchError> {
(**self).restore_to(
dest,
code_hash,
rent_allowance,
delta,
)
}
fn caller(&self) -> &AccountIdOf<Self::T> {
(**self).caller()
}
fn address(&self) -> &AccountIdOf<Self::T> {
(**self).address()
}
fn balance(&self) -> u64 {
(**self).balance()
}
fn value_transferred(&self) -> u64 {
(**self).value_transferred()
}
fn now(&self) -> &u64 {
(**self).now()
}
fn minimum_balance(&self) -> u64 {
(**self).minimum_balance()
}
fn tombstone_deposit(&self) -> u64 {
(**self).tombstone_deposit()
}
fn random(&self, subject: &[u8]) -> H256 {
(**self).random(subject)
}
fn deposit_event(&mut self, topics: Vec<H256>, data: Vec<u8>) {
(**self).deposit_event(topics, data)
}
fn set_rent_allowance(&mut self, rent_allowance: u64) {
(**self).set_rent_allowance(rent_allowance)
}
fn rent_allowance(&self) -> u64 {
(**self).rent_allowance()
}
fn block_number(&self) -> u64 {
(**self).block_number()
}
fn max_value_size(&self) -> u32 {
(**self).max_value_size()
}
fn get_weight_price(&self, weight: Weight) -> BalanceOf<Self::T> {
(**self).get_weight_price(weight)
}
}
fn execute<E: Ext>(
wat: &str,
input_data: Vec<u8>,
ext: E,
gas_meter: &mut GasMeter<E::T>,
) -> ExecResult
where
<E::T as frame_system::Config>::AccountId:
UncheckedFrom<<E::T as frame_system::Config>::Hash> + AsRef<[u8]>
{
use crate::exec::Vm;
let wasm = wat::parse_str(wat).unwrap();
let schedule = crate::Schedule::default();
let prefab_module =
prepare_contract::<super::runtime::Env, E::T>(&wasm, &schedule).unwrap();
let exec = WasmExecutable {
// Use a "call" convention.
entrypoint_name: "call",
prefab_module,
};
let cfg = Default::default();
let vm = WasmVm::new(&cfg);
vm.execute(&exec, ext, input_data, gas_meter)
}
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();
let _ = execute(
CODE_TRANSFER,
vec![],
&mut mock_ext,
&mut GasMeter::new(GAS_LIMIT),
).unwrap();
assert_eq!(
&mock_ext.transfers,
&[TransferEntry {
to: ALICE,
value: 153,
data: Vec::new(),
}]
);
}
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();
let _ = execute(
CODE_CALL,
vec![],
&mut mock_ext,
&mut GasMeter::new(GAS_LIMIT),
).unwrap();
assert_eq!(
&mock_ext.transfers,
&[TransferEntry {
to: ALICE,
value: 6,
data: vec![1, 2, 3, 4],
}]
);
}
const CODE_INSTANTIATE: &str = r#"
(module
;; seal_instantiate(
;; code_ptr: u32,
;; code_len: u32,
;; gas: u64,
;; value_ptr: u32,
;; value_len: u32,
;; input_data_ptr: u32,
;; input_data_len: u32,
;; input_data_len: u32,
;; address_ptr: u32,
;; address_len_ptr: u32,
;; output_ptr: u32,
;; output_len_ptr: u32
;; ) -> u32
(import "seal0" "seal_instantiate" (func $seal_instantiate
(param i32 i32 i64 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32) (result i32)
))
(import "env" "memory" (memory 1 1))
(func (export "call")
(drop
(call $seal_instantiate
(i32.const 16) ;; Pointer to `code_hash`
(i32.const 32) ;; Length of `code_hash`
(i64.const 0) ;; How much gas to devote for the execution. 0 = all.
(i32.const 4) ;; Pointer to the buffer with value to transfer
(i32.const 8) ;; Length of the buffer with value to transfer
(i32.const 12) ;; 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 address
(i32.const 0) ;; Length is ignored in this case
(i32.const 4294967295) ;; u32 max value is the sentinel value: do not copy output
(i32.const 0) ;; Length is ignored in this case
(i32.const 0) ;; salt_ptr
(i32.const 4) ;; salt_len
)
)
)
(func (export "deploy"))
;; Salt
(data (i32.const 0) "\42\43\44\45")
;; Amount of value to transfer.
;; Represented by u64 (8 bytes long) in little endian.
(data (i32.const 4) "\03\00\00\00\00\00\00\00")
;; Input data to pass to the contract being instantiated.
(data (i32.const 12) "\01\02\03\04")
;; Hash of code.
(data (i32.const 16)
"\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"
)
)
"#;
#[test]
fn contract_instantiate() {
let mut mock_ext = MockExt::default();
let _ = execute(
CODE_INSTANTIATE,
vec![],
&mut mock_ext,
&mut GasMeter::new(GAS_LIMIT),
).unwrap();
assert_matches!(
&mock_ext.instantiates[..],
[InstantiateEntry {
code_hash,
endowment: 3,
data,
gas_left: _,
salt,
}] if
code_hash == &[0x11; 32].into() &&
data == &vec![1, 2, 3, 4] &&
salt == &vec![0x42, 0x43, 0x44, 0x45]
);
}
const CODE_TERMINATE: &str = r#"
(module
;; seal_terminate(
;; beneficiary_ptr: u32,
;; beneficiary_len: u32,
;; )
(import "seal0" "seal_terminate" (func $seal_terminate (param i32 i32)))
(import "env" "memory" (memory 1 1))
(func (export "call")
(call $seal_terminate
(i32.const 4) ;; Pointer to "beneficiary" address.
(i32.const 32) ;; Length of "beneficiary" address.
)
)
(func (export "deploy"))
;; Beneficiary AccountId to transfer the funds.
(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"
)
)
"#;
#[test]
fn contract_terminate() {
let mut mock_ext = MockExt::default();
execute(
CODE_TERMINATE,
vec![],
&mut mock_ext,
&mut GasMeter::new(GAS_LIMIT),
).unwrap();
assert_eq!(
&mock_ext.terminations,
&[TerminationEntry {
beneficiary: ALICE,
}]
);
}
const CODE_TRANSFER_LIMITED_GAS: &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 228) ;; How much gas to devote for the execution.
(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 cas
)
)
)
(func (export "deploy"))
;; Destination AccountId to transfer the funds.
(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_limited_gas() {
let mut mock_ext = MockExt::default();
let _ = execute(
&CODE_TRANSFER_LIMITED_GAS,
vec![],
&mut mock_ext,
&mut GasMeter::new(GAS_LIMIT),
).unwrap();
assert_eq!(
&mock_ext.transfers,
&[TransferEntry {
to: ALICE,
value: 6,
data: vec![1, 2, 3, 4],
}]
);
}
const CODE_GET_STORAGE: &str = r#"
(module
(import "seal0" "seal_get_storage" (func $seal_get_storage (param i32 i32 i32) (result i32)))
(import "seal0" "seal_return" (func $seal_return (param i32 i32 i32)))
(import "env" "memory" (memory 1 1))
;; [0, 32) key for get storage
(data (i32.const 0)
"\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"
)
;; [32, 36) buffer size = 128 bytes
(data (i32.const 32) "\80")
;; [36; inf) buffer where the result is copied
(func $assert (param i32)
(block $ok
(br_if $ok
(get_local 0)
)
(unreachable)
)
)
(func (export "call")
(local $buf_size i32)
;; Load a storage value into contract memory.
(call $assert
(i32.eq
(call $seal_get_storage
(i32.const 0) ;; The pointer to the storage key to fetch
(i32.const 36) ;; Pointer to the output buffer
(i32.const 32) ;; Pointer to the size of the buffer
)
;; Return value 0 means that the value is found and there were
;; no errors.
(i32.const 0)
)
)
;; Find out the size of the buffer
(set_local $buf_size
(i32.load (i32.const 32))
)
;; Return the contents of the buffer
(call $seal_return
(i32.const 0)
(i32.const 36)
(get_local $buf_size)
)
;; env:seal_return doesn't return, so this is effectively unreachable.
(unreachable)
)
(func (export "deploy"))
)
"#;
#[test]
fn get_storage_puts_data_into_buf() {
let mut mock_ext = MockExt::default();
mock_ext
.storage
.insert([0x11; 32], [0x22; 32].to_vec());
let output = execute(
CODE_GET_STORAGE,
vec![],
mock_ext,
&mut GasMeter::new(GAS_LIMIT),
).unwrap();
assert_eq!(output, ExecReturnValue { flags: ReturnFlags::empty(), data: [0x22; 32].to_vec() });
}
/// calls `seal_caller` and compares the result with the constant 42.
const CODE_CALLER: &str = r#"
(module
(import "seal0" "seal_caller" (func $seal_caller (param i32 i32)))
(import "env" "memory" (memory 1 1))
;; size of our buffer is 32 bytes
(data (i32.const 32) "\20")
(func $assert (param i32)
(block $ok
(br_if $ok
(get_local 0)
)
(unreachable)
)
)
(func (export "call")
;; fill the buffer with the caller.
(call $seal_caller (i32.const 0) (i32.const 32))
;; assert len == 32
(call $assert
(i32.eq
(i32.load (i32.const 32))
(i32.const 32)
)
)
;; assert that the first 64 byte are the beginning of "ALICE"
(call $assert
(i64.eq
(i64.load (i32.const 0))
(i64.const 0x0101010101010101)
)
)
)
(func (export "deploy"))
)
"#;
#[test]
fn caller() {
let _ = execute(
CODE_CALLER,
vec![],
MockExt::default(),
&mut GasMeter::new(GAS_LIMIT),
).unwrap();
}
/// calls `seal_address` and compares the result with the constant 69.
const CODE_ADDRESS: &str = r#"
(module
(import "seal0" "seal_address" (func $seal_address (param i32 i32)))
(import "env" "memory" (memory 1 1))
;; size of our buffer is 32 bytes
(data (i32.const 32) "\20")
(func $assert (param i32)
(block $ok
(br_if $ok
(get_local 0)
)
(unreachable)
)
)
(func (export "call")
;; fill the buffer with the self address.
(call $seal_address (i32.const 0) (i32.const 32))
;; assert size == 32
(call $assert
(i32.eq
(i32.load (i32.const 32))
(i32.const 32)
)
)
;; assert that the first 64 byte are the beginning of "BOB"
(call $assert
(i64.eq
(i64.load (i32.const 0))
(i64.const 0x0202020202020202)
)
)
)
(func (export "deploy"))
)
"#;
#[test]
fn address() {
let _ = execute(
CODE_ADDRESS,
vec![],
MockExt::default(),
&mut GasMeter::new(GAS_LIMIT),
).unwrap();
}
const CODE_BALANCE: &str = r#"
(module
(import "seal0" "seal_balance" (func $seal_balance (param i32 i32)))
(import "env" "memory" (memory 1 1))
;; size of our buffer is 32 bytes
(data (i32.const 32) "\20")
(func $assert (param i32)
(block $ok
(br_if $ok
(get_local 0)
)
(unreachable)
)
)
(func (export "call")