-
Notifications
You must be signed in to change notification settings - Fork 450
/
Copy pathimpls.rs
459 lines (415 loc) · 14.2 KB
/
impls.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
// Copyright 2018-2021 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::{
hashing,
Account,
EnvInstance,
};
use crate::{
call::{
utils::ReturnType,
CallParams,
CreateParams,
},
hash::{
Blake2x128,
Blake2x256,
CryptoHash,
HashOutput,
Keccak256,
Sha2x256,
},
topics::Topics,
EnvBackend,
Environment,
Error,
Result,
ReturnFlags,
TypedEnvBackend,
};
use core::convert::TryInto;
use ink_primitives::Key;
use num_traits::Bounded;
const UNITIALIZED_EXEC_CONTEXT: &str = "unitialized execution context: \
a possible source of error could be that you are using `#[test]` instead of `#[ink::test]`.";
impl EnvInstance {
/// Returns the callee account.
fn callee_account(&self) -> &Account {
let callee = self
.exec_context()
.expect(UNITIALIZED_EXEC_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(UNITIALIZED_EXEC_CONTEXT)
.callee
.clone();
self.accounts
.get_account_off_mut(&callee)
.expect("callee account does not exist")
}
}
impl CryptoHash for Blake2x128 {
fn hash(input: &[u8], output: &mut <Self as HashOutput>::Type) {
type OutputType = [u8; 16];
static_assertions::assert_type_eq_all!(
<Blake2x128 as HashOutput>::Type,
OutputType
);
let output: &mut OutputType = arrayref::array_mut_ref!(output, 0, 16);
hashing::blake2b_128(input, output);
}
}
impl CryptoHash for Blake2x256 {
fn hash(input: &[u8], output: &mut <Self as HashOutput>::Type) {
type OutputType = [u8; 32];
static_assertions::assert_type_eq_all!(
<Blake2x256 as HashOutput>::Type,
OutputType
);
let output: &mut OutputType = arrayref::array_mut_ref!(output, 0, 32);
hashing::blake2b_256(input, output);
}
}
impl CryptoHash for Sha2x256 {
fn hash(input: &[u8], output: &mut <Self as HashOutput>::Type) {
type OutputType = [u8; 32];
static_assertions::assert_type_eq_all!(
<Sha2x256 as HashOutput>::Type,
OutputType
);
let output: &mut OutputType = arrayref::array_mut_ref!(output, 0, 32);
hashing::sha2_256(input, output);
}
}
impl CryptoHash for Keccak256 {
fn hash(input: &[u8], output: &mut <Self as HashOutput>::Type) {
type OutputType = [u8; 32];
static_assertions::assert_type_eq_all!(
<Keccak256 as HashOutput>::Type,
OutputType
);
let output: &mut OutputType = arrayref::array_mut_ref!(output, 0, 32);
hashing::keccak_256(input, output);
}
}
impl EnvBackend for EnvInstance {
fn set_contract_storage<V>(&mut self, key: &Key, value: &V)
where
V: scale::Encode,
{
self.callee_account_mut()
.set_storage(*key, value)
.expect("callee account is not a smart contract");
}
fn get_contract_storage<R>(&mut self, key: &Key) -> Result<Option<R>>
where
R: scale::Decode,
{
self.callee_account()
.get_storage::<R>(*key)
.map_err(Into::into)
}
fn clear_contract_storage(&mut self, key: &Key) {
if !self.clear_storage_disabled {
self.callee_account_mut()
.clear_storage(*key)
.expect("callee account is not a smart contract");
}
}
fn decode_input<T>(&mut self) -> Result<T>
where
T: scale::Decode,
{
self.exec_context()
.map(|exec_ctx| &exec_ctx.call_data)
.map(|call_data| scale::Encode::encode(call_data))
.map_err(Into::into)
.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)
})
}
fn return_value<R>(&mut self, flags: ReturnFlags, return_value: &R) -> !
where
R: scale::Encode,
{
let ctx = self.exec_context_mut().expect(UNITIALIZED_EXEC_CONTEXT);
ctx.output = Some(return_value.encode());
std::process::exit(flags.into_u32() as i32)
}
fn debug_message(&mut self, message: &str) {
self.debug_buf.debug_message(message)
}
fn hash_bytes<H>(&mut self, input: &[u8], output: &mut <H as HashOutput>::Type)
where
H: CryptoHash,
{
<H as CryptoHash>::hash(input, output)
}
fn hash_encoded<H, T>(&mut self, input: &T, output: &mut <H as HashOutput>::Type)
where
H: CryptoHash,
T: scale::Encode,
{
let encoded = input.encode();
self.hash_bytes::<H>(&encoded[..], output)
}
fn call_chain_extension<I, T, E, ErrorCode, F, D>(
&mut self,
func_id: u32,
input: &I,
status_to_result: F,
decode_to_result: D,
) -> ::core::result::Result<T, E>
where
I: scale::Encode,
T: scale::Decode,
E: From<ErrorCode>,
F: FnOnce(u32) -> ::core::result::Result<(), ErrorCode>,
D: FnOnce(&[u8]) -> ::core::result::Result<T, E>,
{
let encoded_input = input.encode();
let (status_code, mut output) = self
.chain_extension_handler
.eval(func_id, &encoded_input)
.expect("encountered unexpected missing chain extension method");
status_to_result(status_code)?;
let decoded = decode_to_result(&mut output)?;
Ok(decoded)
}
}
impl EnvInstance {
fn transfer_impl<T>(
&mut self,
destination: &T::AccountId,
value: T::Balance,
) -> Result<()>
where
T: Environment,
{
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(Error::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(())
}
// Remove the calling account and transfer remaining balance.
//
// This function never returns. Either the termination was successful and the
// execution of the destroyed contract is halted. Or it failed during the termination
// which is considered fatal.
fn terminate_contract_impl<T>(&mut self, beneficiary: T::AccountId) -> !
where
T: Environment,
{
// Send the remaining balance to the beneficiary
let all: T::Balance = self.balance::<T>().expect("could not decode balance");
self.transfer_impl::<T>(&beneficiary, all)
.expect("transfer did not work ");
// Remove account
let contract_id = self.account_id::<T>().expect("could not decode account id");
self.accounts.remove_account::<T>(contract_id);
// The on-chain implementation would set a tombstone with a code hash here
// and remove the contract storage subsequently. Both is not easily achievable
// with our current off-chain env, hence we left it out here for the moment.
// Encode the result of the termination and panic with it.
// This enables testing for the proper result and makes sure this
// method returns `Never`.
let res = crate::test::ContractTerminationResult::<T> {
beneficiary,
transferred: all,
};
std::panic::panic_any(scale::Encode::encode(&res));
}
}
impl TypedEnvBackend for EnvInstance {
fn caller<T: Environment>(&mut self) -> Result<T::AccountId> {
self.exec_context()
.expect(UNITIALIZED_EXEC_CONTEXT)
.caller::<T>()
.map_err(|_| scale::Error::from("could not decode caller"))
.map_err(Into::into)
}
fn transferred_balance<T: Environment>(&mut self) -> Result<T::Balance> {
self.exec_context()
.expect(UNITIALIZED_EXEC_CONTEXT)
.transferred_value::<T>()
.map_err(|_| scale::Error::from("could not decode transferred balance"))
.map_err(Into::into)
}
/// Emulates gas price calculation
fn weight_to_fee<T: Environment>(&mut self, gas: u64) -> Result<T::Balance> {
use crate::arithmetic::Saturating as _;
let gas_price = self
.chain_spec
.gas_price::<T>()
.map_err(|_| scale::Error::from("could not decode gas price"))?;
Ok(gas_price
.saturating_mul(gas.try_into().unwrap_or_else(|_| Bounded::max_value())))
}
fn gas_left<T: Environment>(&mut self) -> Result<T::Balance> {
self.exec_context()
.expect(UNITIALIZED_EXEC_CONTEXT)
.gas::<T>()
.map_err(|_| scale::Error::from("could not decode gas left"))
.map_err(Into::into)
}
fn block_timestamp<T: Environment>(&mut self) -> Result<T::Timestamp> {
self.current_block()
.expect(UNITIALIZED_EXEC_CONTEXT)
.timestamp::<T>()
.map_err(|_| scale::Error::from("could not decode block time"))
.map_err(Into::into)
}
fn account_id<T: Environment>(&mut self) -> Result<T::AccountId> {
self.exec_context()
.expect(UNITIALIZED_EXEC_CONTEXT)
.callee::<T>()
.map_err(|_| scale::Error::from("could not decode callee"))
.map_err(Into::into)
}
fn balance<T: Environment>(&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: Environment>(&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: Environment>(&mut self) -> Result<T::BlockNumber> {
self.current_block()
.expect(UNITIALIZED_EXEC_CONTEXT)
.number::<T>()
.map_err(|_| scale::Error::from("could not decode block number"))
.map_err(Into::into)
}
fn minimum_balance<T: Environment>(&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: Environment>(&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: Environment,
Event: Topics + scale::Encode,
{
self.emitted_events.record::<T, Event>(new_event)
}
fn set_rent_allowance<T>(&mut self, new_rent_allowance: T::Balance)
where
T: Environment,
{
self.callee_account_mut()
.set_rent_allowance::<T>(new_rent_allowance)
.expect("could not encode rent allowance")
}
fn invoke_contract<T, Args>(
&mut self,
_call_params: &CallParams<T, Args, ()>,
) -> Result<()>
where
T: Environment,
Args: scale::Encode,
{
unimplemented!("off-chain environment does not support contract invocation")
}
fn eval_contract<T, Args, R>(
&mut self,
_call_params: &CallParams<T, Args, ReturnType<R>>,
) -> Result<R>
where
T: Environment,
Args: scale::Encode,
R: scale::Decode,
{
unimplemented!("off-chain environment does not support contract evaluation")
}
fn instantiate_contract<T, Args, Salt, C>(
&mut self,
_params: &CreateParams<T, Args, Salt, C>,
) -> Result<T::AccountId>
where
T: Environment,
Args: scale::Encode,
{
unimplemented!("off-chain environment does not support contract instantiation")
}
fn terminate_contract<T>(&mut self, beneficiary: T::AccountId) -> !
where
T: Environment,
{
self.terminate_contract_impl::<T>(beneficiary)
}
fn restore_contract<T>(
&mut self,
_account_id: T::AccountId,
_code_hash: T::Hash,
_rent_allowance: T::Balance,
_filtered_keys: &[Key],
) where
T: Environment,
{
unimplemented!("off-chain environment does not support contract restoration")
}
fn transfer<T>(&mut self, destination: T::AccountId, value: T::Balance) -> Result<()>
where
T: Environment,
{
self.transfer_impl::<T>(&destination, value)
}
fn random<T>(&mut self, subject: &[u8]) -> Result<(T::Hash, T::BlockNumber)>
where
T: Environment,
{
let block = self.current_block().expect(UNITIALIZED_EXEC_CONTEXT);
Ok((block.random::<T>(subject)?, block.number::<T>()?))
}
}