impls.rs 10.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
//
// 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 super::{
16
    hashing,
17
18
19
20
21
22
23
24
25
26
    Account,
    EnvInstance,
};
use crate::env::{
    call::{
        CallParams,
        InstantiateParams,
        ReturnType,
    },
    Env,
27
    EnvError,
28
29
    EnvTypes,
    Result,
Hero Bird's avatar
Hero Bird committed
30
    ReturnFlags,
31
32
33
    Topics,
    TypedEnv,
};
34
use core::convert::TryInto;
Hero Bird's avatar
Hero Bird committed
35
use ink_primitives::Key;
36
use num_traits::Bounded;
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

impl EnvInstance {
    /// Returns the callee account.
    fn callee_account(&self) -> &Account {
        let callee = self
            .exec_context()
            .expect("uninitialized execution context")
            .callee
            .clone();
        self.accounts
            .get_account_off(&callee)
            .expect("callee account does not exist")
    }

    /// Returns the callee account as mutable reference.
    fn callee_account_mut(&mut self) -> &mut Account {
        let callee = self
            .exec_context()
            .expect("uninitialized execution context")
            .callee
            .clone();
        self.accounts
            .get_account_off_mut(&callee)
            .expect("callee account does not exist")
    }
}

impl Env for EnvInstance {
65
    fn set_contract_storage<V>(&mut self, key: &Key, value: &V)
66
67
68
69
    where
        V: scale::Encode,
    {
        self.callee_account_mut()
70
            .set_storage(*key, value)
71
72
73
            .expect("callee account is not a smart contract");
    }

Hero Bird's avatar
Hero Bird committed
74
    fn get_contract_storage<R>(&mut self, key: &Key) -> Result<Option<R>>
75
76
77
78
    where
        R: scale::Decode,
    {
        self.callee_account()
79
            .get_storage::<R>(*key)
Hero Bird's avatar
Hero Bird committed
80
            .map_err(Into::into)
81
82
    }

83
    fn clear_contract_storage(&mut self, key: &Key) {
84
        self.callee_account_mut()
85
            .clear_storage(*key)
86
87
88
            .expect("callee account is not a smart contract");
    }

89
90
91
92
    fn decode_input<T>(&mut self) -> Result<T>
    where
        T: scale::Decode,
    {
93
94
        self.exec_context()
            .map(|exec_ctx| &exec_ctx.call_data)
95
            .map(|call_data| scale::Encode::encode(call_data))
96
            .map_err(Into::into)
97
98
99
100
101
            .and_then(|encoded| {
                <T as scale::Decode>::decode(&mut &encoded[..])
                    .map_err(|_| scale::Error::from("could not decode input call data"))
                    .map_err(Into::into)
            })
102
103
    }

Hero Bird's avatar
Hero Bird committed
104
    fn return_value<R>(&mut self, flags: ReturnFlags, return_value: &R) -> !
105
106
107
108
109
110
111
    where
        R: scale::Encode,
    {
        let ctx = self
            .exec_context_mut()
            .expect("uninitialized execution context");
        ctx.output = Some(return_value.encode());
Hero Bird's avatar
Hero Bird committed
112
        std::process::exit(flags.into_u32() as i32)
113
114
115
116
117
    }

    fn println(&mut self, content: &str) {
        self.console.println(content)
    }
118
119
120
121
122
123

    fn hash_keccak_256(input: &[u8], output: &mut [u8; 32]) {
        hashing::keccak_256(input, output)
    }

    fn hash_blake2_256(input: &[u8], output: &mut [u8; 32]) {
124
        hashing::blake2b_256(input, output)
125
126
127
    }

    fn hash_blake2_128(input: &[u8], output: &mut [u8; 16]) {
128
        hashing::blake2b_128(input, output)
129
130
131
132
133
    }

    fn hash_sha2_256(input: &[u8], output: &mut [u8; 32]) {
        hashing::sha2_256(input, output)
    }
Hero Bird's avatar
Hero Bird committed
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

    #[cfg(feature = "ink-unstable-chain-extensions")]
    fn call_chain_extension<I, O>(&mut self, func_id: u32, input: &I) -> Result<O>
    where
        I: scale::Codec + 'static,
        O: scale::Codec + 'static,
    {
        self.chain_extension_handler.eval(func_id, input)
    }
}

impl EnvInstance {
    fn transfer_impl<T>(&mut self, destination: T::AccountId, value: T::Balance) -> Result<()>
    where
        T: EnvTypes,
    {
        let src_id = self.account_id::<T>()?;
        let src_value = self
            .accounts
            .get_account::<T>(&src_id)
            .expect("account of executed contract must exist")
            .balance::<T>()?;
        if src_value < value {
            return Err(EnvError::TransferFailed)
        }
        let dst_value = self
            .accounts
            .get_or_create_account::<T>(&destination)
            .balance::<T>()?;
        self.accounts
            .get_account_mut::<T>(&src_id)
            .expect("account of executed contract must exist")
            .set_balance::<T>(src_value - value)?;
        self.accounts
            .get_account_mut::<T>(&destination)
            .expect("the account must exist already or has just been created")
            .set_balance::<T>(dst_value + value)?;
        Ok(())
    }
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
}

impl TypedEnv for EnvInstance {
    fn caller<T: EnvTypes>(&mut self) -> Result<T::AccountId> {
        self.exec_context()
            .expect("uninitialized execution context")
            .caller::<T>()
            .map_err(|_| scale::Error::from("could not decode caller"))
            .map_err(Into::into)
    }

