-
Notifications
You must be signed in to change notification settings - Fork 478
Expand file tree
/
Copy pathbackend.rs
More file actions
640 lines (578 loc) · 21.9 KB
/
backend.rs
File metadata and controls
640 lines (578 loc) · 21.9 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
// Copyright (C) Use Ink (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.
#[cfg(feature = "xcm")]
use ink_primitives::Weight;
use ink_primitives::{
Address,
CodeHashErr,
H256,
U256,
sol::SolResultEncode,
types::Environment,
};
use ink_storage_traits::Storable;
pub use pallet_revive_uapi::ReturnFlags;
use crate::{
DecodeDispatch,
DispatchError,
Result,
call::{
Call,
CallParams,
ConstructorReturnType,
CreateParams,
DelegateCall,
FromAddr,
LimitParamsV2,
utils::{
DecodeMessageResult,
EncodeArgsWith,
},
},
event::{
Event,
TopicEncoder,
},
hash::{
CryptoHash,
HashOutput,
},
};
/// Environmental contract functionality that does not require `Environment`.
pub trait EnvBackend {
/// Writes the value to the contract storage under the given storage key.
///
/// Returns the size of the pre-existing value at the specified key if any.
fn set_contract_storage<K, V>(&mut self, key: &K, value: &V) -> Option<u32>
where
K: scale::Encode,
V: Storable;
/// Returns the value stored under the given storage key in the contract's storage if
/// any.
///
/// # Errors
///
/// - If the decoding of the typed value failed
fn get_contract_storage<K, R>(&mut self, key: &K) -> Result<Option<R>>
where
K: scale::Encode,
R: Storable;
/// Removes the `value` at `key`, returning the previous `value` at `key` from storage
/// if any.
///
/// # Errors
///
/// - If the decoding of the typed value failed
fn take_contract_storage<K, R>(&mut self, key: &K) -> Result<Option<R>>
where
K: scale::Encode,
R: Storable;
/// Returns the size of a value stored under the given storage key is returned if any.
fn contains_contract_storage<K>(&mut self, key: &K) -> Option<u32>
where
K: scale::Encode;
/// Clears the contract's storage key entry under the given storage key.
///
/// Returns the size of the previously stored value at the specified key if any.
fn clear_contract_storage<K>(&mut self, key: &K) -> Option<u32>
where
K: scale::Encode;
/// Returns the execution input to the executed contract and decodes it as `T`.
///
/// # Note
///
/// - The input is the 4-bytes selector followed by the arguments of the called
/// function in their SCALE encoded representation.
/// - No prior interaction with the environment must take place before calling this
/// procedure.
///
/// # Usage
///
/// Normally contracts define their own `enum` dispatch types respective
/// to their exported constructors and messages that implement `scale::Decode`
/// according to the constructors or messages selectors and their arguments.
/// These `enum` dispatch types are then given to this procedure as the `T`.
///
/// When using ink! users do not have to construct those enum dispatch types
/// themselves as they are normally generated by the ink! code generation
/// automatically.
///
/// # Errors
///
/// If the given `T` cannot be properly decoded from the expected input.
fn decode_input<T>(&mut self) -> core::result::Result<T, DispatchError>
where
T: DecodeDispatch;
/// Returns the value back to the caller of the executed contract.
///
/// # Note
///
/// Calling this method will end contract execution immediately.
/// It will return the given return value back to its caller.
///
/// The `flags` parameter can be used to revert the state changes of the
/// entire execution if necessary.
#[cfg(not(feature = "std"))]
fn return_value<R>(&mut self, flags: ReturnFlags, return_value: &R) -> !
where
R: scale::Encode;
/// Returns the value back to the caller of the executed contract.
///
/// # Note
///
/// When the `std` feature is used, the contract is allowed to
/// return normally. This feature should only be used for integration tests.
///
/// The `flags` parameter can be used to revert the state changes of the
/// entire execution if necessary.
#[cfg(feature = "std")]
fn return_value<R>(&mut self, flags: ReturnFlags, return_value: &R)
where
R: scale::Encode;
/// Returns the *Solidity ABI encoded* value back to the caller of the executed
/// contract.
///
/// # Note
///
/// This function stops the execution of the contract immediately.
fn return_value_solidity<R>(&mut self, flags: ReturnFlags, return_value: &R) -> !
where
R: for<'a> SolResultEncode<'a>;
/// Conducts the crypto hash of the given input and stores the result in `output`.
fn hash_bytes<H>(&mut self, input: &[u8], output: &mut <H as HashOutput>::Type)
where
H: CryptoHash;
/// Conducts the crypto hash of the given encoded input and stores the result in
/// `output`.
fn hash_encoded<H, T>(&mut self, input: &T, output: &mut <H as HashOutput>::Type)
where
H: CryptoHash,
T: scale::Encode;
/// Calls the `bn128_add` G1 addition precompile.
///
/// Inputs are affine G1 coordinates over Fq.
/// Returns the resulting affine point or (0, 0) if the result is ∞ / invalid.
///
/// # Note
///
/// The precompile address is `0x06`. You can find its implementation here:
/// <https://github.com/paritytech/polkadot-sdk/blob/master/substrate/frame/revive/src/precompiles/builtin/bn128.rs>
fn bn128_add(&mut self, x1: U256, y1: U256, x2: U256, y2: U256) -> (U256, U256);
/// Calls the `bn128_mul` G1 scalar-mul precompile.
///
/// Multiplies an affine G1 point (x1, y1) by a scalar ∈ Fr.
/// Returns the resulting affine point or (0, 0) if the result is ∞ / invalid.
///
/// # Note
///
/// The precompile address is `0x07`. You can find its implementation here:
/// <https://github.com/paritytech/polkadot-sdk/blob/master/substrate/frame/revive/src/precompiles/builtin/bn128.rs>
fn bn128_mul(&mut self, x1: U256, y1: U256, scalar: U256) -> (U256, U256);
/// Calls the `bn128_pairing` precompile.
///
/// Input is the Solidity-ABI-encoded sequence of (G1, G2) pairs.
/// Returns `true` iff the product of pairings evaluates to the identity.
///
/// # Note
///
/// The precompile address is `0x08`. You can find its implementation here:
/// <https://github.com/paritytech/polkadot-sdk/blob/master/substrate/frame/revive/src/precompiles/builtin/bn128.rs>
fn bn128_pairing(&mut self, input: &[u8]) -> bool;
/// Recovers the compressed ECDSA public key for given `signature` and `message_hash`,
/// and stores the result in `output`.
fn ecdsa_recover(
&mut self,
signature: &[u8; 65],
message_hash: &[u8; 32],
output: &mut [u8; 33],
) -> Result<()>;
/// Retrieves an Ethereum address from the ECDSA compressed `pubkey`
/// and stores the result in `output`.
#[cfg(feature = "unstable-hostfn")]
fn ecdsa_to_eth_address(
&mut self,
pubkey: &[u8; 33],
output: &mut [u8; 20],
) -> Result<()>;
/// Verifies a sr25519 signature.
///
/// # Errors
///
/// - If the signature verification failed.
///
/// **WARNING**: this function is from the [unstable interface](https://github.com/paritytech/polkadot-sdk/tree/master/substrate/frame/revive#unstable-interfaces)
/// which is unsafe and normally is not available on production chains.
#[cfg(feature = "unstable-hostfn")]
fn sr25519_verify(
&mut self,
signature: &[u8; 64],
message: &[u8],
pub_key: &[u8; 32],
) -> Result<()>;
/// Sets a new code hash for the current contract.
///
/// This effectively replaces the code which is executed for this contract address.
///
/// # Errors
///
/// - If the supplied `code_hash` cannot be found on-chain.
#[cfg(feature = "unstable-hostfn")]
fn set_code_hash(&mut self, code_hash: &H256) -> Result<()>;
/// Returns the size of the buffer that is remaining in the backend.
fn remaining_buffer(&mut self) -> usize;
}
/// Environmental contract functionality.
pub trait TypedEnvBackend: EnvBackend {
/// Returns the address of the caller of the executed contract.
///
/// # Note
///
/// For more details visit: [`caller`][`crate::caller`]
fn caller(&mut self) -> Address;
/// Returns the block's `ref_time` limit.
/// This is akin to the EVM [GASLIMIT](https://www.evm.codes/?fork=cancun#45) opcode.
///
/// # Note
///
/// For more details visit: [`gas_limit`][`crate::gas_limit`]
fn gas_limit(&mut self) -> u64;
/// Returns the price per `ref_time`, akin to the EVM
/// [GASPRICE](https://www.evm.codes/?fork=cancun#3a) opcode.
///
/// See <https://use.ink/docs/v6/basics/gas/#what-is-gas-in-ink> for more information.
///
/// # Note
///
/// For more details visit: [`gas_price`][`crate::gas_price`]
fn gas_price(&mut self) -> u64;
/// Returns the amount of gas left.
/// This is the `ref_time` left.
///
/// See <https://use.ink/docs/v6/basics/gas/#what-is-gas-in-ink> for more information.
///
/// # Note
///
/// For more details visit: [`gas_left`][`crate::gas_left`]
fn gas_left(&mut self) -> u64;
/// Returns the total size of the contract call input data.
/// This is akin to the EVM [CALLDATASIZE](https://www.evm.codes/?fork=cancun#36) opcode.
///
/// # Note
///
/// For more details visit: [`call_data_size`][`crate::call_data_size]
fn call_data_size(&mut self) -> u64;
/// Returns the size of the returned data of the last contract call or instantiation.
/// This is akin to the EVM [RETURNDATASIZE](https://www.evm.codes/?fork=cancun#3d) opcode.
///
/// # Note
///
/// For more details visit: [`return_data_size`][`crate::return_data_size`]
fn return_data_size(&mut self) -> u64;
/// Returns the [EIP-155](https://eips.ethereum.org/EIPS/eip-155) chain ID.
/// This is akin to the EVM [CHAINID](https://www.evm.codes/?fork=cancun#46) opcode.
///
/// # Note
///
/// For more details visit: [`chain_id`][`crate::chain_id`]
fn chain_id(&mut self) -> U256;
/// Returns the **reducible** native balance of the supplied address.
/// This is akin to the EVM [BALANCE](https://www.evm.codes/?fork=cancun#31) opcode.
///
/// # Note
///
/// For more details visit: [`balance_of`][`crate::balance_of`]
fn balance_of(&mut self, addr: Address) -> U256;
/// Returns the base fee.
/// This is akin to the EVM [BASEFEE](https://www.evm.codes/?fork=cancun#48) opcode.
///
/// # Note
///
/// For more details visit: [`base_fee`][`crate::base_fee`]
fn base_fee(&mut self) -> U256;
/// Returns the origin address (initator of the call stack).
/// This is akin to the EVM [ORIGIN](https://www.evm.codes/?fork=cancun#32) opcode.
///
/// # Errors
///
/// - If there is no address associated with the origin (e.g. because the origin is
/// root).
///
/// # Note
///
/// For more details visit: [`origin`][`crate::origin`]
fn origin(&mut self) -> Address;
/// Returns the code size for a specified contract address.
/// This is akin to the EVM [CODESIZE](https://www.evm.codes/?fork=cancun#38) opcode.
///
/// # Note
///
/// If `addr` is not a contract the `output` will be zero.
/// For more details visit: [`code_size`][`crate::code_size`]
fn code_size(&mut self, addr: Address) -> u64;
/// Returns the block hash of the given block number.
/// This is akin to the EVM [BLOCKHASH](https://www.evm.codes/?fork=cancun#40) opcode.
///
/// # Note
///
/// For more details visit: [`block_hash`][`crate::block_hash`]
fn block_hash<E: Environment>(&mut self, block_number: E::BlockNumber) -> H256;
/// Returns the current block author.
/// This is akin to the EVM [COINBASE](https://www.evm.codes/?fork=cancun#41) opcode.
///
/// # Note
///
/// For more details visit: [`block_author`][`crate::block_author`]
fn block_author(&mut self) -> Address;
/// Returns the U256 value at given `offset` from the input passed by the caller.
/// This is akin to the EVM [CALLDATALOAD](https://www.evm.codes/?fork=cancun#35) opcode.
///
/// # Note
///
/// - If `offset` is out of bounds, a value of zero will be returned.
/// - If `offset` is in bounds but there is not enough call data, the available data
/// is right-padded in order to fill a whole U256 value.
/// - The data returned is a little endian U256 integer value.
///
/// For more details visit: [`call_data_load`][`crate::call_data_load`]
fn call_data_load(&mut self, offset: u32) -> U256;
/// Sets the storage entry for a fixed 256‑bit key with a fixed 256‑bit value.
/// If the provided 32‑byte value is all zeros then the key is cleared (i.e. deleted).
/// Returns the size (in bytes) of the pre‑existing value at the specified key, if
/// any. This is akin to the EVM [SSTORE](https://www.evm.codes/?fork=cancun#55) opcode.
///
/// # Note
///
/// For more details visit: [`set_storage`][`crate::set_storage`]
fn set_storage(&mut self, key: U256, value: &[u8; 32]) -> Option<u32>;
/// Sets the transient storage entry for a fixed 256‑bit key with a fixed 256‑bit
/// value. If the provided 32‑byte value is all zeros then the key is cleared
/// (i.e. deleted). Returns the size (in bytes) of the pre‑existing value at the
/// specified key, if any. This is akin to the EVM [TSTORE](https://www.evm.codes/?fork=cancun#5D) opcode.
///
/// # Note
///
/// For more details visit: [`set_transient_storage`][`crate::set_transient_storage`]
fn set_transient_storage(&mut self, key: U256, value: &[u8; 32]) -> Option<u32>;
/// Retrieves the storage entry for a fixed 256‑bit key.
/// If the key does not exist, it returns 32 zero bytes.
/// This is akin to the EVM [SLOAD](https://www.evm.codes/?fork=cancun#54) opcode.
///
/// # Note
///
/// For more details visit: [`get_storage`][`crate::get_storage`]
fn get_storage(&mut self, key: U256) -> [u8; 32];
/// Retrieves the transient storage entry for a fixed 256‑bit key.
/// If the key does not exist, it returns 32 zero bytes.
/// This is akin to the EVM [TLOAD](https://www.evm.codes/?fork=cancun#5C) opcode.
///
/// # Note
///
/// For more details visit: [`get_transient_storage`][`crate::get_transient_storage`]
fn get_transient_storage(&mut self, key: U256) -> [u8; 32];
/// Returns the transferred value for the contract execution.
///
/// # Note
///
/// For more details visit: [`transferred_value`][`crate::transferred_value`]
fn transferred_value(&mut self) -> U256;
/// Returns the price for the specified amount of gas.
///
/// # Note
///
/// For more details visit: [`weight_to_fee`][`crate::weight_to_fee`]
fn weight_to_fee(&mut self, gas: u64) -> U256;
/// Returns the timestamp of the current block.
///
/// # Note
///
/// For more details visit: [`block_timestamp`][`crate::block_timestamp`]
fn block_timestamp<E: Environment>(&mut self) -> E::Timestamp;
/// Retrieves the account id for a specified address.
///
/// # Note
///
/// For more details visit: [`to_account_id`][`crate::to_account_id`]
fn to_account_id<E: Environment>(&mut self, addr: Address) -> E::AccountId;
/// Returns the address of the executed contract.
///
/// # Note
///
/// For more details visit: [`account_id`][`crate::account_id`]
fn account_id<E: Environment>(&mut self) -> E::AccountId;
/// Returns the address of the executed contract.
///
/// # Note
///
/// For more details visit: [`address`][`crate::address`]
fn address(&mut self) -> Address;
/// Returns the balance of the executed contract.
///
/// # Note
///
/// For more details visit: [`balance`][`crate::balance`]
fn balance(&mut self) -> U256;
/// Returns the current block number.
///
/// # Note
///
/// For more details visit: [`block_number`][`crate::block_number`]
fn block_number<E: Environment>(&mut self) -> E::BlockNumber;
/// Returns the minimum balance that is required for creating an account
/// (i.e. the chain's existential deposit).
///
/// # Note
///
/// For more details visit: [`minimum_balance`][`crate::minimum_balance`]
fn minimum_balance(&mut self) -> U256;
/// Emits an event with the given event data.
///
/// # Note
///
/// For more details visit: [`emit_event`][`crate::emit_event`]
fn emit_event<Evt, Abi>(&mut self, event: &Evt)
where
Evt: Event<Abi>,
Abi: TopicEncoder;
/// Invokes a contract message and returns its result.
///
/// # Note
///
/// **This will call into the latest `call_v2` host function.**
///
/// For more details visit: [`invoke_contract`][`crate::invoke_contract`]
fn invoke_contract<E, Args, R, Abi>(
&mut self,
call_data: &CallParams<E, Call, Args, R, Abi>,
) -> Result<ink_primitives::MessageResult<R>>
where
E: Environment,
Args: EncodeArgsWith<Abi>,
R: DecodeMessageResult<Abi>;
/// Invokes a contract message via delegate call and returns its result.
///
/// # Note
///
/// For more details visit:
/// [`invoke_contract_delegate`][`crate::invoke_contract_delegate`]
fn invoke_contract_delegate<E, Args, R, Abi>(
&mut self,
call_data: &CallParams<E, DelegateCall, Args, R, Abi>,
) -> Result<ink_primitives::MessageResult<R>>
where
E: Environment,
Args: EncodeArgsWith<Abi>,
R: DecodeMessageResult<Abi>;
/// Instantiates another contract.
///
/// # Note
///
/// For more details visit: [`instantiate_contract`][`crate::instantiate_contract`]
fn instantiate_contract<E, ContractRef, Args, R, Abi>(
&mut self,
params: &CreateParams<E, ContractRef, LimitParamsV2, Args, R, Abi>,
) -> Result<
ink_primitives::ConstructorResult<
<R as ConstructorReturnType<ContractRef, Abi>>::Output,
>,
>
where
E: Environment,
ContractRef: FromAddr + crate::ContractReverseReference,
<ContractRef as crate::ContractReverseReference>::Type:
crate::reflect::ContractConstructorDecoder,
Args: EncodeArgsWith<Abi>,
R: ConstructorReturnType<ContractRef, Abi>;
/// Terminates a smart contract.
///
/// # Note
///
/// For more details visit: [`terminate_contract`][`crate::terminate_contract`]
#[cfg(feature = "unstable-hostfn")]
fn terminate_contract(&mut self, beneficiary: Address) -> !;
/// Transfers value from the contract to the destination account ID.
///
/// # Note
///
/// For more details visit: [`transfer`][`crate::transfer`]
fn transfer<E>(&mut self, destination: Address, value: U256) -> Result<()>
where
E: Environment;
/// Checks whether a specified contract lives at `addr`.
///
/// # Note
///
/// For more details visit: [`is_contract`][`crate::is_contract`]
fn is_contract(&mut self, account: &Address) -> bool;
/// Checks whether the caller of the current contract is the origin of the whole call
/// stack.
///
/// # Note
///
/// For more details visit: [`caller_is_origin`][`crate::caller_is_origin`]
fn caller_is_origin(&mut self) -> bool;
/// Checks whether the caller of the current contract is root.
///
/// # Note
///
/// For more details visit: [`caller_is_root`][`crate::caller_is_root`]
fn caller_is_root(&mut self) -> bool;
/// Retrieves the code hash of the contract at the given `account` id.
///
/// # Note
///
/// For more details visit: [`code_hash`][`crate::code_hash`]
fn code_hash(&mut self, account: &Address)
-> core::result::Result<H256, CodeHashErr>;
/// Retrieves the code hash of the currently executing contract.
///
/// # Note
///
/// For more details visit: [`own_code_hash`][`crate::own_code_hash`]
fn own_code_hash(&mut self) -> H256;
/// Estimates the [`Weight`] required to execute a given XCM message.
///
/// # Note
///
/// For more details visit: [`xcm`][`crate::xcm_weigh`].
#[cfg(feature = "xcm")]
fn xcm_weigh<Call>(&mut self, msg: &xcm::VersionedXcm<Call>) -> Result<Weight>
where
Call: scale::Encode;
/// Execute an XCM message locally, using the contract's address as the origin.
///
/// # Note
///
/// For more details visit: [`xcm`][`crate::xcm_execute`].
#[cfg(feature = "xcm")]
fn xcm_execute<Call>(
&mut self,
msg: &xcm::VersionedXcm<Call>,
weight: Weight,
) -> Result<()>
where
Call: scale::Encode;
/// Send an XCM message, using the contract's address as the origin.
///
/// # Note
///
/// For more details visit: [`xcm`][`crate::xcm_send`].
#[cfg(feature = "xcm")]
fn xcm_send<Call>(
&mut self,
dest: &xcm::VersionedLocation,
msg: &xcm::VersionedXcm<Call>,
) -> Result<()>
where
Call: scale::Encode;
}