    fn transferred_balance<T: EnvTypes>(&mut self) -> Result<T::Balance> {
        self.exec_context()
            .expect("uninitialized execution context")
            .transferred_value::<T>()
            .map_err(|_| scale::Error::from("could not decode transferred balance"))
            .map_err(Into::into)
    }

192
    /// Emulates gas price calculation
Hero Bird's avatar
Hero Bird committed
193
    fn weight_to_fee<T: EnvTypes>(&mut self, gas: u64) -> Result<T::Balance> {
194
195
        use crate::env::arithmetic::Saturating as _;

Hero Bird's avatar
Hero Bird committed
196
197
        let gas_price = self
            .chain_spec
198
            .gas_price::<T>()
199
200
            .map_err(|_| scale::Error::from("could not decode gas price"))?;

Hero Bird's avatar
Hero Bird committed
201
202
        Ok(gas_price
            .saturating_mul(gas.try_into().unwrap_or_else(|_| Bounded::max_value())))
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
    }

    fn gas_left<T: EnvTypes>(&mut self) -> Result<T::Balance> {
        self.exec_context()
            .expect("uninitialized execution context")
            .gas::<T>()
            .map_err(|_| scale::Error::from("could not decode gas left"))
            .map_err(Into::into)
    }

    fn block_timestamp<T: EnvTypes>(&mut self) -> Result<T::Timestamp> {
        self.current_block()
            .expect("uninitialized execution context")
            .timestamp::<T>()
            .map_err(|_| scale::Error::from("could not decode block time"))
            .map_err(Into::into)
    }

    fn account_id<T: EnvTypes>(&mut self) -> Result<T::AccountId> {
        self.exec_context()
            .expect("uninitialized execution context")
            .callee::<T>()
            .map_err(|_| scale::Error::from("could not decode callee"))
            .map_err(Into::into)
    }

    fn balance<T: EnvTypes>(&mut self) -> Result<T::Balance> {
        self.callee_account()
            .balance::<T>()
            .map_err(|_| scale::Error::from("could not decode callee balance"))
            .map_err(Into::into)
    }

    fn rent_allowance<T: EnvTypes>(&mut self) -> Result<T::Balance> {
        self.callee_account()
            .rent_allowance::<T>()
            .map_err(|_| scale::Error::from("could not decode callee rent allowance"))
            .map_err(Into::into)
    }

    fn block_number<T: EnvTypes>(&mut self) -> Result<T::BlockNumber> {
        self.current_block()
            .expect("uninitialized execution context")
            .number::<T>()
            .map_err(|_| scale::Error::from("could not decode block number"))
            .map_err(Into::into)
    }

    fn minimum_balance<T: EnvTypes>(&mut self) -> Result<T::Balance> {
        self.chain_spec
            .minimum_balance::<T>()
            .map_err(|_| scale::Error::from("could not decode minimum balance"))
            .map_err(Into::into)
    }

    fn tombstone_deposit<T: EnvTypes>(&mut self) -> Result<T::Balance> {
        self.chain_spec
            .tombstone_deposit::<T>()
            .map_err(|_| scale::Error::from("could not decode tombstone deposit"))
            .map_err(Into::into)
    }

    fn emit_event<T, Event>(&mut self, new_event: Event)
    where
        T: EnvTypes,
        Event: Topics<T> + scale::Encode,
    {
        self.emitted_events.record::<T, Event>(new_event)
    }

    fn set_rent_allowance<T>(&mut self, new_rent_allowance: T::Balance)
    where
        T: EnvTypes,
    {
        self.callee_account_mut()
            .set_rent_allowance::<T>(new_rent_allowance)
            .expect("could not encode rent allowance")
    }

282
283
284
285
    fn invoke_contract<T, Args>(
        &mut self,
        _call_params: &CallParams<T, Args, ()>,
    ) -> Result<()>
286
287
    where
        T: EnvTypes,
288
        Args: scale::Encode,
289
290
291
292
    {
        unimplemented!("off-chain environment does not support contract invokation")
    }

293
    fn eval_contract<T, Args, R>(
294
        &mut self,
295
        _call_params: &CallParams<T, Args, ReturnType<R>>,
296
297
298
    ) -> Result<R>
    where
        T: EnvTypes,
299
        Args: scale::Encode,
300
301
302
303
304
        R: scale::Decode,
    {
        unimplemented!("off-chain environment does not support contract evaluation")
    }

305
    fn instantiate_contract<T, Args, C>(
306
        &mut self,
307
        _params: &InstantiateParams<T, Args, C>,
308
309
310
    ) -> Result<T::AccountId>
    where
        T: EnvTypes,
311
        Args: scale::Encode,
312
313
314
315
    {
        unimplemented!("off-chain environment does not support contract instantiation")
    }

316
317
318
319
320
321
322
    fn terminate_contract<T>(&mut self, _beneficiary: T::AccountId) -> !
    where
        T: EnvTypes,
    {
        unimplemented!("off-chain environment does not support contract termination")
    }

323
324
325
326
327
328
329
330
331
332
333
334
    fn restore_contract<T>(
        &mut self,
        _account_id: T::AccountId,
        _code_hash: T::Hash,
        _rent_allowance: T::Balance,
        _filtered_keys: &[Key],
    ) where
        T: EnvTypes,
    {
        unimplemented!("off-chain environment does not support contract restoration")
    }

335
336
337
338
    fn transfer<T>(&mut self, destination: T::AccountId, value: T::Balance) -> Result<()>
    where
        T: EnvTypes,
    {
Hero Bird's avatar
Hero Bird committed
339
        self.transfer_impl::<T>(destination, value)
340
341
    }

342
343
344
345
346
347
348
349
350
351
    fn random<T>(&mut self, subject: &[u8]) -> Result<T::Hash>
    where
        T: EnvTypes,
    {
        self.current_block()
            .expect("uninitialized execution context")
            .random::<T>(subject)
            .map_err(Into::into)
    }
}