mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-07-20 22:05:42 +00:00
Rename Palette to FRAME (#4182)
* palette -> frame * PALETTE, Palette -> FRAME * Move folder pallete -> frame * Update docs/Structure.adoc Co-Authored-By: Benjamin Kampmann <ben.kampmann@googlemail.com> * Update docs/README.adoc Co-Authored-By: Benjamin Kampmann <ben.kampmann@googlemail.com> * Update README.adoc
This commit is contained in:
@@ -0,0 +1,417 @@
|
||||
# Complexity
|
||||
|
||||
This analysis is on the computing and memory complexity of specific procedures. It provides a rough estimate of operations performed in general and especially focusing on DB reads and writes. It is also an attempt to estimate the memory consumption at its peak.
|
||||
|
||||
The primary goal is to come up with decent pricing for functions that can be invoked by a user (via extrinsics) or by untrusted code that prevents DoS attacks.
|
||||
|
||||
# Sandboxing
|
||||
|
||||
It makes sense to describe the sandboxing module first because the smart-contract module is built upon it.
|
||||
|
||||
## Memory
|
||||
|
||||
### set
|
||||
|
||||
Copies data from the supervisor's memory to the guest's memory.
|
||||
|
||||
**complexity**: It doesn't allocate, and the computational complexity is proportional to the number of bytes to copy.
|
||||
|
||||
### get
|
||||
|
||||
Copies data from the guest's memory to the supervisor's memory.
|
||||
|
||||
**complexity**: It doesn't allocate, and the computational complexity is proportional to the number of bytes to copy.
|
||||
|
||||
## Instance
|
||||
|
||||
### Instantiation
|
||||
|
||||
Instantiation of a sandbox module consists of the following steps:
|
||||
|
||||
1. Loading the wasm module in the in-memory representation,
|
||||
2. Performing validation of the wasm code,
|
||||
3. Setting up the environment which will be used to instantiate the module,
|
||||
4. Performing the standard wasm instantiation process, which includes (but is not limited to):
|
||||
1. Allocating of memory requested by the instance,
|
||||
2. Copying static data from the module to newly allocated memory,
|
||||
3. Executing the `start` function.
|
||||
|
||||
**Note** that the `start` function can be viewed as a normal function and can do anything that a normal function can do, including allocation of more memory or calling the host environment. The complexity of running the `start` function should be considered separately.
|
||||
|
||||
In order to start the process of instantiation, the supervisor should provide the wasm module code being instantiated and the environment definition (a set of functions, memories (and maybe globals and tables in the future) available for import by the guest module) for that module. While the environment definition typically is of the constant size (unless mechanisms like dynamic linking are used), the size of wasm is not.
|
||||
|
||||
Validation and instantiation in WebAssembly are designed to be able to be performed in linear time. The allocation and computational complexity of loading a wasm module depend on the underlying wasm VM being used. For example, for JIT compilers it can and probably will be non-linear because of compilation. However, for wasmi, it should be linear. We can try to use other VMs that are able to compile code with memory and time consumption proportional to the size of the code.
|
||||
|
||||
Since the module itself requests memory, the amount of allocation depends on the module code itself. If untrusted code is being instantiated, it's up to the supervisor to limit the amount of memory available to allocate.
|
||||
|
||||
**complexity**: The computational complexity is proportional to the size of wasm code. Memory complexity is proportional to the size of wasm code and the amount of memory requested by the module.
|
||||
|
||||
### Preparation to invoke
|
||||
|
||||
Invocation of an exported function in the sandboxed module consists of the following steps:
|
||||
|
||||
1. Marshalling, copying and unmarshalling the arguments when passing them between the supervisor and executor,
|
||||
2. Calling into the underlying VM,
|
||||
3. Marshalling, copying and unmarshalling the result when passing it between the executor and supervisor,
|
||||
|
||||
**Note** that the complexity of running the function code itself should be considered separately.
|
||||
|
||||
The actual complexity of invocation depends on the underlying VM. Wasmi will reserve a relatively large chunk of memory for the stack before execution of the code, although it's of constant size.
|
||||
|
||||
The size of the arguments and the return value depends on the exact function in question, but can be considered as constant.
|
||||
|
||||
**complexity**: Memory and computational complexity can be considered as a constant.
|
||||
|
||||
### Call from the guest to the supervisor
|
||||
|
||||
The executor handles each call from the guest. The execution of it consists of the following steps:
|
||||
|
||||
1. Marshalling, copying and unmarshalling the arguments when passing them between the guest and executor,
|
||||
2. Calling into the supervisor,
|
||||
3. Marshaling, copying and unmarshalling the result when passing it between the executor and guest.
|
||||
|
||||
**Note** that the complexity of running the supervisor handler should be considered separately.
|
||||
|
||||
Because calling into the supervisor requires invoking a wasm VM, the actual complexity of invocation depends on the actual VM used for the runtime/supervisor. Wasmi will reserve a relatively large chunk of memory for the stack before execution of the code, although it's of constant size.
|
||||
|
||||
The size of the arguments and the return value depends on the exact function in question, but can be considered as a constant.
|
||||
|
||||
**complexity**: Memory and computational complexity can be considered as a constant.
|
||||
|
||||
# `AccountDb`
|
||||
|
||||
`AccountDb` is an abstraction that supports collecting changes to accounts with the ability to efficiently reverting them. Contract
|
||||
execution contexts operate on the AccountDb. All changes are flushed into underlying storage only after origin transaction succeeds.
|
||||
|
||||
## Relation to the underlying storage
|
||||
|
||||
At present, `AccountDb` is implemented as a cascade of overlays with the direct storage at the bottom. The direct
|
||||
storage `AccountDb` leverages child tries. Each overlay is represented by a `Map`. On a commit from an overlay to an
|
||||
overlay, maps are merged. On commit from an overlay to the bottommost `AccountDb` all changes are flushed to the storage
|
||||
and on revert, the overlay is just discarded.
|
||||
|
||||
> ℹ️ The underlying storage has a overlay layer implemented as a `Map`. If the runtime reads a storage location and the
|
||||
> respective key doesn't exist in the overlay, then the underlying storage performs a DB access, but the value won't be
|
||||
> placed into the overlay. The overlay is only filled with writes.
|
||||
>
|
||||
> This means that the overlay can be abused in the following ways:
|
||||
>
|
||||
> - The overlay can be inflated by issuing a lot of writes to unique locations,
|
||||
> - Deliberate cache misses can be induced by reading non-modified storage locations,
|
||||
|
||||
It also worth noting that the performance degrades with more state stored in the trie. Due to this
|
||||
there is not negligible chance that gas schedule will be updated for all operations that involve
|
||||
storage access.
|
||||
|
||||
## get_storage, get_code_hash, get_rent_allowance, get_balance, contract_exists
|
||||
|
||||
These functions check the local cache for a requested value and, if it is there, the value is returned. Otherwise, these functions will ask an underlying `AccountDb` for the value. This means that the number of lookups is proportional to the depth of the overlay cascade. If the value can't be found before reaching the bottommost `AccountDb`, then a DB read will be performed (in case `get_balance` the function `free_balance` will be invoked).
|
||||
|
||||
A lookup in the local cache consists of at least one `Map` lookup, for locating the specific account. For `get_storage` there is a second lookup: because account's storage is implemented as a nested map, another lookup is required for fetching a storage value by a key.
|
||||
|
||||
These functions return an owned value as its result, so memory usage depends on the value being returned.
|
||||
|
||||
**complexity**: The memory complexity is proportional to the size of the value. The computational complexity is proportional to the depth of the overlay cascade and the size of the value; the cost is dominated by the DB read though.
|
||||
|
||||
## set_storage, set_balance, set_rent_allowance
|
||||
|
||||
These functions only modify the local `Map`.
|
||||
|
||||
A lookup in the local cache consists of at least one `Map` lookup, for locating the specific account. For `get_storage` there is a second lookup: because account's storage is implemented as a nested map, another lookup is required for fetching a storage value by a key.
|
||||
|
||||
While these functions only modify the local `Map`, if changes made by them are committed to the bottommost `AccountDb`, each changed entry in the `Map` will require a DB write. Moreover, if the balance of the account is changed to be below `existential_deposit` then that account along with all its storage will be removed, which requires time proportional to the number of storage entries that account has. It should be ensured that pricing accounts for these facts.
|
||||
|
||||
**complexity**: Each lookup has a logarithmical computing time to the number of already inserted entries. No additional memory is required.
|
||||
|
||||
## instantiate_contract
|
||||
|
||||
Calls `contract_exists` and if it doesn't exist, do not modify the local `Map` similarly to `set_rent_allowance`.
|
||||
|
||||
**complexity**: The computational complexity is proportional to the depth of the overlay cascade and the size of the value; the cost is dominated by the DB read though. No additional memory is required.
|
||||
|
||||
## commit
|
||||
|
||||
In this function, all cached values will be inserted into the underlying `AccountDb` or into the storage.
|
||||
|
||||
We are doing `N` inserts into `Map` (`O(log M)` complexity) or into the storage, where `N` is the size of the committed `Map` and `M` is the size of the map of the underlying overlay. Consider adjusting the price of modifying the `AccountDb` to account for this (since pricing for the count of entries in `commit` will make the price of commit way less predictable). No additional memory is required.
|
||||
|
||||
Note that in case of storage modification we need to construct a key in the underlying storage. In order to do that we need:
|
||||
|
||||
- perform `twox_128` hashing over a concatenation of some prefix literal and the `AccountId` of the storage owner.
|
||||
- then perform `blake2_256` hashing of the storage key.
|
||||
- concatenation of these hashes will constitute the key in the underlying storage.
|
||||
|
||||
There is also a special case to think of: if the balance of some account goes below `existential_deposit`, then all storage entries of that account will be erased, which requires time proprotional to the number of storage entries that account has.
|
||||
|
||||
**complexity**: `N` inserts into a `Map` or eventually into the storage (if committed). Every deleted account will induce removal of all its storage which is proportional to the number of storage entries that account has.
|
||||
|
||||
## revert
|
||||
|
||||
Consists of dropping (in the Rust sense) of the `AccountDb`.
|
||||
|
||||
**complexity**: Computing complexity is proportional to a number of changed entries in a overlay. No additional memory is required.
|
||||
|
||||
# Executive
|
||||
|
||||
## Transfer
|
||||
|
||||
This function performs the following steps:
|
||||
|
||||
1. Querying source and destination balances from an overlay (see `get_balance`),
|
||||
2. Querying `existential_deposit`.
|
||||
3. Executing `ensure_account_liquid` hook.
|
||||
4. Updating source and destination balance in the overlay (see `set_balance`).
|
||||
|
||||
**Note** that the complexity of executing `ensure_account_liquid` hook should be considered separately.
|
||||
|
||||
In the course of the execution this function can perform up to 2 DB reads to `get_balance` of source and destination accounts. It can also induce up to 2 DB writes via `set_balance` if flushed to the storage.
|
||||
|
||||
Moreover, if the source balance goes below `existential_deposit` then the account will be deleted along with all its storage which requires time proportional to the number of storage entries of that account.
|
||||
|
||||
Assuming marshaled size of a balance value is of the constant size we can neglect its effect on the performance.
|
||||
|
||||
**complexity**: up to 2 DB reads and up to 2 DB writes (if flushed to the storage) in the standard case. If removal of the source account takes place then it will additionally perform a DB write per one storage entry that the account has. For the current `AccountDb` implementation computing complexity also depends on the depth of the `AccountDb` cascade. Memorywise it can be assumed to be constant.
|
||||
|
||||
## Initialization
|
||||
|
||||
Before a call or instantiate can be performed the execution context must be initialized.
|
||||
|
||||
For the first call or instantiation in the handling of an extrinsic, this involves two calls:
|
||||
|
||||
1. `<timestamp::Module<T>>::now()`
|
||||
2. `<system::Module<T>>::block_number()`
|
||||
|
||||
The complexity of initialization depends on the complexity of these functions. In the current
|
||||
implementation they just involve a DB read.
|
||||
|
||||
For subsequent calls and instantiations during contract execution, the initialization requires no
|
||||
expensive operations.
|
||||
|
||||
## Call
|
||||
|
||||
This function receives input data for the contract execution. The execution consists of the following steps:
|
||||
|
||||
1. Initialization of the execution context.
|
||||
2. Checking rent payment.
|
||||
3. Loading code from the DB.
|
||||
4. `transfer`-ing funds between the caller and the destination account.
|
||||
5. Executing the code of the destination account.
|
||||
6. Committing overlayed changed to the underlying `AccountDb`.
|
||||
|
||||
**Note** that the complexity of executing the contract code should be considered separately.
|
||||
|
||||
Checking for rent involves 2 unconditional DB reads: `ContractInfoOf` and `block_number`
|
||||
and on top of that at most once per block:
|
||||
|
||||
- DB read to `free_balance` and
|
||||
- `rent_deposit_offset` and
|
||||
- `rent_byte_price` and
|
||||
- `Currency::minimum_balance` and
|
||||
- `tombstone_deposit`.
|
||||
- Calls to `ensure_can_withdraw`, `withdraw`, `make_free_balance_be` can perform arbitrary logic and should be considered separately,
|
||||
- `child_storage_root`
|
||||
- `kill_child_storage`
|
||||
- mutation of `ContractInfoOf`
|
||||
|
||||
Loading code most likely will trigger a DB read, since the code is immutable and therefore will not get into the cache (unless a suicide removes it, or it has been instantiated in the same call chain).
|
||||
|
||||
Also, `transfer` can make up to 2 DB reads and up to 2 DB writes (if flushed to the storage) in the standard case. If removal of the source account takes place then it will additionally perform a DB write per one storage entry that the account has.
|
||||
|
||||
Finally, all changes are `commit`-ted into the underlying overlay. The complexity of this depends on the number of changes performed by the code. Thus, the pricing of storage modification should account for that.
|
||||
|
||||
**complexity**:
|
||||
- Only for the first invocation of the contract: up to 5 DB reads and one DB write as well as logic executed by `ensure_can_withdraw`, `withdraw`, `make_free_balance_be`.
|
||||
- On top of that for every invocation: Up to 5 DB reads. DB read of the code is of dynamic size. There can also be up to 2 DB writes (if flushed to the storage). Additionally, if the source account removal takes place a DB write will be performed per one storage entry that the account has.
|
||||
|
||||
## Instantiate
|
||||
|
||||
This function takes the code of the constructor and input data. Instantiation of a contract consists of the following steps:
|
||||
|
||||
1. Initialization of the execution context.
|
||||
2. Calling `DetermineContractAddress` hook to determine an address for the contract,
|
||||
3. `transfer`-ing funds between self and the newly instantiated contract.
|
||||
4. Executing the constructor code. This will yield the final code of the code.
|
||||
5. Storing the code for the newly instantiated contract in the overlay.
|
||||
6. Committing overlayed changed to the underlying `AccountDb`.
|
||||
|
||||
**Note** that the complexity of executing the constructor code should be considered separately.
|
||||
|
||||
**Note** that the complexity of `DetermineContractAddress` hook should be considered separately as well. Most likely it will use some kind of hashing over the code of the constructor and input data. The default `SimpleAddressDeterminator` does precisely that.
|
||||
|
||||
**Note** that the constructor returns code in the owned form and it's obtained via return facilities, which should have take fee for the return value.
|
||||
|
||||
Also, `transfer` can make up to 2 DB reads and up to 2 DB writes (if flushed to the storage) in the standard case. If removal of the source account takes place then it will additionally perform a DB write per one storage entry that the account has.
|
||||
|
||||
Storing the code in the overlay may induce another DB write (if flushed to the storage) with the size proportional to the size of the constructor code.
|
||||
|
||||
Finally, all changes are `commit`-ted into the underlying overlay. The complexity of this depends on the number of changes performed by the constructor code. Thus, the pricing of storage modification should account for that.
|
||||
|
||||
**complexity**: Up to 2 DB reads and induces up to 3 DB writes (if flushed to the storage), one of which is dependent on the size of the code. Additionally, if the source account removal takes place a DB write will be performed per one storage entry that the account has.
|
||||
|
||||
# Externalities
|
||||
|
||||
Each external function invoked from a contract can involve some overhead.
|
||||
|
||||
## ext_gas
|
||||
|
||||
**complexity**: This is of constant complexity.
|
||||
|
||||
## ext_set_storage
|
||||
|
||||
This function receives a `key` and `value` as arguments. It consists of the following steps:
|
||||
|
||||
1. Reading the sandbox memory for `key` and `value` (see sandboxing memory get).
|
||||
2. Setting the storage by the given `key` with the given `value` (see `set_storage`).
|
||||
|
||||
**complexity**: Complexity is proportional to the size of the `value`. This function induces a DB write of size proportional to the `value` size (if flushed to the storage), so should be priced accordingly.
|
||||
|
||||
## ext_get_storage
|
||||
|
||||
This function receives a `key` as an argument. It consists of the following steps:
|
||||
|
||||
1. Reading the sandbox memory for `key` (see sandboxing memory get).
|
||||
2. Reading the storage with the given key (see `get_storage`). It receives back the owned result buffer.
|
||||
3. Replacing the scratch buffer.
|
||||
|
||||
Key is of a constant size. Therefore, the sandbox memory load can be considered to be of constant complexity.
|
||||
|
||||
Unless the value is cached, a DB read will be performed. The size of the value is not known until the read is
|
||||
performed. Moreover, the DB read has to be synchronous and no progress can be made until the value is fetched.
|
||||
|
||||
**complexity**: The memory and computing complexity is proportional to the size of the fetched value. This function performs a
|
||||
DB read.
|
||||
|
||||
## ext_call
|
||||
|
||||
This function receives the following arguments:
|
||||
|
||||
- `callee` buffer of a marshaled `AccountId`,
|
||||
- `gas` limit which is plain u64,
|
||||
- `value` buffer of a marshaled `Balance`,
|
||||
- `input_data`. An arbitrarily sized byte vector.
|
||||
|
||||
It consists of the following steps:
|
||||
|
||||
1. Loading `callee` buffer from the sandbox memory (see sandboxing memory get) and then decoding it.
|
||||
2. Loading `value` buffer from the sandbox memory and then decoding it.
|
||||
3. Loading `input_data` buffer from the sandbox memory.
|
||||
4. Invoking the executive function `call`.
|
||||
|
||||
Loading of `callee` and `value` buffers should be charged. This is because the sizes of buffers are specified by the calling code, even though marshaled representations are, essentially, of constant size. This can be fixed by assigning an upper bound for sizes of `AccountId` and `Balance`.
|
||||
|
||||
Loading `input_data` should be charged in any case.
|
||||
|
||||
**complexity**: All complexity comes from loading buffers and executing `call` executive function. The former component is proportional to the sizes of `callee`, `value` and `input_data` buffers. The latter component completely depends on the complexity of `call` executive function, and also dominated by it.
|
||||
|
||||
## ext_instantiate
|
||||
|
||||
This function receives the following arguments:
|
||||
|
||||
- `init_code`, a buffer which contains the code of the constructor.
|
||||
- `gas` limit which is plain u64
|
||||
- `value` buffer of a marshaled `Balance`
|
||||
- `input_data`. an arbitrarily sized byte vector.
|
||||
|
||||
It consists of the following steps:
|
||||
|
||||
1. Loading `init_code` buffer from the sandbox memory (see sandboxing memory get) and then decoding it.
|
||||
2. Loading `value` buffer from the sandbox memory and then decoding it.
|
||||
3. Loading `input_data` buffer from the sandbox memory.
|
||||
4. Invoking `instantiate` executive function.
|
||||
|
||||
Loading of `value` buffer should be charged. This is because the size of the buffer is specified by the calling code, even though marshaled representation is, essentially, of constant size. This can be fixed by assigning an upper bound for size for `Balance`.
|
||||
|
||||
Loading `init_code` and `input_data` should be charged in any case.
|
||||
|
||||
**complexity**: All complexity comes from loading buffers and executing `instantiate` executive function. The former component is proportional to the sizes of `init_code`, `value` and `input_data` buffers. The latter component completely depends on the complexity of `instantiate` executive function and also dominated by it.
|
||||
|
||||
## ext_return
|
||||
|
||||
This function receives a `data` buffer as an argument. Execution of the function consists of the following steps:
|
||||
|
||||
1. Loading `data` buffer from the sandbox memory (see sandboxing memory get),
|
||||
2. Trapping
|
||||
|
||||
**complexity**: The complexity of this function is proportional to the size of the `data` buffer.
|
||||
|
||||
## ext_deposit_event
|
||||
|
||||
This function receives a `data` buffer as an argument. Execution of the function consists of the following steps:
|
||||
|
||||
1. Loading `data` buffer from the sandbox memory (see sandboxing memory get),
|
||||
2. Insert to nested context execution
|
||||
3. Copies from nested to underlying contexts
|
||||
4. Call system deposit event
|
||||
|
||||
**complexity**: The complexity of this function is proportional to the size of the `data` buffer.
|
||||
|
||||
## ext_caller
|
||||
|
||||
This function serializes the address of the caller into the scratch buffer.
|
||||
|
||||
**complexity**: Assuming that the address is of constant size, this function has constant complexity.
|
||||
|
||||
## ext_random
|
||||
|
||||
This function serializes a random number generated by the given subject into the scratch buffer.
|
||||
The complexity of this function highly depends on the complexity of `System::random`. `max_subject_len`
|
||||
limits the size of the subject buffer.
|
||||
|
||||
**complexity**: The complexity of this function depends on the implementation of `System::random`.
|
||||
|
||||
## ext_now
|
||||
|
||||
This function serializes the current block's timestamp into the scratch buffer.
|
||||
|
||||
**complexity**: Assuming that the timestamp is of constant size, this function has constant complexity.
|
||||
|
||||
## ext_scratch_size
|
||||
|
||||
This function returns the size of the scratch buffer.
|
||||
|
||||
**complexity**: This function is of constant complexity.
|
||||
|
||||
## ext_scratch_read
|
||||
|
||||
This function copies slice of data from the scratch buffer to the sandbox memory. The calling code specifies the slice length. Execution of the function consists of the following steps:
|
||||
|
||||
1. Storing a specified slice of the scratch buffer into the sandbox memory (see sandboxing memory set)
|
||||
|
||||
**complexity**: The computing complexity of this function is proportional to the length of the slice. No additional memory is required.
|
||||
|
||||
## ext_scratch_write
|
||||
|
||||
This function copies slice of data from the sandbox memory to the scratch buffer. The calling code specifies the slice length. Execution of the function consists of the following steps:
|
||||
|
||||
1. Loading a slice from the sandbox memory into the (see sandboxing memory get)
|
||||
|
||||
**complexity**: Complexity is proportional to the length of the slice.
|
||||
|
||||
## ext_set_rent_allowance
|
||||
|
||||
This function receives the following argument:
|
||||
|
||||
- `value` buffer of a marshaled `Balance`,
|
||||
|
||||
It consists of the following steps:
|
||||
|
||||
1. Loading `value` buffer from the sandbox memory and then decoding it.
|
||||
2. Invoking `set_rent_allowance` AccountDB function.
|
||||
|
||||
**complexity**: Complexity is proportional to the size of the `value`. This function induces a DB write of size proportional to the `value` size (if flushed to the storage), so should be priced accordingly.
|
||||
|
||||
## ext_rent_allowance
|
||||
|
||||
It consists of the following steps:
|
||||
|
||||
1. Invoking `get_rent_allowance` AccountDB function.
|
||||
2. Serializing the rent allowance of the current contract into the scratch buffer.
|
||||
|
||||
**complexity**: Assuming that the rent allowance is of constant size, this function has constant complexity. This
|
||||
function performs a DB read.
|
||||
|
||||
## ext_block_number
|
||||
|
||||
This function serializes the current block's number into the scratch buffer.
|
||||
|
||||
**complexity**: Assuming that the block number is of constant size, this function has constant complexity.
|
||||
@@ -0,0 +1,45 @@
|
||||
[package]
|
||||
name = "pallet-contracts"
|
||||
version = "2.0.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0.101", optional = true, features = ["derive"] }
|
||||
pwasm-utils = { version = "0.11.0", default-features = false }
|
||||
codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] }
|
||||
parity-wasm = { version = "0.40.3", default-features = false }
|
||||
wasmi-validation = { version = "0.2.0", default-features = false }
|
||||
primitives = { package = "substrate-primitives", path = "../../primitives/core", default-features = false }
|
||||
sr-primitives = { path = "../../primitives/sr-primitives", default-features = false }
|
||||
runtime-io = { package = "sr-io", path = "../../primitives/sr-io", default-features = false }
|
||||
rstd = { package = "sr-std", path = "../../primitives/sr-std", default-features = false }
|
||||
sandbox = { package = "sr-sandbox", path = "../../primitives/sr-sandbox", default-features = false }
|
||||
support = { package = "frame-support", path = "../support", default-features = false }
|
||||
system = { package = "frame-system", path = "../system", default-features = false }
|
||||
|
||||
[dev-dependencies]
|
||||
wabt = "0.9.2"
|
||||
assert_matches = "1.3.0"
|
||||
hex-literal = "0.2.1"
|
||||
balances = { package = "pallet-balances", path = "../balances" }
|
||||
hex = "0.3.2"
|
||||
timestamp = { package = "pallet-timestamp", path = "../timestamp" }
|
||||
randomness-collective-flip = { package = "pallet-randomness-collective-flip", path = "../randomness-collective-flip" }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"serde",
|
||||
"codec/std",
|
||||
"primitives/std",
|
||||
"sr-primitives/std",
|
||||
"runtime-io/std",
|
||||
"rstd/std",
|
||||
"sandbox/std",
|
||||
"support/std",
|
||||
"system/std",
|
||||
"parity-wasm/std",
|
||||
"pwasm-utils/std",
|
||||
"wasmi-validation/std",
|
||||
]
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "pallet-contracts-rpc"
|
||||
version = "2.0.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
client = { package = "substrate-client", path = "../../../client/" }
|
||||
codec = { package = "parity-scale-codec", version = "1.0.0" }
|
||||
jsonrpc-core = "14.0.3"
|
||||
jsonrpc-core-client = "14.0.3"
|
||||
jsonrpc-derive = "14.0.3"
|
||||
primitives = { package = "substrate-primitives", path = "../../../primitives/core" }
|
||||
rpc-primitives = { package = "substrate-rpc-primitives", path = "../../../primitives/rpc" }
|
||||
serde = { version = "1.0.101", features = ["derive"] }
|
||||
sr-primitives = { path = "../../../primitives/sr-primitives" }
|
||||
pallet-contracts-rpc-runtime-api = { path = "./runtime-api" }
|
||||
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "pallet-contracts-rpc-runtime-api"
|
||||
version = "2.0.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
sr-api = { path = "../../../../primitives/sr-api", default-features = false }
|
||||
codec = { package = "parity-scale-codec", version = "1.0.0", default-features = false, features = ["derive"] }
|
||||
rstd = { package = "sr-std", path = "../../../../primitives/sr-std", default-features = false }
|
||||
serde = { version = "1.0.101", optional = true, features = ["derive"] }
|
||||
sr-primitives = { path = "../../../../primitives/sr-primitives", default-features = false }
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"sr-api/std",
|
||||
"codec/std",
|
||||
"rstd/std",
|
||||
"serde",
|
||||
"sr-primitives/std",
|
||||
]
|
||||
@@ -0,0 +1,90 @@
|
||||
// Copyright 2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Runtime API definition required by Contracts RPC extensions.
|
||||
//!
|
||||
//! This API should be imported and implemented by the runtime,
|
||||
//! of a node that wants to use the custom RPC extension
|
||||
//! adding Contracts access methods.
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
use rstd::vec::Vec;
|
||||
use codec::{Encode, Decode, Codec};
|
||||
use sr_primitives::RuntimeDebug;
|
||||
|
||||
/// A result of execution of a contract.
|
||||
#[derive(Eq, PartialEq, Encode, Decode, RuntimeDebug)]
|
||||
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum ContractExecResult {
|
||||
/// The contract returned successfully.
|
||||
///
|
||||
/// There is a status code and, optionally, some data returned by the contract.
|
||||
Success {
|
||||
/// Status code returned by the contract.
|
||||
status: u8,
|
||||
/// Output data returned by the contract.
|
||||
///
|
||||
/// Can be empty.
|
||||
data: Vec<u8>,
|
||||
},
|
||||
/// The contract execution either trapped or returned an error.
|
||||
Error,
|
||||
}
|
||||
|
||||
/// A result type of the get storage call.
|
||||
///
|
||||
/// See [`ContractsApi::get_storage`] for more info.
|
||||
pub type GetStorageResult = Result<Option<Vec<u8>>, GetStorageError>;
|
||||
|
||||
/// The possible errors that can happen querying the storage of a contract.
|
||||
#[derive(Eq, PartialEq, Encode, Decode, RuntimeDebug)]
|
||||
pub enum GetStorageError {
|
||||
/// The given address doesn't point on a contract.
|
||||
ContractDoesntExist,
|
||||
/// The specified contract is a tombstone and thus cannot have any storage.
|
||||
IsTombstone,
|
||||
}
|
||||
|
||||
sr_api::decl_runtime_apis! {
|
||||
/// The API to interact with contracts without using executive.
|
||||
pub trait ContractsApi<AccountId, Balance> where
|
||||
AccountId: Codec,
|
||||
Balance: Codec,
|
||||
{
|
||||
/// Perform a call from a specified account to a given contract.
|
||||
///
|
||||
/// See the contracts' `call` dispatchable function for more details.
|
||||
fn call(
|
||||
origin: AccountId,
|
||||
dest: AccountId,
|
||||
value: Balance,
|
||||
gas_limit: u64,
|
||||
input_data: Vec<u8>,
|
||||
) -> ContractExecResult;
|
||||
|
||||
/// Query a given storage key in a given contract.
|
||||
///
|
||||
/// Returns `Ok(Some(Vec<u8>))` if the storage value exists under the given key in the
|
||||
/// specified account and `Ok(None)` if it doesn't. If the account specified by the address
|
||||
/// doesn't exist, or doesn't have a contract or if the contract is a tombstone, then `Err`
|
||||
/// is returned.
|
||||
fn get_storage(
|
||||
address: AccountId,
|
||||
key: [u8; 32],
|
||||
) -> GetStorageResult;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
// Copyright 2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Node-specific RPC methods for interaction with contracts.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use client::blockchain::HeaderBackend;
|
||||
use codec::Codec;
|
||||
use jsonrpc_core::{Error, ErrorCode, Result};
|
||||
use jsonrpc_derive::rpc;
|
||||
use primitives::{H256, Bytes};
|
||||
use rpc_primitives::number;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sr_primitives::{
|
||||
generic::BlockId,
|
||||
traits::{Block as BlockT, ProvideRuntimeApi},
|
||||
};
|
||||
|
||||
pub use self::gen_client::Client as ContractsClient;
|
||||
pub use pallet_contracts_rpc_runtime_api::{
|
||||
self as runtime_api, ContractExecResult, ContractsApi as ContractsRuntimeApi, GetStorageResult,
|
||||
};
|
||||
|
||||
const RUNTIME_ERROR: i64 = 1;
|
||||
const CONTRACT_DOESNT_EXIST: i64 = 2;
|
||||
const CONTRACT_IS_A_TOMBSTONE: i64 = 3;
|
||||
|
||||
// A private newtype for converting `GetStorageError` into an RPC error.
|
||||
struct GetStorageError(runtime_api::GetStorageError);
|
||||
impl From<GetStorageError> for Error {
|
||||
fn from(e: GetStorageError) -> Error {
|
||||
use runtime_api::GetStorageError::*;
|
||||
match e.0 {
|
||||
ContractDoesntExist => Error {
|
||||
code: ErrorCode::ServerError(CONTRACT_DOESNT_EXIST),
|
||||
message: "The specified contract doesn't exist.".into(),
|
||||
data: None,
|
||||
},
|
||||
IsTombstone => Error {
|
||||
code: ErrorCode::ServerError(CONTRACT_IS_A_TOMBSTONE),
|
||||
message: "The contract is a tombstone and doesn't have any storage.".into(),
|
||||
data: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A struct that encodes RPC parameters required for a call to a smart-contract.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CallRequest<AccountId, Balance> {
|
||||
origin: AccountId,
|
||||
dest: AccountId,
|
||||
value: Balance,
|
||||
gas_limit: number::NumberOrHex<u64>,
|
||||
input_data: Bytes,
|
||||
}
|
||||
|
||||
/// Contracts RPC methods.
|
||||
#[rpc]
|
||||
pub trait ContractsApi<BlockHash, AccountId, Balance> {
|
||||
/// Executes a call to a contract.
|
||||
///
|
||||
/// This call is performed locally without submitting any transactions. Thus executing this
|
||||
/// won't change any state. Nonetheless, the calling state-changing contracts is still possible.
|
||||
///
|
||||
/// This method is useful for calling getter-like methods on contracts.
|
||||
#[rpc(name = "contracts_call")]
|
||||
fn call(
|
||||
&self,
|
||||
call_request: CallRequest<AccountId, Balance>,
|
||||
at: Option<BlockHash>,
|
||||
) -> Result<ContractExecResult>;
|
||||
|
||||
/// Returns the value under a specified storage `key` in a contract given by `address` param,
|
||||
/// or `None` if it is not set.
|
||||
#[rpc(name = "contracts_getStorage")]
|
||||
fn get_storage(
|
||||
&self,
|
||||
address: AccountId,
|
||||
key: H256,
|
||||
at: Option<BlockHash>,
|
||||
) -> Result<Option<Bytes>>;
|
||||
}
|
||||
|
||||
/// An implementation of contract specific RPC methods.
|
||||
pub struct Contracts<C, B> {
|
||||
client: Arc<C>,
|
||||
_marker: std::marker::PhantomData<B>,
|
||||
}
|
||||
|
||||
impl<C, B> Contracts<C, B> {
|
||||
/// Create new `Contracts` with the given reference to the client.
|
||||
pub fn new(client: Arc<C>) -> Self {
|
||||
Contracts {
|
||||
client,
|
||||
_marker: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<C, Block, AccountId, Balance> ContractsApi<<Block as BlockT>::Hash, AccountId, Balance>
|
||||
for Contracts<C, Block>
|
||||
where
|
||||
Block: BlockT,
|
||||
C: Send + Sync + 'static,
|
||||
C: ProvideRuntimeApi,
|
||||
C: HeaderBackend<Block>,
|
||||
C::Api: ContractsRuntimeApi<Block, AccountId, Balance>,
|
||||
AccountId: Codec,
|
||||
Balance: Codec,
|
||||
{
|
||||
fn call(
|
||||
&self,
|
||||
call_request: CallRequest<AccountId, Balance>,
|
||||
at: Option<<Block as BlockT>::Hash>,
|
||||
) -> Result<ContractExecResult> {
|
||||
let api = self.client.runtime_api();
|
||||
let at = BlockId::hash(at.unwrap_or_else(||
|
||||
// If the block hash is not supplied assume the best block.
|
||||
self.client.info().best_hash));
|
||||
|
||||
let CallRequest {
|
||||
origin,
|
||||
dest,
|
||||
value,
|
||||
gas_limit,
|
||||
input_data,
|
||||
} = call_request;
|
||||
let gas_limit = gas_limit.to_number().map_err(|e| Error {
|
||||
code: ErrorCode::InvalidParams,
|
||||
message: e,
|
||||
data: None,
|
||||
})?;
|
||||
|
||||
let exec_result = api
|
||||
.call(&at, origin, dest, value, gas_limit, input_data.to_vec())
|
||||
.map_err(|e| Error {
|
||||
code: ErrorCode::ServerError(RUNTIME_ERROR),
|
||||
message: "Runtime trapped while executing a contract.".into(),
|
||||
data: Some(format!("{:?}", e).into()),
|
||||
})?;
|
||||
|
||||
Ok(exec_result)
|
||||
}
|
||||
|
||||
fn get_storage(
|
||||
&self,
|
||||
address: AccountId,
|
||||
key: H256,
|
||||
at: Option<<Block as BlockT>::Hash>,
|
||||
) -> Result<Option<Bytes>> {
|
||||
let api = self.client.runtime_api();
|
||||
let at = BlockId::hash(at.unwrap_or_else(||
|
||||
// If the block hash is not supplied assume the best block.
|
||||
self.client.info().best_hash));
|
||||
|
||||
let get_storage_result = api
|
||||
.get_storage(&at, address, key.into())
|
||||
.map_err(|e|
|
||||
// Handle general API calling errors.
|
||||
Error {
|
||||
code: ErrorCode::ServerError(RUNTIME_ERROR),
|
||||
message: "Runtime trapped while querying storage.".into(),
|
||||
data: Some(format!("{:?}", e).into()),
|
||||
})?
|
||||
.map_err(GetStorageError)?
|
||||
.map(Bytes);
|
||||
|
||||
Ok(get_storage_result)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
// Copyright 2018-2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Auxiliaries to help with managing partial changes to accounts state.
|
||||
|
||||
use super::{
|
||||
AliveContractInfo, BalanceOf, CodeHash, ContractInfo, ContractInfoOf, Trait, TrieId,
|
||||
TrieIdGenerator,
|
||||
};
|
||||
use crate::exec::StorageKey;
|
||||
use rstd::cell::RefCell;
|
||||
use rstd::collections::btree_map::{BTreeMap, Entry};
|
||||
use rstd::prelude::*;
|
||||
use runtime_io::hashing::blake2_256;
|
||||
use sr_primitives::traits::{Bounded, Zero};
|
||||
use support::traits::{Currency, Get, Imbalance, SignedImbalance, UpdateBalanceOutcome};
|
||||
use support::{storage::child, StorageMap};
|
||||
use system;
|
||||
|
||||
// Note: we don't provide Option<Contract> because we can't create
|
||||
// the trie_id in the overlay, thus we provide an overlay on the fields
|
||||
// specifically.
|
||||
pub struct ChangeEntry<T: Trait> {
|
||||
/// If Some(_), then the account balance is modified to the value. If None and `reset` is false,
|
||||
/// the balance unmodified. If None and `reset` is true, the balance is reset to 0.
|
||||
balance: Option<BalanceOf<T>>,
|
||||
/// If Some(_), then a contract is instantiated with the code hash. If None and `reset` is false,
|
||||
/// then the contract code is unmodified. If None and `reset` is true, the contract is deleted.
|
||||
code_hash: Option<CodeHash<T>>,
|
||||
/// If Some(_), then the rent allowance is set to the value. If None and `reset` is false, then
|
||||
/// the rent allowance is unmodified. If None and `reset` is true, the contract is deleted.
|
||||
rent_allowance: Option<BalanceOf<T>>,
|
||||
storage: BTreeMap<StorageKey, Option<Vec<u8>>>,
|
||||
/// If true, indicates that the existing contract and all its storage entries should be removed
|
||||
/// and replaced with the fields on this change entry. Otherwise, the fields on this change
|
||||
/// entry are updates merged into the existing contract info and storage.
|
||||
reset: bool,
|
||||
}
|
||||
|
||||
impl<T: Trait> ChangeEntry<T> {
|
||||
fn balance(&self) -> Option<BalanceOf<T>> {
|
||||
self.balance.or_else(|| {
|
||||
if self.reset {
|
||||
Some(<BalanceOf<T>>::zero())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn code_hash(&self) -> Option<Option<CodeHash<T>>> {
|
||||
if self.reset {
|
||||
Some(self.code_hash)
|
||||
} else {
|
||||
self.code_hash.map(Some)
|
||||
}
|
||||
}
|
||||
|
||||
fn rent_allowance(&self) -> Option<Option<BalanceOf<T>>> {
|
||||
if self.reset {
|
||||
Some(self.rent_allowance)
|
||||
} else {
|
||||
self.rent_allowance.map(Some)
|
||||
}
|
||||
}
|
||||
|
||||
fn storage(&self, location: &StorageKey) -> Option<Option<Vec<u8>>> {
|
||||
let value = self.storage.get(location).cloned();
|
||||
if self.reset {
|
||||
Some(value.unwrap_or(None))
|
||||
} else {
|
||||
value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Cannot derive(Default) since it erroneously bounds T by Default.
|
||||
impl<T: Trait> Default for ChangeEntry<T> {
|
||||
fn default() -> Self {
|
||||
ChangeEntry {
|
||||
rent_allowance: Default::default(),
|
||||
balance: Default::default(),
|
||||
code_hash: Default::default(),
|
||||
storage: Default::default(),
|
||||
reset: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type ChangeSet<T> = BTreeMap<<T as system::Trait>::AccountId, ChangeEntry<T>>;
|
||||
|
||||
pub trait AccountDb<T: Trait> {
|
||||
/// Account is used when overlayed otherwise trie_id must be provided.
|
||||
/// This is for performance reason.
|
||||
///
|
||||
/// Trie id is None iff account doesn't have an associated trie id in <ContractInfoOf<T>>.
|
||||
/// Because DirectAccountDb bypass the lookup for this association.
|
||||
fn get_storage(&self, account: &T::AccountId, trie_id: Option<&TrieId>, location: &StorageKey) -> Option<Vec<u8>>;
|
||||
/// If account has an alive contract then return the code hash associated.
|
||||
fn get_code_hash(&self, account: &T::AccountId) -> Option<CodeHash<T>>;
|
||||
/// If account has an alive contract then return the rent allowance associated.
|
||||
fn get_rent_allowance(&self, account: &T::AccountId) -> Option<BalanceOf<T>>;
|
||||
/// Returns false iff account has no alive contract nor tombstone.
|
||||
fn contract_exists(&self, account: &T::AccountId) -> bool;
|
||||
fn get_balance(&self, account: &T::AccountId) -> BalanceOf<T>;
|
||||
|
||||
fn commit(&mut self, change_set: ChangeSet<T>);
|
||||
}
|
||||
|
||||
pub struct DirectAccountDb;
|
||||
impl<T: Trait> AccountDb<T> for DirectAccountDb {
|
||||
fn get_storage(
|
||||
&self,
|
||||
_account: &T::AccountId,
|
||||
trie_id: Option<&TrieId>,
|
||||
location: &StorageKey
|
||||
) -> Option<Vec<u8>> {
|
||||
trie_id.and_then(|id| child::get_raw(id, &blake2_256(location)))
|
||||
}
|
||||
fn get_code_hash(&self, account: &T::AccountId) -> Option<CodeHash<T>> {
|
||||
<ContractInfoOf<T>>::get(account).and_then(|i| i.as_alive().map(|i| i.code_hash))
|
||||
}
|
||||
fn get_rent_allowance(&self, account: &T::AccountId) -> Option<BalanceOf<T>> {
|
||||
<ContractInfoOf<T>>::get(account).and_then(|i| i.as_alive().map(|i| i.rent_allowance))
|
||||
}
|
||||
fn contract_exists(&self, account: &T::AccountId) -> bool {
|
||||
<ContractInfoOf<T>>::exists(account)
|
||||
}
|
||||
fn get_balance(&self, account: &T::AccountId) -> BalanceOf<T> {
|
||||
T::Currency::free_balance(account)
|
||||
}
|
||||
fn commit(&mut self, s: ChangeSet<T>) {
|
||||
let mut total_imbalance = SignedImbalance::zero();
|
||||
for (address, changed) in s.into_iter() {
|
||||
if let Some(balance) = changed.balance() {
|
||||
let (imbalance, outcome) = T::Currency::make_free_balance_be(&address, balance);
|
||||
total_imbalance = total_imbalance.merge(imbalance);
|
||||
if let UpdateBalanceOutcome::AccountKilled = outcome {
|
||||
// Account killed. This will ultimately lead to calling `OnFreeBalanceZero` callback
|
||||
// which will make removal of CodeHashOf and AccountStorage for this account.
|
||||
// In order to avoid writing over the deleted properties we `continue` here.
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if changed.code_hash().is_some()
|
||||
|| changed.rent_allowance().is_some()
|
||||
|| !changed.storage.is_empty()
|
||||
|| changed.reset
|
||||
{
|
||||
let old_info = match <ContractInfoOf<T>>::get(&address) {
|
||||
Some(ContractInfo::Alive(alive)) => Some(alive),
|
||||
None => None,
|
||||
// Cannot commit changes to tombstone contract
|
||||
Some(ContractInfo::Tombstone(_)) => continue,
|
||||
};
|
||||
|
||||
let mut new_info = match (changed.reset, old_info.clone(), changed.code_hash) {
|
||||
// Existing contract is being modified.
|
||||
(false, Some(info), _) => info,
|
||||
// Existing contract is being removed.
|
||||
(true, Some(info), None) => {
|
||||
child::kill_storage(&info.trie_id);
|
||||
<ContractInfoOf<T>>::remove(&address);
|
||||
continue;
|
||||
}
|
||||
// Existing contract is being replaced by a new one.
|
||||
(true, Some(info), Some(code_hash)) => {
|
||||
child::kill_storage(&info.trie_id);
|
||||
AliveContractInfo::<T> {
|
||||
code_hash,
|
||||
storage_size: T::StorageSizeOffset::get(),
|
||||
trie_id: <T as Trait>::TrieIdGenerator::trie_id(&address),
|
||||
deduct_block: <system::Module<T>>::block_number(),
|
||||
rent_allowance: <BalanceOf<T>>::max_value(),
|
||||
last_write: None,
|
||||
}
|
||||
}
|
||||
// New contract is being instantiated.
|
||||
(_, None, Some(code_hash)) => {
|
||||
AliveContractInfo::<T> {
|
||||
code_hash,
|
||||
storage_size: T::StorageSizeOffset::get(),
|
||||
trie_id: <T as Trait>::TrieIdGenerator::trie_id(&address),
|
||||
deduct_block: <system::Module<T>>::block_number(),
|
||||
rent_allowance: <BalanceOf<T>>::max_value(),
|
||||
last_write: None,
|
||||
}
|
||||
}
|
||||
// There is no existing at the address nor a new one to be instantiated.
|
||||
(_, None, None) => continue,
|
||||
};
|
||||
|
||||
if let Some(rent_allowance) = changed.rent_allowance {
|
||||
new_info.rent_allowance = rent_allowance;
|
||||
}
|
||||
|
||||
if let Some(code_hash) = changed.code_hash {
|
||||
new_info.code_hash = code_hash;
|
||||
}
|
||||
|
||||
if !changed.storage.is_empty() {
|
||||
new_info.last_write = Some(<system::Module<T>>::block_number());
|
||||
}
|
||||
|
||||
for (k, v) in changed.storage.into_iter() {
|
||||
if let Some(value) = child::get_raw(&new_info.trie_id[..], &blake2_256(&k)) {
|
||||
new_info.storage_size -= value.len() as u32;
|
||||
}
|
||||
if let Some(value) = v {
|
||||
new_info.storage_size += value.len() as u32;
|
||||
child::put_raw(&new_info.trie_id[..], &blake2_256(&k), &value[..]);
|
||||
} else {
|
||||
child::kill(&new_info.trie_id[..], &blake2_256(&k));
|
||||
}
|
||||
}
|
||||
|
||||
if old_info
|
||||
.map(|old_info| old_info != new_info)
|
||||
.unwrap_or(true)
|
||||
{
|
||||
<ContractInfoOf<T>>::insert(&address, ContractInfo::Alive(new_info));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match total_imbalance {
|
||||
// If we've detected a positive imbalance as a result of our contract-level machinations
|
||||
// then it's indicative of a buggy contracts system.
|
||||
// Panicking is far from ideal as it opens up a DoS attack on block validators, however
|
||||
// it's a less bad option than allowing arbitrary value to be created.
|
||||
SignedImbalance::Positive(ref p) if !p.peek().is_zero() =>
|
||||
panic!("contract subsystem resulting in positive imbalance!"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
pub struct OverlayAccountDb<'a, T: Trait + 'a> {
|
||||
local: RefCell<ChangeSet<T>>,
|
||||
underlying: &'a dyn AccountDb<T>,
|
||||
}
|
||||
impl<'a, T: Trait> OverlayAccountDb<'a, T> {
|
||||
pub fn new(underlying: &'a dyn AccountDb<T>) -> OverlayAccountDb<'a, T> {
|
||||
OverlayAccountDb {
|
||||
local: RefCell::new(ChangeSet::new()),
|
||||
underlying,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_change_set(self) -> ChangeSet<T> {
|
||||
self.local.into_inner()
|
||||
}
|
||||
|
||||
pub fn set_storage(
|
||||
&mut self,
|
||||
account: &T::AccountId,
|
||||
location: StorageKey,
|
||||
value: Option<Vec<u8>>,
|
||||
) {
|
||||
self.local.borrow_mut()
|
||||
.entry(account.clone())
|
||||
.or_insert(Default::default())
|
||||
.storage
|
||||
.insert(location, value);
|
||||
}
|
||||
|
||||
/// Return an error if contract already exists (either if it is alive or tombstone)
|
||||
pub fn instantiate_contract(
|
||||
&mut self,
|
||||
account: &T::AccountId,
|
||||
code_hash: CodeHash<T>,
|
||||
) -> Result<(), &'static str> {
|
||||
if self.contract_exists(account) {
|
||||
return Err("Alive contract or tombstone already exists");
|
||||
}
|
||||
|
||||
let mut local = self.local.borrow_mut();
|
||||
let contract = local.entry(account.clone()).or_insert_with(|| Default::default());
|
||||
|
||||
contract.code_hash = Some(code_hash);
|
||||
contract.rent_allowance = Some(<BalanceOf<T>>::max_value());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Mark a contract as deleted.
|
||||
pub fn destroy_contract(&mut self, account: &T::AccountId) {
|
||||
let mut local = self.local.borrow_mut();
|
||||
local.insert(
|
||||
account.clone(),
|
||||
ChangeEntry {
|
||||
reset: true,
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/// Assume contract exists
|
||||
pub fn set_rent_allowance(&mut self, account: &T::AccountId, rent_allowance: BalanceOf<T>) {
|
||||
self.local
|
||||
.borrow_mut()
|
||||
.entry(account.clone())
|
||||
.or_insert(Default::default())
|
||||
.rent_allowance = Some(rent_allowance);
|
||||
}
|
||||
pub fn set_balance(&mut self, account: &T::AccountId, balance: BalanceOf<T>) {
|
||||
self.local
|
||||
.borrow_mut()
|
||||
.entry(account.clone())
|
||||
.or_insert(Default::default())
|
||||
.balance = Some(balance);
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: Trait> AccountDb<T> for OverlayAccountDb<'a, T> {
|
||||
fn get_storage(
|
||||
&self,
|
||||
account: &T::AccountId,
|
||||
trie_id: Option<&TrieId>,
|
||||
location: &StorageKey
|
||||
) -> Option<Vec<u8>> {
|
||||
self.local
|
||||
.borrow()
|
||||
.get(account)
|
||||
.and_then(|changes| changes.storage(location))
|
||||
.unwrap_or_else(|| self.underlying.get_storage(account, trie_id, location))
|
||||
}
|
||||
fn get_code_hash(&self, account: &T::AccountId) -> Option<CodeHash<T>> {
|
||||
self.local
|
||||
.borrow()
|
||||
.get(account)
|
||||
.and_then(|changes| changes.code_hash())
|
||||
.unwrap_or_else(|| self.underlying.get_code_hash(account))
|
||||
}
|
||||
fn get_rent_allowance(&self, account: &T::AccountId) -> Option<BalanceOf<T>> {
|
||||
self.local
|
||||
.borrow()
|
||||
.get(account)
|
||||
.and_then(|changes| changes.rent_allowance())
|
||||
.unwrap_or_else(|| self.underlying.get_rent_allowance(account))
|
||||
}
|
||||
fn contract_exists(&self, account: &T::AccountId) -> bool {
|
||||
self.local
|
||||
.borrow()
|
||||
.get(account)
|
||||
.and_then(|changes| changes.code_hash().map(|code_hash| code_hash.is_some()))
|
||||
.unwrap_or_else(|| self.underlying.contract_exists(account))
|
||||
}
|
||||
fn get_balance(&self, account: &T::AccountId) -> BalanceOf<T> {
|
||||
self.local
|
||||
.borrow()
|
||||
.get(account)
|
||||
.and_then(|changes| changes.balance())
|
||||
.unwrap_or_else(|| self.underlying.get_balance(account))
|
||||
}
|
||||
fn commit(&mut self, s: ChangeSet<T>) {
|
||||
let mut local = self.local.borrow_mut();
|
||||
|
||||
for (address, changed) in s.into_iter() {
|
||||
match local.entry(address) {
|
||||
Entry::Occupied(e) => {
|
||||
let mut value = e.into_mut();
|
||||
if changed.reset {
|
||||
*value = changed;
|
||||
} else {
|
||||
value.balance = changed.balance.or(value.balance);
|
||||
value.code_hash = changed.code_hash.or(value.code_hash);
|
||||
value.rent_allowance = changed.rent_allowance.or(value.rent_allowance);
|
||||
value.storage.extend(changed.storage.into_iter());
|
||||
}
|
||||
}
|
||||
Entry::Vacant(e) => {
|
||||
e.insert(changed);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,384 @@
|
||||
// Copyright 2018-2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
use crate::{GasSpent, Module, Trait, BalanceOf, NegativeImbalanceOf};
|
||||
use rstd::convert::TryFrom;
|
||||
use sr_primitives::traits::{
|
||||
CheckedMul, Zero, SaturatedConversion, SimpleArithmetic, UniqueSaturatedInto,
|
||||
};
|
||||
use support::{
|
||||
traits::{Currency, ExistenceRequirement, Imbalance, OnUnbalanced, WithdrawReason}, StorageValue,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
use std::{any::Any, fmt::Debug};
|
||||
|
||||
// Gas units are chosen to be represented by u64 so that gas metering instructions can operate on
|
||||
// them efficiently.
|
||||
pub type Gas = u64;
|
||||
|
||||
#[must_use]
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum GasMeterResult {
|
||||
Proceed,
|
||||
OutOfGas,
|
||||
}
|
||||
|
||||
impl GasMeterResult {
|
||||
pub fn is_out_of_gas(&self) -> bool {
|
||||
match *self {
|
||||
GasMeterResult::OutOfGas => true,
|
||||
GasMeterResult::Proceed => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(test))]
|
||||
pub trait TestAuxiliaries {}
|
||||
#[cfg(not(test))]
|
||||
impl<T> TestAuxiliaries for T {}
|
||||
|
||||
#[cfg(test)]
|
||||
pub trait TestAuxiliaries: Any + Debug + PartialEq + Eq {}
|
||||
#[cfg(test)]
|
||||
impl<T: Any + Debug + PartialEq + Eq> TestAuxiliaries for T {}
|
||||
|
||||
/// This trait represents a token that can be used for charging `GasMeter`.
|
||||
/// There is no other way of charging it.
|
||||
///
|
||||
/// Implementing type is expected to be super lightweight hence `Copy` (`Clone` is added
|
||||
/// for consistency). If inlined there should be no observable difference compared
|
||||
/// to a hand-written code.
|
||||
pub trait Token<T: Trait>: Copy + Clone + TestAuxiliaries {
|
||||
/// Metadata type, which the token can require for calculating the amount
|
||||
/// of gas to charge. Can be a some configuration type or
|
||||
/// just the `()`.
|
||||
type Metadata;
|
||||
|
||||
/// Calculate amount of gas that should be taken by this token.
|
||||
///
|
||||
/// This function should be really lightweight and must not fail. It is not
|
||||
/// expected that implementors will query the storage or do any kinds of heavy operations.
|
||||
///
|
||||
/// That said, implementors of this function still can run into overflows
|
||||
/// while calculating the amount. In this case it is ok to use saturating operations
|
||||
/// since on overflow they will return `max_value` which should consume all gas.
|
||||
fn calculate_amount(&self, metadata: &Self::Metadata) -> Gas;
|
||||
}
|
||||
|
||||
/// A wrapper around a type-erased trait object of what used to be a `Token`.
|
||||
#[cfg(test)]
|
||||
pub struct ErasedToken {
|
||||
pub description: String,
|
||||
pub token: Box<dyn Any>,
|
||||
}
|
||||
|
||||
pub struct GasMeter<T: Trait> {
|
||||
limit: Gas,
|
||||
/// Amount of gas left from initial gas limit. Can reach zero.
|
||||
gas_left: Gas,
|
||||
gas_price: BalanceOf<T>,
|
||||
|
||||
#[cfg(test)]
|
||||
tokens: Vec<ErasedToken>,
|
||||
}
|
||||
impl<T: Trait> GasMeter<T> {
|
||||
pub fn with_limit(gas_limit: Gas, gas_price: BalanceOf<T>) -> GasMeter<T> {
|
||||
GasMeter {
|
||||
limit: gas_limit,
|
||||
gas_left: gas_limit,
|
||||
gas_price,
|
||||
#[cfg(test)]
|
||||
tokens: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Account for used gas.
|
||||
///
|
||||
/// Amount is calculated by the given `token`.
|
||||
///
|
||||
/// Returns `OutOfGas` if there is not enough gas or addition of the specified
|
||||
/// amount of gas has lead to overflow. On success returns `Proceed`.
|
||||
///
|
||||
/// NOTE that amount is always consumed, i.e. if there is not enough gas
|
||||
/// then the counter will be set to zero.
|
||||
#[inline]
|
||||
pub fn charge<Tok: Token<T>>(
|
||||
&mut self,
|
||||
metadata: &Tok::Metadata,
|
||||
token: Tok,
|
||||
) -> GasMeterResult {
|
||||
#[cfg(test)]
|
||||
{
|
||||
// Unconditionally add the token to the storage.
|
||||
let erased_tok = ErasedToken {
|
||||
description: format!("{:?}", token),
|
||||
token: Box::new(token),
|
||||
};
|
||||
self.tokens.push(erased_tok);
|
||||
}
|
||||
|
||||
let amount = token.calculate_amount(metadata);
|
||||
let new_value = match self.gas_left.checked_sub(amount) {
|
||||
None => None,
|
||||
Some(val) => Some(val),
|
||||
};
|
||||
|
||||
// We always consume the gas even if there is not enough gas.
|
||||
self.gas_left = new_value.unwrap_or_else(Zero::zero);
|
||||
|
||||
match new_value {
|
||||
Some(_) => GasMeterResult::Proceed,
|
||||
None => GasMeterResult::OutOfGas,
|
||||
}
|
||||
}
|
||||
|
||||
/// Allocate some amount of gas and perform some work with
|
||||
/// a newly created nested gas meter.
|
||||
///
|
||||
/// Invokes `f` with either the gas meter that has `amount` gas left or
|
||||
/// with `None`, if this gas meter has not enough gas to allocate given `amount`.
|
||||
///
|
||||
/// All unused gas in the nested gas meter is returned to this gas meter.
|
||||
pub fn with_nested<R, F: FnOnce(Option<&mut GasMeter<T>>) -> R>(
|
||||
&mut self,
|
||||
amount: Gas,
|
||||
f: F,
|
||||
) -> R {
|
||||
// NOTE that it is ok to allocate all available gas since it still ensured
|
||||
// by `charge` that it doesn't reach zero.
|
||||
if self.gas_left < amount {
|
||||
f(None)
|
||||
} else {
|
||||
self.gas_left = self.gas_left - amount;
|
||||
let mut nested = GasMeter::with_limit(amount, self.gas_price);
|
||||
|
||||
let r = f(Some(&mut nested));
|
||||
|
||||
self.gas_left = self.gas_left + nested.gas_left;
|
||||
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
pub fn gas_price(&self) -> BalanceOf<T> {
|
||||
self.gas_price
|
||||
}
|
||||
|
||||
/// Returns how much gas left from the initial budget.
|
||||
pub fn gas_left(&self) -> Gas {
|
||||
self.gas_left
|
||||
}
|
||||
|
||||
/// Returns how much gas was spent.
|
||||
fn spent(&self) -> Gas {
|
||||
self.limit - self.gas_left
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn tokens(&self) -> &[ErasedToken] {
|
||||
&self.tokens
|
||||
}
|
||||
}
|
||||
|
||||
/// Buy the given amount of gas.
|
||||
///
|
||||
/// Cost is calculated by multiplying the gas cost (taken from the storage) by the `gas_limit`.
|
||||
/// The funds are deducted from `transactor`.
|
||||
pub fn buy_gas<T: Trait>(
|
||||
transactor: &T::AccountId,
|
||||
gas_limit: Gas,
|
||||
) -> Result<(GasMeter<T>, NegativeImbalanceOf<T>), &'static str> {
|
||||
// Buy the specified amount of gas.
|
||||
let gas_price = <Module<T>>::gas_price();
|
||||
let cost = if gas_price.is_zero() {
|
||||
<BalanceOf<T>>::zero()
|
||||
} else {
|
||||
<BalanceOf<T> as TryFrom<Gas>>::try_from(gas_limit).ok()
|
||||
.and_then(|gas_limit| gas_price.checked_mul(&gas_limit))
|
||||
.ok_or("overflow multiplying gas limit by price")?
|
||||
};
|
||||
|
||||
let imbalance = T::Currency::withdraw(
|
||||
transactor,
|
||||
cost,
|
||||
WithdrawReason::Fee.into(),
|
||||
ExistenceRequirement::KeepAlive
|
||||
)?;
|
||||
|
||||
Ok((GasMeter::with_limit(gas_limit, gas_price), imbalance))
|
||||
}
|
||||
|
||||
/// Refund the unused gas.
|
||||
pub fn refund_unused_gas<T: Trait>(
|
||||
transactor: &T::AccountId,
|
||||
gas_meter: GasMeter<T>,
|
||||
imbalance: NegativeImbalanceOf<T>,
|
||||
) {
|
||||
let gas_spent = gas_meter.spent();
|
||||
let gas_left = gas_meter.gas_left();
|
||||
|
||||
// Increase total spent gas.
|
||||
// This cannot overflow, since `gas_spent` is never greater than `block_gas_limit`, which
|
||||
// also has Gas type.
|
||||
GasSpent::mutate(|block_gas_spent| *block_gas_spent += gas_spent);
|
||||
|
||||
// Refund gas left by the price it was bought at.
|
||||
let refund = gas_meter.gas_price * gas_left.unique_saturated_into();
|
||||
let refund_imbalance = T::Currency::deposit_creating(transactor, refund);
|
||||
if let Ok(imbalance) = imbalance.offset(refund_imbalance) {
|
||||
T::GasPayment::on_unbalanced(imbalance);
|
||||
}
|
||||
}
|
||||
|
||||
/// A little handy utility for converting a value in balance units into approximate value in gas units
|
||||
/// at the given gas price.
|
||||
pub fn approx_gas_for_balance<Balance>(gas_price: Balance, balance: Balance) -> Gas
|
||||
where Balance: SimpleArithmetic
|
||||
{
|
||||
(balance / gas_price).saturated_into::<Gas>()
|
||||
}
|
||||
|
||||
/// A simple utility macro that helps to match against a
|
||||
/// list of tokens.
|
||||
#[macro_export]
|
||||
macro_rules! match_tokens {
|
||||
($tokens_iter:ident,) => {
|
||||
};
|
||||
($tokens_iter:ident, $x:expr, $($rest:tt)*) => {
|
||||
{
|
||||
let next = ($tokens_iter).next().unwrap();
|
||||
let pattern = $x;
|
||||
|
||||
// Note that we don't specify the type name directly in this macro,
|
||||
// we only have some expression $x of some type. At the same time, we
|
||||
// have an iterator of Box<dyn Any> and to downcast we need to specify
|
||||
// the type which we want downcast to.
|
||||
//
|
||||
// So what we do is we assign `_pattern_typed_next_ref` to a variable which has
|
||||
// the required type.
|
||||
//
|
||||
// Then we make `_pattern_typed_next_ref = token.downcast_ref()`. This makes
|
||||
// rustc infer the type `T` (in `downcast_ref<T: Any>`) to be the same as in $x.
|
||||
|
||||
let mut _pattern_typed_next_ref = &pattern;
|
||||
_pattern_typed_next_ref = match next.token.downcast_ref() {
|
||||
Some(p) => {
|
||||
assert_eq!(p, &pattern);
|
||||
p
|
||||
}
|
||||
None => {
|
||||
panic!("expected type {} got {}", stringify!($x), next.description);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
match_tokens!($tokens_iter, $($rest)*);
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{GasMeter, Token};
|
||||
use crate::tests::Test;
|
||||
|
||||
/// A trivial token that charges the specified number of gas units.
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
struct SimpleToken(u64);
|
||||
impl Token<Test> for SimpleToken {
|
||||
type Metadata = ();
|
||||
fn calculate_amount(&self, _metadata: &()) -> u64 { self.0 }
|
||||
}
|
||||
|
||||
struct MultiplierTokenMetadata {
|
||||
multiplier: u64,
|
||||
}
|
||||
/// A simple token that charges for the given amount multiplied to
|
||||
/// a multiplier taken from a given metadata.
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
||||
struct MultiplierToken(u64);
|
||||
|
||||
impl Token<Test> for MultiplierToken {
|
||||
type Metadata = MultiplierTokenMetadata;
|
||||
fn calculate_amount(&self, metadata: &MultiplierTokenMetadata) -> u64 {
|
||||
// Probably you want to use saturating mul in production code.
|
||||
self.0 * metadata.multiplier
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_works() {
|
||||
let gas_meter = GasMeter::<Test>::with_limit(50000, 10);
|
||||
assert_eq!(gas_meter.gas_left(), 50000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simple() {
|
||||
let mut gas_meter = GasMeter::<Test>::with_limit(50000, 10);
|
||||
|
||||
let result = gas_meter
|
||||
.charge(&MultiplierTokenMetadata { multiplier: 3 }, MultiplierToken(10));
|
||||
assert!(!result.is_out_of_gas());
|
||||
|
||||
assert_eq!(gas_meter.gas_left(), 49_970);
|
||||
assert_eq!(gas_meter.spent(), 30);
|
||||
assert_eq!(gas_meter.gas_price(), 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tracing() {
|
||||
let mut gas_meter = GasMeter::<Test>::with_limit(50000, 10);
|
||||
assert!(!gas_meter.charge(&(), SimpleToken(1)).is_out_of_gas());
|
||||
assert!(!gas_meter
|
||||
.charge(&MultiplierTokenMetadata { multiplier: 3 }, MultiplierToken(10))
|
||||
.is_out_of_gas());
|
||||
|
||||
let mut tokens = gas_meter.tokens()[0..2].iter();
|
||||
match_tokens!(tokens, SimpleToken(1), MultiplierToken(10),);
|
||||
}
|
||||
|
||||
// This test makes sure that nothing can be executed if there is no gas.
|
||||
#[test]
|
||||
fn refuse_to_execute_anything_if_zero() {
|
||||
let mut gas_meter = GasMeter::<Test>::with_limit(0, 10);
|
||||
assert!(gas_meter.charge(&(), SimpleToken(1)).is_out_of_gas());
|
||||
}
|
||||
|
||||
// Make sure that if the gas meter is charged by exceeding amount then not only an error
|
||||
// returned for that charge, but also for all consequent charges.
|
||||
//
|
||||
// This is not strictly necessary, because the execution should be interrupted immediately
|
||||
// if the gas meter runs out of gas. However, this is just a nice property to have.
|
||||
#[test]
|
||||
fn overcharge_is_unrecoverable() {
|
||||
let mut gas_meter = GasMeter::<Test>::with_limit(200, 10);
|
||||
|
||||
// The first charge is should lead to OOG.
|
||||
assert!(gas_meter.charge(&(), SimpleToken(300)).is_out_of_gas());
|
||||
|
||||
// The gas meter is emptied at this moment, so this should also fail.
|
||||
assert!(gas_meter.charge(&(), SimpleToken(1)).is_out_of_gas());
|
||||
}
|
||||
|
||||
|
||||
// Charging the exact amount that the user paid for should be
|
||||
// possible.
|
||||
#[test]
|
||||
fn charge_exact_amount() {
|
||||
let mut gas_meter = GasMeter::<Test>::with_limit(25, 10);
|
||||
assert!(!gas_meter.charge(&(), SimpleToken(25)).is_out_of_gas());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,194 @@
|
||||
// Copyright 2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
use crate::{BalanceOf, ContractInfo, ContractInfoOf, TombstoneContractInfo, Trait, AliveContractInfo};
|
||||
use sr_primitives::traits::{Bounded, CheckedDiv, CheckedMul, Saturating, Zero,
|
||||
SaturatedConversion};
|
||||
use support::traits::{Currency, ExistenceRequirement, Get, WithdrawReason, OnUnbalanced};
|
||||
use support::StorageMap;
|
||||
|
||||
#[derive(PartialEq, Eq, Copy, Clone)]
|
||||
#[must_use]
|
||||
pub enum RentOutcome {
|
||||
/// Exempted from rent iff:
|
||||
/// * rent is offset completely by the `rent_deposit_offset`,
|
||||
/// * or rent has already been paid for this block number,
|
||||
/// * or account doesn't have a contract,
|
||||
/// * or account has a tombstone.
|
||||
Exempted,
|
||||
/// Evicted iff:
|
||||
/// * rent exceed rent allowance,
|
||||
/// * or can't withdraw the rent,
|
||||
/// * or go below subsistence threshold.
|
||||
Evicted,
|
||||
/// The outstanding dues were paid or were able to be paid.
|
||||
Ok,
|
||||
}
|
||||
|
||||
/// Evict and optionally pay dues (or check account can pay them otherwise) at the current
|
||||
/// block number (modulo `handicap`, read on).
|
||||
///
|
||||
/// `pay_rent` gives an ability to pay or skip paying rent.
|
||||
/// `handicap` gives a way to check or pay the rent up to a moment in the past instead
|
||||
/// of current block.
|
||||
///
|
||||
/// NOTE: This function acts eagerly, all modification are committed into the storage.
|
||||
fn try_evict_or_and_pay_rent<T: Trait>(
|
||||
account: &T::AccountId,
|
||||
handicap: T::BlockNumber,
|
||||
pay_rent: bool,
|
||||
) -> (RentOutcome, Option<ContractInfo<T>>) {
|
||||
let contract_info = <ContractInfoOf<T>>::get(account);
|
||||
let contract = match contract_info {
|
||||
None | Some(ContractInfo::Tombstone(_)) => return (RentOutcome::Exempted, contract_info),
|
||||
Some(ContractInfo::Alive(contract)) => contract,
|
||||
};
|
||||
|
||||
let current_block_number = <system::Module<T>>::block_number();
|
||||
|
||||
// How much block has passed since the last deduction for the contract.
|
||||
let blocks_passed = {
|
||||
// Calculate an effective block number, i.e. after adjusting for handicap.
|
||||
let effective_block_number = current_block_number.saturating_sub(handicap);
|
||||
let n = effective_block_number.saturating_sub(contract.deduct_block);
|
||||
if n.is_zero() {
|
||||
// Rent has already been paid
|
||||
return (RentOutcome::Exempted, Some(ContractInfo::Alive(contract)));
|
||||
}
|
||||
n
|
||||
};
|
||||
|
||||
let balance = T::Currency::free_balance(account);
|
||||
|
||||
// An amount of funds to charge per block for storage taken up by the contract.
|
||||
let fee_per_block = {
|
||||
let free_storage = balance
|
||||
.checked_div(&T::RentDepositOffset::get())
|
||||
.unwrap_or_else(Zero::zero);
|
||||
|
||||
let effective_storage_size =
|
||||
<BalanceOf<T>>::from(contract.storage_size).saturating_sub(free_storage);
|
||||
|
||||
effective_storage_size
|
||||
.checked_mul(&T::RentByteFee::get())
|
||||
.unwrap_or(<BalanceOf<T>>::max_value())
|
||||
};
|
||||
|
||||
if fee_per_block.is_zero() {
|
||||
// The rent deposit offset reduced the fee to 0. This means that the contract
|
||||
// gets the rent for free.
|
||||
return (RentOutcome::Exempted, Some(ContractInfo::Alive(contract)));
|
||||
}
|
||||
|
||||
// The minimal amount of funds required for a contract not to be evicted.
|
||||
let subsistence_threshold = T::Currency::minimum_balance() + T::TombstoneDeposit::get();
|
||||
|
||||
if balance < subsistence_threshold {
|
||||
// The contract cannot afford to leave a tombstone, so remove the contract info altogether.
|
||||
<ContractInfoOf<T>>::remove(account);
|
||||
runtime_io::storage::child_storage_kill(&contract.trie_id);
|
||||
return (RentOutcome::Evicted, None);
|
||||
}
|
||||
|
||||
let dues = fee_per_block
|
||||
.checked_mul(&blocks_passed.saturated_into::<u32>().into())
|
||||
.unwrap_or(<BalanceOf<T>>::max_value());
|
||||
let rent_budget = contract.rent_allowance.min(balance - subsistence_threshold);
|
||||
let insufficient_rent = rent_budget < dues;
|
||||
|
||||
// If the rent payment cannot be withdrawn due to locks on the account balance, then evict the
|
||||
// account.
|
||||
//
|
||||
// NOTE: This seems problematic because it provides a way to tombstone an account while
|
||||
// avoiding the last rent payment. In effect, someone could retroactively set rent_allowance
|
||||
// for their contract to 0.
|
||||
let dues_limited = dues.min(rent_budget);
|
||||
let can_withdraw_rent = T::Currency::ensure_can_withdraw(
|
||||
account,
|
||||
dues_limited,
|
||||
WithdrawReason::Fee.into(),
|
||||
balance.saturating_sub(dues_limited),
|
||||
)
|
||||
.is_ok();
|
||||
|
||||
if can_withdraw_rent && (insufficient_rent || pay_rent) {
|
||||
// Collect dues.
|
||||
let imbalance = T::Currency::withdraw(
|
||||
account,
|
||||
dues_limited,
|
||||
WithdrawReason::Fee.into(),
|
||||
ExistenceRequirement::KeepAlive,
|
||||
)
|
||||
.expect(
|
||||
"Withdraw has been checked above;
|
||||
dues_limited < rent_budget < balance - subsistence < balance - existential_deposit;
|
||||
qed",
|
||||
);
|
||||
|
||||
T::RentPayment::on_unbalanced(imbalance);
|
||||
}
|
||||
|
||||
if insufficient_rent || !can_withdraw_rent {
|
||||
// The contract cannot afford the rent payment and has a balance above the subsistence
|
||||
// threshold, so it leaves a tombstone.
|
||||
|
||||
// Note: this operation is heavy.
|
||||
let child_storage_root = runtime_io::storage::child_root(&contract.trie_id);
|
||||
|
||||
let tombstone = <TombstoneContractInfo<T>>::new(
|
||||
&child_storage_root[..],
|
||||
contract.code_hash,
|
||||
);
|
||||
let tombstone_info = ContractInfo::Tombstone(tombstone);
|
||||
<ContractInfoOf<T>>::insert(account, &tombstone_info);
|
||||
|
||||
runtime_io::storage::child_storage_kill(&contract.trie_id);
|
||||
|
||||
return (RentOutcome::Evicted, Some(tombstone_info));
|
||||
}
|
||||
|
||||
if pay_rent {
|
||||
let contract_info = ContractInfo::Alive(AliveContractInfo::<T> {
|
||||
rent_allowance: contract.rent_allowance - dues, // rent_allowance is not exceeded
|
||||
deduct_block: current_block_number,
|
||||
..contract
|
||||
});
|
||||
|
||||
<ContractInfoOf<T>>::insert(account, &contract_info);
|
||||
|
||||
return (RentOutcome::Ok, Some(contract_info));
|
||||
}
|
||||
|
||||
(RentOutcome::Ok, Some(ContractInfo::Alive(contract)))
|
||||
}
|
||||
|
||||
/// Make account paying the rent for the current block number
|
||||
///
|
||||
/// NOTE: This function acts eagerly.
|
||||
pub fn pay_rent<T: Trait>(account: &T::AccountId) -> Option<ContractInfo<T>> {
|
||||
try_evict_or_and_pay_rent::<T>(account, Zero::zero(), true).1
|
||||
}
|
||||
|
||||
/// Evict the account if it should be evicted at the given block number.
|
||||
///
|
||||
/// `handicap` gives a way to check or pay the rent up to a moment in the past instead
|
||||
/// of current block. E.g. if the contract is going to be evicted at the current block,
|
||||
/// `handicap=1` can defer the eviction for 1 block.
|
||||
///
|
||||
/// NOTE: This function acts eagerly.
|
||||
pub fn try_evict<T: Trait>(account: &T::AccountId, handicap: T::BlockNumber) -> RentOutcome {
|
||||
try_evict_or_and_pay_rent::<T>(account, handicap, false).0
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,104 @@
|
||||
// Copyright 2018-2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! A module that implements instrumented code cache.
|
||||
//!
|
||||
//! - In order to run contract code we need to instrument it with gas metering.
|
||||
//! To do that we need to provide the schedule which will supply exact gas costs values.
|
||||
//! We cache this code in the storage saving the schedule version.
|
||||
//! - Before running contract code we check if the cached code has the schedule version that
|
||||
//! is equal to the current saved schedule.
|
||||
//! If it is equal then run the code, if it isn't reinstrument with the current schedule.
|
||||
//! - When we update the schedule we want it to have strictly greater version than the current saved one:
|
||||
//! this guarantees that every instrumented contract code in cache cannot have the version equal to the current one.
|
||||
//! Thus, before executing a contract it should be reinstrument with new schedule.
|
||||
|
||||
use crate::gas::{Gas, GasMeter, Token};
|
||||
use crate::wasm::{prepare, runtime::Env, PrefabWasmModule};
|
||||
use crate::{CodeHash, CodeStorage, PristineCode, Schedule, Trait};
|
||||
use rstd::prelude::*;
|
||||
use sr_primitives::traits::{Hash, Bounded};
|
||||
use support::StorageMap;
|
||||
|
||||
/// Gas metering token that used for charging storing code into the code storage.
|
||||
///
|
||||
/// Specifies the code length in bytes.
|
||||
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct PutCodeToken(u32);
|
||||
|
||||
impl<T: Trait> Token<T> for PutCodeToken {
|
||||
type Metadata = Schedule;
|
||||
|
||||
fn calculate_amount(&self, metadata: &Schedule) -> Gas {
|
||||
metadata
|
||||
.put_code_per_byte_cost
|
||||
.checked_mul(self.0.into())
|
||||
.unwrap_or_else(|| Bounded::max_value())
|
||||
}
|
||||
}
|
||||
|
||||
/// Put code in the storage. The hash of code is used as a key and is returned
|
||||
/// as a result of this function.
|
||||
///
|
||||
/// This function instruments the given code and caches it in the storage.
|
||||
pub fn save<T: Trait>(
|
||||
original_code: Vec<u8>,
|
||||
gas_meter: &mut GasMeter<T>,
|
||||
schedule: &Schedule,
|
||||
) -> Result<CodeHash<T>, &'static str> {
|
||||
// The first time instrumentation is on the user. However, consequent reinstrumentation
|
||||
// due to the schedule changes is on governance system.
|
||||
if gas_meter
|
||||
.charge(schedule, PutCodeToken(original_code.len() as u32))
|
||||
.is_out_of_gas()
|
||||
{
|
||||
return Err("there is not enough gas for storing the code");
|
||||
}
|
||||
|
||||
let prefab_module = prepare::prepare_contract::<Env>(&original_code, schedule)?;
|
||||
let code_hash = T::Hashing::hash(&original_code);
|
||||
|
||||
<CodeStorage<T>>::insert(code_hash, prefab_module);
|
||||
<PristineCode<T>>::insert(code_hash, original_code);
|
||||
|
||||
Ok(code_hash)
|
||||
}
|
||||
|
||||
/// Load code with the given code hash.
|
||||
///
|
||||
/// If the module was instrumented with a lower version of schedule than
|
||||
/// the current one given as an argument, then this function will perform
|
||||
/// re-instrumentation and update the cache in the storage.
|
||||
pub fn load<T: Trait>(
|
||||
code_hash: &CodeHash<T>,
|
||||
schedule: &Schedule,
|
||||
) -> Result<PrefabWasmModule, &'static str> {
|
||||
let mut prefab_module =
|
||||
<CodeStorage<T>>::get(code_hash).ok_or_else(|| "code is not found")?;
|
||||
|
||||
if prefab_module.schedule_version < schedule.version {
|
||||
// The current schedule version is greater than the version of the one cached
|
||||
// in the storage.
|
||||
//
|
||||
// We need to re-instrument the code with the latest schedule here.
|
||||
let original_code =
|
||||
<PristineCode<T>>::get(code_hash).ok_or_else(|| "pristine code is not found")?;
|
||||
prefab_module = prepare::prepare_contract::<Env>(&original_code, schedule)?;
|
||||
<CodeStorage<T>>::insert(&code_hash, &prefab_module);
|
||||
}
|
||||
Ok(prefab_module)
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
// Copyright 2018-2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Definition of macros that hides boilerplate of defining external environment
|
||||
//! for a wasm module.
|
||||
//!
|
||||
//! Most likely you should use `define_env` macro.
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! convert_args {
|
||||
() => (vec![]);
|
||||
( $( $t:ty ),* ) => ( vec![ $( { use $crate::wasm::env_def::ConvertibleToWasm; <$t>::VALUE_TYPE }, )* ] );
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! gen_signature {
|
||||
( ( $( $params: ty ),* ) ) => (
|
||||
{
|
||||
parity_wasm::elements::FunctionType::new(convert_args!($($params),*), None)
|
||||
}
|
||||
);
|
||||
|
||||
( ( $( $params: ty ),* ) -> $returns: ty ) => (
|
||||
{
|
||||
parity_wasm::elements::FunctionType::new(convert_args!($($params),*), Some({
|
||||
use $crate::wasm::env_def::ConvertibleToWasm; <$returns>::VALUE_TYPE
|
||||
}))
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! gen_signature_dispatch {
|
||||
(
|
||||
$needle_name:ident,
|
||||
$needle_sig:ident ;
|
||||
$name:ident
|
||||
( $ctx:ident $( , $names:ident : $params:ty )* ) $( -> $returns:ty )* , $($rest:tt)* ) => {
|
||||
if stringify!($name).as_bytes() == $needle_name {
|
||||
let signature = gen_signature!( ( $( $params ),* ) $( -> $returns )* );
|
||||
if $needle_sig == &signature {
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
gen_signature_dispatch!($needle_name, $needle_sig ; $($rest)*);
|
||||
}
|
||||
};
|
||||
( $needle_name:ident, $needle_sig:ident ; ) => {
|
||||
};
|
||||
}
|
||||
|
||||
/// Unmarshall arguments and then execute `body` expression and return its result.
|
||||
macro_rules! unmarshall_then_body {
|
||||
( $body:tt, $ctx:ident, $args_iter:ident, $( $names:ident : $params:ty ),* ) => ({
|
||||
$(
|
||||
let $names : <$params as $crate::wasm::env_def::ConvertibleToWasm>::NativeType =
|
||||
$args_iter.next()
|
||||
.and_then(|v| <$params as $crate::wasm::env_def::ConvertibleToWasm>
|
||||
::from_typed_value(v.clone()))
|
||||
.expect(
|
||||
"precondition: all imports should be checked against the signatures of corresponding
|
||||
functions defined by `define_env!` macro by the user of the macro;
|
||||
signatures of these functions defined by `$params`;
|
||||
calls always made with arguments types of which are defined by the corresponding imports;
|
||||
thus types of arguments should be equal to type list in `$params` and
|
||||
length of argument list and $params should be equal;
|
||||
thus this can never be `None`;
|
||||
qed;
|
||||
"
|
||||
);
|
||||
)*
|
||||
$body
|
||||
})
|
||||
}
|
||||
|
||||
/// Since we can't specify the type of closure directly at binding site:
|
||||
///
|
||||
/// ```nocompile
|
||||
/// let f: FnOnce() -> Result<<u32 as ConvertibleToWasm>::NativeType, _> = || { /* ... */ };
|
||||
/// ```
|
||||
///
|
||||
/// we use this function to constrain the type of the closure.
|
||||
#[inline(always)]
|
||||
pub fn constrain_closure<R, F>(f: F) -> F
|
||||
where
|
||||
F: FnOnce() -> Result<R, sandbox::HostError>,
|
||||
{
|
||||
f
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! unmarshall_then_body_then_marshall {
|
||||
( $args_iter:ident, $ctx:ident, ( $( $names:ident : $params:ty ),* ) -> $returns:ty => $body:tt ) => ({
|
||||
let body = $crate::wasm::env_def::macros::constrain_closure::<
|
||||
<$returns as $crate::wasm::env_def::ConvertibleToWasm>::NativeType, _
|
||||
>(|| {
|
||||
unmarshall_then_body!($body, $ctx, $args_iter, $( $names : $params ),*)
|
||||
});
|
||||
let r = body()?;
|
||||
return Ok(sandbox::ReturnValue::Value({ use $crate::wasm::env_def::ConvertibleToWasm; r.to_typed_value() }))
|
||||
});
|
||||
( $args_iter:ident, $ctx:ident, ( $( $names:ident : $params:ty ),* ) => $body:tt ) => ({
|
||||
let body = $crate::wasm::env_def::macros::constrain_closure::<(), _>(|| {
|
||||
unmarshall_then_body!($body, $ctx, $args_iter, $( $names : $params ),*)
|
||||
});
|
||||
body()?;
|
||||
return Ok(sandbox::ReturnValue::Unit)
|
||||
})
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! define_func {
|
||||
( < E: $ext_ty:tt > $name:ident ( $ctx: ident $(, $names:ident : $params:ty)*) $(-> $returns:ty)* => $body:tt ) => {
|
||||
fn $name< E: $ext_ty >(
|
||||
$ctx: &mut $crate::wasm::Runtime<E>,
|
||||
args: &[sandbox::TypedValue],
|
||||
) -> Result<sandbox::ReturnValue, sandbox::HostError> {
|
||||
#[allow(unused)]
|
||||
let mut args = args.iter();
|
||||
|
||||
unmarshall_then_body_then_marshall!(
|
||||
args,
|
||||
$ctx,
|
||||
( $( $names : $params ),* ) $( -> $returns )* => $body
|
||||
)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! register_func {
|
||||
( $reg_cb:ident, < E: $ext_ty:tt > ; ) => {};
|
||||
|
||||
( $reg_cb:ident, < E: $ext_ty:tt > ;
|
||||
$name:ident ( $ctx:ident $( , $names:ident : $params:ty )* )
|
||||
$( -> $returns:ty )* => $body:tt $($rest:tt)*
|
||||
) => {
|
||||
$reg_cb(
|
||||
stringify!($name).as_bytes(),
|
||||
{
|
||||
define_func!(
|
||||
< E: $ext_ty > $name ( $ctx $(, $names : $params )* ) $( -> $returns )* => $body
|
||||
);
|
||||
$name::<E>
|
||||
}
|
||||
);
|
||||
register_func!( $reg_cb, < E: $ext_ty > ; $($rest)* );
|
||||
};
|
||||
}
|
||||
|
||||
/// Define a function set that can be imported by executing wasm code.
|
||||
///
|
||||
/// **NB**: Be advised that all functions defined by this macro
|
||||
/// will panic if called with unexpected arguments.
|
||||
///
|
||||
/// It's up to the user of this macro to check signatures of wasm code to be executed
|
||||
/// and reject the code if any imported function has a mismatched signature.
|
||||
macro_rules! define_env {
|
||||
( $init_name:ident , < E: $ext_ty:tt > ,
|
||||
$( $name:ident ( $ctx:ident $( , $names:ident : $params:ty )* )
|
||||
$( -> $returns:ty )* => $body:tt , )*
|
||||
) => {
|
||||
pub struct $init_name;
|
||||
|
||||
impl $crate::wasm::env_def::ImportSatisfyCheck for $init_name {
|
||||
fn can_satisfy(name: &[u8], func_type: &parity_wasm::elements::FunctionType) -> bool {
|
||||
gen_signature_dispatch!( name, func_type ; $( $name ( $ctx $(, $names : $params )* ) $( -> $returns )* , )* );
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: Ext> $crate::wasm::env_def::FunctionImplProvider<E> for $init_name {
|
||||
fn impls<F: FnMut(&[u8], $crate::wasm::env_def::HostFunc<E>)>(f: &mut F) {
|
||||
register_func!(f, < E: $ext_ty > ; $( $name ( $ctx $( , $names : $params )* ) $( -> $returns)* => $body )* );
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use parity_wasm::elements::FunctionType;
|
||||
use parity_wasm::elements::ValueType;
|
||||
use sr_primitives::traits::Zero;
|
||||
use sandbox::{self, ReturnValue, TypedValue};
|
||||
use crate::wasm::tests::MockExt;
|
||||
use crate::wasm::Runtime;
|
||||
use crate::exec::Ext;
|
||||
use crate::gas::Gas;
|
||||
|
||||
#[test]
|
||||
fn macro_unmarshall_then_body_then_marshall_value_or_trap() {
|
||||
fn test_value(
|
||||
_ctx: &mut u32,
|
||||
args: &[sandbox::TypedValue],
|
||||
) -> Result<ReturnValue, sandbox::HostError> {
|
||||
let mut args = args.iter();
|
||||
unmarshall_then_body_then_marshall!(
|
||||
args,
|
||||
_ctx,
|
||||
(a: u32, b: u32) -> u32 => {
|
||||
if b == 0 {
|
||||
Err(sandbox::HostError)
|
||||
} else {
|
||||
Ok(a / b)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
let ctx = &mut 0;
|
||||
assert_eq!(
|
||||
test_value(ctx, &[TypedValue::I32(15), TypedValue::I32(3)]).unwrap(),
|
||||
ReturnValue::Value(TypedValue::I32(5)),
|
||||
);
|
||||
assert!(test_value(ctx, &[TypedValue::I32(15), TypedValue::I32(0)]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macro_unmarshall_then_body_then_marshall_unit() {
|
||||
fn test_unit(
|
||||
ctx: &mut u32,
|
||||
args: &[sandbox::TypedValue],
|
||||
) -> Result<ReturnValue, sandbox::HostError> {
|
||||
let mut args = args.iter();
|
||||
unmarshall_then_body_then_marshall!(
|
||||
args,
|
||||
ctx,
|
||||
(a: u32, b: u32) => {
|
||||
*ctx = a + b;
|
||||
Ok(())
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
let ctx = &mut 0;
|
||||
let result = test_unit(ctx, &[TypedValue::I32(2), TypedValue::I32(3)]).unwrap();
|
||||
assert_eq!(result, ReturnValue::Unit);
|
||||
assert_eq!(*ctx, 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macro_define_func() {
|
||||
define_func!( <E: Ext> ext_gas (_ctx, amount: u32) => {
|
||||
let amount = Gas::from(amount);
|
||||
if !amount.is_zero() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(sandbox::HostError)
|
||||
}
|
||||
});
|
||||
let _f: fn(&mut Runtime<MockExt>, &[sandbox::TypedValue])
|
||||
-> Result<sandbox::ReturnValue, sandbox::HostError> = ext_gas::<MockExt>;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macro_gen_signature() {
|
||||
assert_eq!(
|
||||
gen_signature!((i32)),
|
||||
FunctionType::new(vec![ValueType::I32], None),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
gen_signature!( (i32, u32) -> u32 ),
|
||||
FunctionType::new(vec![ValueType::I32, ValueType::I32], Some(ValueType::I32)),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macro_unmarshall_then_body() {
|
||||
let args = vec![TypedValue::I32(5), TypedValue::I32(3)];
|
||||
let mut args = args.iter();
|
||||
|
||||
let ctx: &mut u32 = &mut 0;
|
||||
|
||||
let r = unmarshall_then_body!(
|
||||
{
|
||||
*ctx = a + b;
|
||||
a * b
|
||||
},
|
||||
ctx,
|
||||
args,
|
||||
a: u32,
|
||||
b: u32
|
||||
);
|
||||
|
||||
assert_eq!(*ctx, 8);
|
||||
assert_eq!(r, 15);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macro_define_env() {
|
||||
use crate::wasm::env_def::ImportSatisfyCheck;
|
||||
|
||||
define_env!(Env, <E: Ext>,
|
||||
ext_gas( _ctx, amount: u32 ) => {
|
||||
let amount = Gas::from(amount);
|
||||
if !amount.is_zero() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(sandbox::HostError)
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
assert!(Env::can_satisfy(b"ext_gas", &FunctionType::new(vec![ValueType::I32], None)));
|
||||
assert!(!Env::can_satisfy(b"not_exists", &FunctionType::new(vec![], None)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// Copyright 2018-2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
use super::Runtime;
|
||||
use crate::exec::Ext;
|
||||
|
||||
use sandbox::{self, TypedValue};
|
||||
use parity_wasm::elements::{FunctionType, ValueType};
|
||||
|
||||
#[macro_use]
|
||||
pub(crate) mod macros;
|
||||
|
||||
pub trait ConvertibleToWasm: Sized {
|
||||
const VALUE_TYPE: ValueType;
|
||||
type NativeType;
|
||||
fn to_typed_value(self) -> TypedValue;
|
||||
fn from_typed_value(_: TypedValue) -> Option<Self>;
|
||||
}
|
||||
impl ConvertibleToWasm for i32 {
|
||||
type NativeType = i32;
|
||||
const VALUE_TYPE: ValueType = ValueType::I32;
|
||||
fn to_typed_value(self) -> TypedValue {
|
||||
TypedValue::I32(self)
|
||||
}
|
||||
fn from_typed_value(v: TypedValue) -> Option<Self> {
|
||||
v.as_i32()
|
||||
}
|
||||
}
|
||||
impl ConvertibleToWasm for u32 {
|
||||
type NativeType = u32;
|
||||
const VALUE_TYPE: ValueType = ValueType::I32;
|
||||
fn to_typed_value(self) -> TypedValue {
|
||||
TypedValue::I32(self as i32)
|
||||
}
|
||||
fn from_typed_value(v: TypedValue) -> Option<Self> {
|
||||
match v {
|
||||
TypedValue::I32(v) => Some(v as u32),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl ConvertibleToWasm for u64 {
|
||||
type NativeType = u64;
|
||||
const VALUE_TYPE: ValueType = ValueType::I64;
|
||||
fn to_typed_value(self) -> TypedValue {
|
||||
TypedValue::I64(self as i64)
|
||||
}
|
||||
fn from_typed_value(v: TypedValue) -> Option<Self> {
|
||||
match v {
|
||||
TypedValue::I64(v) => Some(v as u64),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) type HostFunc<E> =
|
||||
fn(
|
||||
&mut Runtime<E>,
|
||||
&[sandbox::TypedValue]
|
||||
) -> Result<sandbox::ReturnValue, sandbox::HostError>;
|
||||
|
||||
pub(crate) trait FunctionImplProvider<E: Ext> {
|
||||
fn impls<F: FnMut(&[u8], HostFunc<E>)>(f: &mut F);
|
||||
}
|
||||
|
||||
/// This trait can be used to check whether the host environment can satisfy
|
||||
/// a requested function import.
|
||||
pub trait ImportSatisfyCheck {
|
||||
/// Returns `true` if the host environment contains a function with
|
||||
/// the specified name and its type matches to the given type, or `false`
|
||||
/// otherwise.
|
||||
fn can_satisfy(name: &[u8], func_type: &FunctionType) -> bool;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,839 @@
|
||||
// Copyright 2018-2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! This module takes care of loading, checking and preprocessing of a
|
||||
//! wasm module before execution. It also extracts some essential information
|
||||
//! from a module.
|
||||
|
||||
use crate::wasm::env_def::ImportSatisfyCheck;
|
||||
use crate::wasm::PrefabWasmModule;
|
||||
use crate::Schedule;
|
||||
|
||||
use parity_wasm::elements::{self, Internal, External, MemoryType, Type, ValueType};
|
||||
use pwasm_utils;
|
||||
use pwasm_utils::rules;
|
||||
use rstd::prelude::*;
|
||||
use sr_primitives::traits::{SaturatedConversion};
|
||||
|
||||
struct ContractModule<'a> {
|
||||
/// A deserialized module. The module is valid (this is Guaranteed by `new` method).
|
||||
module: elements::Module,
|
||||
schedule: &'a Schedule,
|
||||
}
|
||||
|
||||
impl<'a> ContractModule<'a> {
|
||||
/// Creates a new instance of `ContractModule`.
|
||||
///
|
||||
/// Returns `Err` if the `original_code` couldn't be decoded or
|
||||
/// if it contains an invalid module.
|
||||
fn new(
|
||||
original_code: &[u8],
|
||||
schedule: &'a Schedule,
|
||||
) -> Result<Self, &'static str> {
|
||||
use wasmi_validation::{validate_module, PlainValidator};
|
||||
|
||||
let module =
|
||||
elements::deserialize_buffer(original_code).map_err(|_| "Can't decode wasm code")?;
|
||||
|
||||
// Make sure that the module is valid.
|
||||
validate_module::<PlainValidator>(&module).map_err(|_| "Module is not valid")?;
|
||||
|
||||
// Return a `ContractModule` instance with
|
||||
// __valid__ module.
|
||||
Ok(ContractModule {
|
||||
module,
|
||||
schedule,
|
||||
})
|
||||
}
|
||||
|
||||
/// Ensures that module doesn't declare internal memories.
|
||||
///
|
||||
/// In this runtime we only allow wasm module to import memory from the environment.
|
||||
/// Memory section contains declarations of internal linear memories, so if we find one
|
||||
/// we reject such a module.
|
||||
fn ensure_no_internal_memory(&self) -> Result<(), &'static str> {
|
||||
if self.module
|
||||
.memory_section()
|
||||
.map_or(false, |ms| ms.entries().len() > 0)
|
||||
{
|
||||
return Err("module declares internal memory");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Ensures that tables declared in the module are not too big.
|
||||
fn ensure_table_size_limit(&self, limit: u32) -> Result<(), &'static str> {
|
||||
if let Some(table_section) = self.module.table_section() {
|
||||
// In Wasm MVP spec, there may be at most one table declared. Double check this
|
||||
// explicitly just in case the Wasm version changes.
|
||||
if table_section.entries().len() > 1 {
|
||||
return Err("multiple tables declared");
|
||||
}
|
||||
if let Some(table_type) = table_section.entries().first() {
|
||||
// Check the table's initial size as there is no instruction or environment function
|
||||
// capable of growing the table.
|
||||
if table_type.limits().initial() > limit {
|
||||
return Err("table exceeds maximum size allowed")
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Ensures that no floating point types are in use.
|
||||
fn ensure_no_floating_types(&self) -> Result<(), &'static str> {
|
||||
if let Some(global_section) = self.module.global_section() {
|
||||
for global in global_section.entries() {
|
||||
match global.global_type().content_type() {
|
||||
ValueType::F32 | ValueType::F64 =>
|
||||
return Err("use of floating point type in globals is forbidden"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(code_section) = self.module.code_section() {
|
||||
for func_body in code_section.bodies() {
|
||||
for local in func_body.locals() {
|
||||
match local.value_type() {
|
||||
ValueType::F32 | ValueType::F64 =>
|
||||
return Err("use of floating point type in locals is forbidden"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(type_section) = self.module.type_section() {
|
||||
for wasm_type in type_section.types() {
|
||||
match wasm_type {
|
||||
Type::Function(func_type) => {
|
||||
let return_type = func_type.return_type();
|
||||
for value_type in func_type.params().iter().chain(return_type.iter()) {
|
||||
match value_type {
|
||||
ValueType::F32 | ValueType::F64 =>
|
||||
return Err("use of floating point type in function types is forbidden"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn inject_gas_metering(self) -> Result<Self, &'static str> {
|
||||
let gas_rules =
|
||||
rules::Set::new(
|
||||
self.schedule.regular_op_cost.clone().saturated_into(),
|
||||
Default::default(),
|
||||
)
|
||||
.with_grow_cost(self.schedule.grow_mem_cost.clone().saturated_into())
|
||||
.with_forbidden_floats();
|
||||
|
||||
let contract_module = pwasm_utils::inject_gas_counter(self.module, &gas_rules)
|
||||
.map_err(|_| "gas instrumentation failed")?;
|
||||
Ok(ContractModule {
|
||||
module: contract_module,
|
||||
schedule: self.schedule,
|
||||
})
|
||||
}
|
||||
|
||||
fn inject_stack_height_metering(self) -> Result<Self, &'static str> {
|
||||
let contract_module =
|
||||
pwasm_utils::stack_height::inject_limiter(self.module, self.schedule.max_stack_height)
|
||||
.map_err(|_| "stack height instrumentation failed")?;
|
||||
Ok(ContractModule {
|
||||
module: contract_module,
|
||||
schedule: self.schedule,
|
||||
})
|
||||
}
|
||||
|
||||
/// Check that the module has required exported functions. For now
|
||||
/// these are just entrypoints:
|
||||
///
|
||||
/// - 'call'
|
||||
/// - 'deploy'
|
||||
///
|
||||
/// Any other exports are not allowed.
|
||||
fn scan_exports(&self) -> Result<(), &'static str> {
|
||||
let mut deploy_found = false;
|
||||
let mut call_found = false;
|
||||
|
||||
let module = &self.module;
|
||||
|
||||
let types = module.type_section().map(|ts| ts.types()).unwrap_or(&[]);
|
||||
let export_entries = module
|
||||
.export_section()
|
||||
.map(|is| is.entries())
|
||||
.unwrap_or(&[]);
|
||||
let func_entries = module
|
||||
.function_section()
|
||||
.map(|fs| fs.entries())
|
||||
.unwrap_or(&[]);
|
||||
|
||||
// Function index space consists of imported function following by
|
||||
// declared functions. Calculate the total number of imported functions so
|
||||
// we can use it to convert indexes from function space to declared function space.
|
||||
let fn_space_offset = module
|
||||
.import_section()
|
||||
.map(|is| is.entries())
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.filter(|entry| {
|
||||
match *entry.external() {
|
||||
External::Function(_) => true,
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
.count();
|
||||
|
||||
for export in export_entries {
|
||||
match export.field() {
|
||||
"call" => call_found = true,
|
||||
"deploy" => deploy_found = true,
|
||||
_ => return Err("unknown export: expecting only deploy and call functions"),
|
||||
}
|
||||
|
||||
// Then check the export kind. "call" and "deploy" are
|
||||
// functions.
|
||||
let fn_idx = match export.internal() {
|
||||
Internal::Function(ref fn_idx) => *fn_idx,
|
||||
_ => return Err("expected a function"),
|
||||
};
|
||||
|
||||
// convert index from function index space to declared index space.
|
||||
let fn_idx = match fn_idx.checked_sub(fn_space_offset as u32) {
|
||||
Some(fn_idx) => fn_idx,
|
||||
None => {
|
||||
// Underflow here means fn_idx points to imported function which we don't allow!
|
||||
return Err("entry point points to an imported function");
|
||||
}
|
||||
};
|
||||
|
||||
// Then check the signature.
|
||||
// Both "call" and "deploy" has a [] -> [] or [] -> [i32] function type.
|
||||
//
|
||||
// The [] -> [] signature predates the [] -> [i32] signature and is supported for
|
||||
// backwards compatibility. This will likely be removed once ink! is updated to
|
||||
// generate modules with the new function signatures.
|
||||
let func_ty_idx = func_entries.get(fn_idx as usize)
|
||||
.ok_or_else(|| "export refers to non-existent function")?
|
||||
.type_ref();
|
||||
let Type::Function(ref func_ty) = types
|
||||
.get(func_ty_idx as usize)
|
||||
.ok_or_else(|| "function has a non-existent type")?;
|
||||
if !func_ty.params().is_empty() ||
|
||||
!(func_ty.return_type().is_none() ||
|
||||
func_ty.return_type() == Some(ValueType::I32)) {
|
||||
return Err("entry point has wrong signature");
|
||||
}
|
||||
}
|
||||
|
||||
if !deploy_found {
|
||||
return Err("deploy function isn't exported");
|
||||
}
|
||||
if !call_found {
|
||||
return Err("call function isn't exported");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Scan an import section if any.
|
||||
///
|
||||
/// This accomplishes two tasks:
|
||||
///
|
||||
/// - checks any imported function against defined host functions set, incl.
|
||||
/// their signatures.
|
||||
/// - if there is a memory import, returns it's descriptor
|
||||
fn scan_imports<C: ImportSatisfyCheck>(&self) -> Result<Option<&MemoryType>, &'static str> {
|
||||
let module = &self.module;
|
||||
|
||||
let types = module.type_section().map(|ts| ts.types()).unwrap_or(&[]);
|
||||
let import_entries = module
|
||||
.import_section()
|
||||
.map(|is| is.entries())
|
||||
.unwrap_or(&[]);
|
||||
|
||||
let mut imported_mem_type = None;
|
||||
|
||||
for import in import_entries {
|
||||
if import.module() != "env" {
|
||||
// This import tries to import something from non-"env" module,
|
||||
// but all imports are located in "env" at the moment.
|
||||
return Err("module has imports from a non-'env' namespace");
|
||||
}
|
||||
|
||||
let type_idx = match import.external() {
|
||||
&External::Table(_) => return Err("Cannot import tables"),
|
||||
&External::Global(_) => return Err("Cannot import globals"),
|
||||
&External::Function(ref type_idx) => type_idx,
|
||||
&External::Memory(ref memory_type) => {
|
||||
if import.field() != "memory" {
|
||||
return Err("Memory import must have the field name 'memory'")
|
||||
}
|
||||
if imported_mem_type.is_some() {
|
||||
return Err("Multiple memory imports defined")
|
||||
}
|
||||
imported_mem_type = Some(memory_type);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let Type::Function(ref func_ty) = types
|
||||
.get(*type_idx as usize)
|
||||
.ok_or_else(|| "validation: import entry points to a non-existent type")?;
|
||||
|
||||
// We disallow importing `ext_println` unless debug features are enabled,
|
||||
// which should only be allowed on a dev chain
|
||||
if !self.schedule.enable_println && import.field().as_bytes() == b"ext_println" {
|
||||
return Err("module imports `ext_println` but debug features disabled");
|
||||
}
|
||||
|
||||
// We disallow importing `gas` function here since it is treated as implementation detail.
|
||||
if import.field().as_bytes() == b"gas"
|
||||
|| !C::can_satisfy(import.field().as_bytes(), func_ty)
|
||||
{
|
||||
return Err("module imports a non-existent function");
|
||||
}
|
||||
}
|
||||
Ok(imported_mem_type)
|
||||
}
|
||||
|
||||
fn into_wasm_code(self) -> Result<Vec<u8>, &'static str> {
|
||||
elements::serialize(self.module)
|
||||
.map_err(|_| "error serializing instrumented module")
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads the given module given in `original_code`, performs some checks on it and
|
||||
/// does some preprocessing.
|
||||
///
|
||||
/// The checks are:
|
||||
///
|
||||
/// - provided code is a valid wasm module.
|
||||
/// - the module doesn't define an internal memory instance,
|
||||
/// - imported memory (if any) doesn't reserve more memory than permitted by the `schedule`,
|
||||
/// - all imported functions from the external environment matches defined by `env` module,
|
||||
///
|
||||
/// The preprocessing includes injecting code for gas metering and metering the height of stack.
|
||||
pub fn prepare_contract<C: ImportSatisfyCheck>(
|
||||
original_code: &[u8],
|
||||
schedule: &Schedule,
|
||||
) -> Result<PrefabWasmModule, &'static str> {
|
||||
let mut contract_module = ContractModule::new(original_code, schedule)?;
|
||||
contract_module.scan_exports()?;
|
||||
contract_module.ensure_no_internal_memory()?;
|
||||
contract_module.ensure_table_size_limit(schedule.max_table_size)?;
|
||||
contract_module.ensure_no_floating_types()?;
|
||||
|
||||
struct MemoryDefinition {
|
||||
initial: u32,
|
||||
maximum: u32,
|
||||
}
|
||||
|
||||
let memory_def = if let Some(memory_type) = contract_module.scan_imports::<C>()? {
|
||||
// Inspect the module to extract the initial and maximum page count.
|
||||
let limits = memory_type.limits();
|
||||
match (limits.initial(), limits.maximum()) {
|
||||
(initial, Some(maximum)) if initial > maximum => {
|
||||
return Err(
|
||||
"Requested initial number of pages should not exceed the requested maximum",
|
||||
);
|
||||
}
|
||||
(_, Some(maximum)) if maximum > schedule.max_memory_pages => {
|
||||
return Err("Maximum number of pages should not exceed the configured maximum.");
|
||||
}
|
||||
(initial, Some(maximum)) => MemoryDefinition { initial, maximum },
|
||||
(_, None) => {
|
||||
// Maximum number of pages should be always declared.
|
||||
// This isn't a hard requirement and can be treated as a maximum set
|
||||
// to configured maximum.
|
||||
return Err("Maximum number of pages should be always declared.");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// If none memory imported then just crate an empty placeholder.
|
||||
// Any access to it will lead to out of bounds trap.
|
||||
MemoryDefinition {
|
||||
initial: 0,
|
||||
maximum: 0,
|
||||
}
|
||||
};
|
||||
|
||||
contract_module = contract_module
|
||||
.inject_gas_metering()?
|
||||
.inject_stack_height_metering()?;
|
||||
|
||||
Ok(PrefabWasmModule {
|
||||
schedule_version: schedule.version,
|
||||
initial: memory_def.initial,
|
||||
maximum: memory_def.maximum,
|
||||
_reserved: None,
|
||||
code: contract_module.into_wasm_code()?,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::exec::Ext;
|
||||
use std::fmt;
|
||||
use wabt;
|
||||
use assert_matches::assert_matches;
|
||||
|
||||
impl fmt::Debug for PrefabWasmModule {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "PreparedContract {{ .. }}")
|
||||
}
|
||||
}
|
||||
|
||||
// Define test environment for tests. We need ImportSatisfyCheck
|
||||
// implementation from it. So actual implementations doesn't matter.
|
||||
define_env!(TestEnv, <E: Ext>,
|
||||
panic(_ctx) => { unreachable!(); },
|
||||
|
||||
// gas is an implementation defined function and a contract can't import it.
|
||||
gas(_ctx, _amount: u32) => { unreachable!(); },
|
||||
|
||||
nop(_ctx, _unused: u64) => { unreachable!(); },
|
||||
|
||||
ext_println(_ctx, _ptr: u32, _len: u32) => { unreachable!(); },
|
||||
);
|
||||
|
||||
macro_rules! prepare_test {
|
||||
($name:ident, $wat:expr, $($expected:tt)*) => {
|
||||
#[test]
|
||||
fn $name() {
|
||||
let wasm = wabt::Wat2Wasm::new().validate(false).convert($wat).unwrap();
|
||||
let schedule = Schedule::default();
|
||||
let r = prepare_contract::<TestEnv>(wasm.as_ref(), &schedule);
|
||||
assert_matches!(r, $($expected)*);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
prepare_test!(no_floats,
|
||||
r#"
|
||||
(module
|
||||
(func (export "call")
|
||||
(drop
|
||||
(f32.add
|
||||
(f32.const 0)
|
||||
(f32.const 1)
|
||||
)
|
||||
)
|
||||
)
|
||||
(func (export "deploy"))
|
||||
)"#,
|
||||
Err("gas instrumentation failed")
|
||||
);
|
||||
|
||||
mod memories {
|
||||
use super::*;
|
||||
|
||||
// Tests below assumes that maximum page number is configured to a certain number.
|
||||
#[test]
|
||||
fn assume_memory_size() {
|
||||
assert_eq!(Schedule::default().max_memory_pages, 16);
|
||||
}
|
||||
|
||||
prepare_test!(memory_with_one_page,
|
||||
r#"
|
||||
(module
|
||||
(import "env" "memory" (memory 1 1))
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Ok(_)
|
||||
);
|
||||
|
||||
prepare_test!(internal_memory_declaration,
|
||||
r#"
|
||||
(module
|
||||
(memory 1 1)
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("module declares internal memory")
|
||||
);
|
||||
|
||||
prepare_test!(no_memory_import,
|
||||
r#"
|
||||
(module
|
||||
;; no memory imported
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)"#,
|
||||
Ok(_)
|
||||
);
|
||||
|
||||
prepare_test!(initial_exceeds_maximum,
|
||||
r#"
|
||||
(module
|
||||
(import "env" "memory" (memory 16 1))
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("Module is not valid")
|
||||
);
|
||||
|
||||
prepare_test!(no_maximum,
|
||||
r#"
|
||||
(module
|
||||
(import "env" "memory" (memory 1))
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("Maximum number of pages should be always declared.")
|
||||
);
|
||||
|
||||
prepare_test!(requested_maximum_exceeds_configured_maximum,
|
||||
r#"
|
||||
(module
|
||||
(import "env" "memory" (memory 1 17))
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("Maximum number of pages should not exceed the configured maximum.")
|
||||
);
|
||||
|
||||
prepare_test!(field_name_not_memory,
|
||||
r#"
|
||||
(module
|
||||
(import "env" "forgetit" (memory 1 1))
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("Memory import must have the field name 'memory'")
|
||||
);
|
||||
|
||||
prepare_test!(multiple_memory_imports,
|
||||
r#"
|
||||
(module
|
||||
(import "env" "memory" (memory 1 1))
|
||||
(import "env" "memory" (memory 1 1))
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("Module is not valid")
|
||||
);
|
||||
|
||||
prepare_test!(table_import,
|
||||
r#"
|
||||
(module
|
||||
(import "env" "table" (table 1 anyfunc))
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("Cannot import tables")
|
||||
);
|
||||
|
||||
prepare_test!(global_import,
|
||||
r#"
|
||||
(module
|
||||
(global $g (import "env" "global") i32)
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("Cannot import globals")
|
||||
);
|
||||
}
|
||||
|
||||
mod tables {
|
||||
use super::*;
|
||||
|
||||
// Tests below assumes that maximum table size is configured to a certain number.
|
||||
#[test]
|
||||
fn assume_table_size() {
|
||||
assert_eq!(Schedule::default().max_table_size, 16384);
|
||||
}
|
||||
|
||||
prepare_test!(no_tables,
|
||||
r#"
|
||||
(module
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Ok(_)
|
||||
);
|
||||
|
||||
prepare_test!(table_valid_size,
|
||||
r#"
|
||||
(module
|
||||
(table 10000 funcref)
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Ok(_)
|
||||
);
|
||||
|
||||
prepare_test!(table_too_big,
|
||||
r#"
|
||||
(module
|
||||
(table 20000 funcref)
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)"#,
|
||||
Err("table exceeds maximum size allowed")
|
||||
);
|
||||
}
|
||||
|
||||
mod imports {
|
||||
use super::*;
|
||||
|
||||
prepare_test!(can_import_legit_function,
|
||||
r#"
|
||||
(module
|
||||
(import "env" "nop" (func (param i64)))
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Ok(_)
|
||||
);
|
||||
|
||||
// even though gas is defined the contract can't import it since
|
||||
// it is an implementation defined.
|
||||
prepare_test!(can_not_import_gas_function,
|
||||
r#"
|
||||
(module
|
||||
(import "env" "gas" (func (param i32)))
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("module imports a non-existent function")
|
||||
);
|
||||
|
||||
// nothing can be imported from non-"env" module for now.
|
||||
prepare_test!(non_env_import,
|
||||
r#"
|
||||
(module
|
||||
(import "another_module" "memory" (memory 1 1))
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("module has imports from a non-'env' namespace")
|
||||
);
|
||||
|
||||
// wrong signature
|
||||
prepare_test!(wrong_signature,
|
||||
r#"
|
||||
(module
|
||||
(import "env" "gas" (func (param i64)))
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("module imports a non-existent function")
|
||||
);
|
||||
|
||||
prepare_test!(unknown_func_name,
|
||||
r#"
|
||||
(module
|
||||
(import "env" "unknown_func" (func))
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("module imports a non-existent function")
|
||||
);
|
||||
|
||||
prepare_test!(ext_println_debug_disabled,
|
||||
r#"
|
||||
(module
|
||||
(import "env" "ext_println" (func $ext_println (param i32 i32)))
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("module imports `ext_println` but debug features disabled")
|
||||
);
|
||||
|
||||
#[test]
|
||||
fn ext_println_debug_enabled() {
|
||||
let wasm = wabt::Wat2Wasm::new().validate(false).convert(
|
||||
r#"
|
||||
(module
|
||||
(import "env" "ext_println" (func $ext_println (param i32 i32)))
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#
|
||||
).unwrap();
|
||||
let mut schedule = Schedule::default();
|
||||
schedule.enable_println = true;
|
||||
let r = prepare_contract::<TestEnv>(wasm.as_ref(), &schedule);
|
||||
assert_matches!(r, Ok(_));
|
||||
}
|
||||
}
|
||||
|
||||
mod entrypoints {
|
||||
use super::*;
|
||||
|
||||
prepare_test!(it_works,
|
||||
r#"
|
||||
(module
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Ok(_)
|
||||
);
|
||||
|
||||
prepare_test!(omit_deploy,
|
||||
r#"
|
||||
(module
|
||||
(func (export "call"))
|
||||
)
|
||||
"#,
|
||||
Err("deploy function isn't exported")
|
||||
);
|
||||
|
||||
prepare_test!(omit_call,
|
||||
r#"
|
||||
(module
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("call function isn't exported")
|
||||
);
|
||||
|
||||
// Try to use imported function as an entry point.
|
||||
prepare_test!(try_sneak_export_as_entrypoint,
|
||||
r#"
|
||||
(module
|
||||
(import "env" "panic" (func))
|
||||
|
||||
(func (export "deploy"))
|
||||
|
||||
(export "call" (func 0))
|
||||
)
|
||||
"#,
|
||||
Err("entry point points to an imported function")
|
||||
);
|
||||
|
||||
// Try to use imported function as an entry point.
|
||||
prepare_test!(try_sneak_export_as_global,
|
||||
r#"
|
||||
(module
|
||||
(func (export "deploy"))
|
||||
(global (export "call") i32 (i32.const 0))
|
||||
)
|
||||
"#,
|
||||
Err("expected a function")
|
||||
);
|
||||
|
||||
prepare_test!(wrong_signature,
|
||||
r#"
|
||||
(module
|
||||
(func (export "deploy"))
|
||||
(func (export "call") (param i32))
|
||||
)
|
||||
"#,
|
||||
Err("entry point has wrong signature")
|
||||
);
|
||||
|
||||
prepare_test!(unknown_exports,
|
||||
r#"
|
||||
(module
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
(func (export "whatevs"))
|
||||
)
|
||||
"#,
|
||||
Err("unknown export: expecting only deploy and call functions")
|
||||
);
|
||||
|
||||
prepare_test!(global_float,
|
||||
r#"
|
||||
(module
|
||||
(global $x f32 (f32.const 0))
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("use of floating point type in globals is forbidden")
|
||||
);
|
||||
|
||||
prepare_test!(local_float,
|
||||
r#"
|
||||
(module
|
||||
(func $foo (local f32))
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("use of floating point type in locals is forbidden")
|
||||
);
|
||||
|
||||
prepare_test!(param_float,
|
||||
r#"
|
||||
(module
|
||||
(func $foo (param f32))
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("use of floating point type in function types is forbidden")
|
||||
);
|
||||
|
||||
prepare_test!(result_float,
|
||||
r#"
|
||||
(module
|
||||
(func $foo (result f32) (f32.const 0))
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("use of floating point type in function types is forbidden")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,882 @@
|
||||
// Copyright 2018-2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Environment definition of the wasm smart-contract runtime.
|
||||
|
||||
use crate::{Schedule, Trait, CodeHash, ComputeDispatchFee, BalanceOf};
|
||||
use crate::exec::{
|
||||
Ext, ExecResult, ExecError, ExecReturnValue, StorageKey, TopicOf, STATUS_SUCCESS,
|
||||
};
|
||||
use crate::gas::{Gas, GasMeter, Token, GasMeterResult, approx_gas_for_balance};
|
||||
use sandbox;
|
||||
use system;
|
||||
use rstd::prelude::*;
|
||||
use rstd::convert::TryInto;
|
||||
use rstd::mem;
|
||||
use codec::{Decode, Encode};
|
||||
use sr_primitives::traits::{Bounded, SaturatedConversion};
|
||||
|
||||
/// The value returned from ext_call and ext_instantiate contract external functions if the call or
|
||||
/// instantiation traps. This value is chosen as if the execution does not trap, the return value
|
||||
/// will always be an 8-bit integer, so 0x0100 is the smallest value that could not be returned.
|
||||
const TRAP_RETURN_CODE: u32 = 0x0100;
|
||||
|
||||
/// Enumerates all possible *special* trap conditions.
|
||||
///
|
||||
/// In this runtime traps used not only for signaling about errors but also
|
||||
/// to just terminate quickly in some cases.
|
||||
enum SpecialTrap {
|
||||
/// Signals that trap was generated in response to call `ext_return` host function.
|
||||
Return(Vec<u8>),
|
||||
}
|
||||
|
||||
/// Can only be used for one call.
|
||||
pub(crate) struct Runtime<'a, E: Ext + 'a> {
|
||||
ext: &'a mut E,
|
||||
scratch_buf: Vec<u8>,
|
||||
schedule: &'a Schedule,
|
||||
memory: sandbox::Memory,
|
||||
gas_meter: &'a mut GasMeter<E::T>,
|
||||
special_trap: Option<SpecialTrap>,
|
||||
}
|
||||
impl<'a, E: Ext + 'a> Runtime<'a, E> {
|
||||
pub(crate) fn new(
|
||||
ext: &'a mut E,
|
||||
input_data: Vec<u8>,
|
||||
schedule: &'a Schedule,
|
||||
memory: sandbox::Memory,
|
||||
gas_meter: &'a mut GasMeter<E::T>,
|
||||
) -> Self {
|
||||
Runtime {
|
||||
ext,
|
||||
// Put the input data into the scratch buffer immediately.
|
||||
scratch_buf: input_data,
|
||||
schedule,
|
||||
memory,
|
||||
gas_meter,
|
||||
special_trap: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn to_execution_result<E: Ext>(
|
||||
runtime: Runtime<E>,
|
||||
sandbox_result: Result<sandbox::ReturnValue, sandbox::Error>,
|
||||
) -> ExecResult {
|
||||
// Special case. The trap was the result of the execution `return` host function.
|
||||
if let Some(SpecialTrap::Return(data)) = runtime.special_trap {
|
||||
return Ok(ExecReturnValue { status: STATUS_SUCCESS, data });
|
||||
}
|
||||
|
||||
// Check the exact type of the error.
|
||||
match sandbox_result {
|
||||
// No traps were generated. Proceed normally.
|
||||
Ok(sandbox::ReturnValue::Unit) => {
|
||||
let mut buffer = runtime.scratch_buf;
|
||||
buffer.clear();
|
||||
Ok(ExecReturnValue { status: STATUS_SUCCESS, data: buffer })
|
||||
}
|
||||
Ok(sandbox::ReturnValue::Value(sandbox::TypedValue::I32(exit_code))) => {
|
||||
let status = (exit_code & 0xFF).try_into()
|
||||
.expect("exit_code is masked into the range of a u8; qed");
|
||||
Ok(ExecReturnValue { status, data: runtime.scratch_buf })
|
||||
}
|
||||
// This should never happen as the return type of exported functions should have been
|
||||
// validated by the code preparation process. However, because panics are really
|
||||
// undesirable in the runtime code, we treat this as a trap for now. Eventually, we might
|
||||
// want to revisit this.
|
||||
Ok(_) => Err(ExecError { reason: "return type error", buffer: runtime.scratch_buf }),
|
||||
// `Error::Module` is returned only if instantiation or linking failed (i.e.
|
||||
// wasm binary tried to import a function that is not provided by the host).
|
||||
// This shouldn't happen because validation process ought to reject such binaries.
|
||||
//
|
||||
// Because panics are really undesirable in the runtime code, we treat this as
|
||||
// a trap for now. Eventually, we might want to revisit this.
|
||||
Err(sandbox::Error::Module) =>
|
||||
Err(ExecError { reason: "validation error", buffer: runtime.scratch_buf }),
|
||||
// Any other kind of a trap should result in a failure.
|
||||
Err(sandbox::Error::Execution) | Err(sandbox::Error::OutOfBounds) =>
|
||||
Err(ExecError { reason: "during execution", buffer: runtime.scratch_buf }),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
|
||||
#[derive(Copy, Clone)]
|
||||
pub enum RuntimeToken {
|
||||
/// Explicit call to the `gas` function. Charge the gas meter
|
||||
/// with the value provided.
|
||||
Explicit(u32),
|
||||
/// The given number of bytes is read from the sandbox memory.
|
||||
ReadMemory(u32),
|
||||
/// The given number of bytes is written to the sandbox memory.
|
||||
WriteMemory(u32),
|
||||
/// The given number of bytes is read from the sandbox memory and
|
||||
/// is returned as the return data buffer of the call.
|
||||
ReturnData(u32),
|
||||
/// Dispatch fee calculated by `T::ComputeDispatchFee`.
|
||||
ComputedDispatchFee(Gas),
|
||||
/// (topic_count, data_bytes): A buffer of the given size is posted as an event indexed with the
|
||||
/// given number of topics.
|
||||
DepositEvent(u32, u32),
|
||||
}
|
||||
|
||||
impl<T: Trait> Token<T> for RuntimeToken {
|
||||
type Metadata = Schedule;
|
||||
|
||||
fn calculate_amount(&self, metadata: &Schedule) -> Gas {
|
||||
use self::RuntimeToken::*;
|
||||
let value = match *self {
|
||||
Explicit(amount) => Some(amount.into()),
|
||||
ReadMemory(byte_count) => metadata
|
||||
.sandbox_data_read_cost
|
||||
.checked_mul(byte_count.into()),
|
||||
WriteMemory(byte_count) => metadata
|
||||
.sandbox_data_write_cost
|
||||
.checked_mul(byte_count.into()),
|
||||
ReturnData(byte_count) => metadata
|
||||
.return_data_per_byte_cost
|
||||
.checked_mul(byte_count.into()),
|
||||
DepositEvent(topic_count, data_byte_count) => {
|
||||
let data_cost = metadata
|
||||
.event_data_per_byte_cost
|
||||
.checked_mul(data_byte_count.into());
|
||||
|
||||
let topics_cost = metadata
|
||||
.event_per_topic_cost
|
||||
.checked_mul(topic_count.into());
|
||||
|
||||
data_cost
|
||||
.and_then(|data_cost| {
|
||||
topics_cost.and_then(|topics_cost| {
|
||||
data_cost.checked_add(topics_cost)
|
||||
})
|
||||
})
|
||||
.and_then(|data_and_topics_cost|
|
||||
data_and_topics_cost.checked_add(metadata.event_base_cost)
|
||||
)
|
||||
},
|
||||
ComputedDispatchFee(gas) => Some(gas),
|
||||
};
|
||||
|
||||
value.unwrap_or_else(|| Bounded::max_value())
|
||||
}
|
||||
}
|
||||
|
||||
/// Charge the gas meter with the specified token.
|
||||
///
|
||||
/// Returns `Err(HostError)` if there is not enough gas.
|
||||
fn charge_gas<T: Trait, Tok: Token<T>>(
|
||||
gas_meter: &mut GasMeter<T>,
|
||||
metadata: &Tok::Metadata,
|
||||
token: Tok,
|
||||
) -> Result<(), sandbox::HostError> {
|
||||
match gas_meter.charge(metadata, token) {
|
||||
GasMeterResult::Proceed => Ok(()),
|
||||
GasMeterResult::OutOfGas => Err(sandbox::HostError),
|
||||
}
|
||||
}
|
||||
|
||||
/// Read designated chunk from the sandbox memory, consuming an appropriate amount of
|
||||
/// gas.
|
||||
///
|
||||
/// Returns `Err` if one of the following conditions occurs:
|
||||
///
|
||||
/// - calculating the gas cost resulted in overflow.
|
||||
/// - out of gas
|
||||
/// - requested buffer is not within the bounds of the sandbox memory.
|
||||
fn read_sandbox_memory<E: Ext>(
|
||||
ctx: &mut Runtime<E>,
|
||||
ptr: u32,
|
||||
len: u32,
|
||||
) -> Result<Vec<u8>, sandbox::HostError> {
|
||||
charge_gas(ctx.gas_meter, ctx.schedule, RuntimeToken::ReadMemory(len))?;
|
||||
|
||||
let mut buf = vec![0u8; len as usize];
|
||||
ctx.memory.get(ptr, buf.as_mut_slice()).map_err(|_| sandbox::HostError)?;
|
||||
Ok(buf)
|
||||
}
|
||||
|
||||
/// Read designated chunk from the sandbox memory into the scratch buffer, consuming an
|
||||
/// appropriate amount of gas. Resizes the scratch buffer to the specified length on success.
|
||||
///
|
||||
/// Returns `Err` if one of the following conditions occurs:
|
||||
///
|
||||
/// - calculating the gas cost resulted in overflow.
|
||||
/// - out of gas
|
||||
/// - requested buffer is not within the bounds of the sandbox memory.
|
||||
fn read_sandbox_memory_into_scratch<E: Ext>(
|
||||
ctx: &mut Runtime<E>,
|
||||
ptr: u32,
|
||||
len: u32,
|
||||
) -> Result<(), sandbox::HostError> {
|
||||
charge_gas(ctx.gas_meter, ctx.schedule, RuntimeToken::ReadMemory(len))?;
|
||||
|
||||
ctx.scratch_buf.resize(len as usize, 0);
|
||||
ctx.memory.get(ptr, ctx.scratch_buf.as_mut_slice()).map_err(|_| sandbox::HostError)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read designated chunk from the sandbox memory into the supplied buffer, consuming
|
||||
/// an appropriate amount of gas.
|
||||
///
|
||||
/// Returns `Err` if one of the following conditions occurs:
|
||||
///
|
||||
/// - calculating the gas cost resulted in overflow.
|
||||
/// - out of gas
|
||||
/// - requested buffer is not within the bounds of the sandbox memory.
|
||||
fn read_sandbox_memory_into_buf<E: Ext>(
|
||||
ctx: &mut Runtime<E>,
|
||||
ptr: u32,
|
||||
buf: &mut [u8],
|
||||
) -> Result<(), sandbox::HostError> {
|
||||
charge_gas(ctx.gas_meter, ctx.schedule, RuntimeToken::ReadMemory(buf.len() as u32))?;
|
||||
|
||||
ctx.memory.get(ptr, buf).map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Read designated chunk from the sandbox memory, consuming an appropriate amount of
|
||||
/// gas, and attempt to decode into the specified type.
|
||||
///
|
||||
/// Returns `Err` if one of the following conditions occurs:
|
||||
///
|
||||
/// - calculating the gas cost resulted in overflow.
|
||||
/// - out of gas
|
||||
/// - requested buffer is not within the bounds of the sandbox memory.
|
||||
/// - the buffer contents cannot be decoded as the required type.
|
||||
fn read_sandbox_memory_as<E: Ext, D: Decode>(
|
||||
ctx: &mut Runtime<E>,
|
||||
ptr: u32,
|
||||
len: u32,
|
||||
) -> Result<D, sandbox::HostError> {
|
||||
let buf = read_sandbox_memory(ctx, ptr, len)?;
|
||||
D::decode(&mut &buf[..]).map_err(|_| sandbox::HostError)
|
||||
}
|
||||
|
||||
/// Write the given buffer to the designated location in the sandbox memory, consuming
|
||||
/// an appropriate amount of gas.
|
||||
///
|
||||
/// Returns `Err` if one of the following conditions occurs:
|
||||
///
|
||||
/// - calculating the gas cost resulted in overflow.
|
||||
/// - out of gas
|
||||
/// - designated area is not within the bounds of the sandbox memory.
|
||||
fn write_sandbox_memory<T: Trait>(
|
||||
schedule: &Schedule,
|
||||
gas_meter: &mut GasMeter<T>,
|
||||
memory: &sandbox::Memory,
|
||||
ptr: u32,
|
||||
buf: &[u8],
|
||||
) -> Result<(), sandbox::HostError> {
|
||||
charge_gas(gas_meter, schedule, RuntimeToken::WriteMemory(buf.len() as u32))?;
|
||||
|
||||
memory.set(ptr, buf)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ***********************************************************
|
||||
// * AFTER MAKING A CHANGE MAKE SURE TO UPDATE COMPLEXITY.MD *
|
||||
// ***********************************************************
|
||||
|
||||
// Define a function `fn init_env<E: Ext>() -> HostFunctionSet<E>` that returns
|
||||
// a function set which can be imported by an executed contract.
|
||||
define_env!(Env, <E: Ext>,
|
||||
|
||||
// Account for used gas. Traps if gas used is greater than gas limit.
|
||||
//
|
||||
// NOTE: This is a implementation defined call and is NOT a part of the public API.
|
||||
// This call is supposed to be called only by instrumentation injected code.
|
||||
//
|
||||
// - amount: How much gas is used.
|
||||
gas(ctx, amount: u32) => {
|
||||
charge_gas(&mut ctx.gas_meter, ctx.schedule, RuntimeToken::Explicit(amount))?;
|
||||
Ok(())
|
||||
},
|
||||
|
||||
// Change the value at the given key in the storage or remove the entry.
|
||||
// The value length must not exceed the maximum defined by the Contracts module parameters.
|
||||
//
|
||||
// - key_ptr: pointer into the linear
|
||||
// memory where the location of the requested value is placed.
|
||||
// - value_non_null: if set to 0, then the entry
|
||||
// at the given location will be removed.
|
||||
// - value_ptr: pointer into the linear memory
|
||||
// where the value to set is placed. If `value_non_null` is set to 0, then this parameter is ignored.
|
||||
// - value_len: the length of the value. If `value_non_null` is set to 0, then this parameter is ignored.
|
||||
ext_set_storage(ctx, key_ptr: u32, value_non_null: u32, value_ptr: u32, value_len: u32) => {
|
||||
if value_non_null != 0 && ctx.ext.max_value_size() < value_len {
|
||||
return Err(sandbox::HostError);
|
||||
}
|
||||
let mut key: StorageKey = [0; 32];
|
||||
read_sandbox_memory_into_buf(ctx, key_ptr, &mut key)?;
|
||||
let value =
|
||||
if value_non_null != 0 {
|
||||
Some(read_sandbox_memory(ctx, value_ptr, value_len)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
ctx.ext.set_storage(key, value).map_err(|_| sandbox::HostError)?;
|
||||
|
||||
Ok(())
|
||||
},
|
||||
|
||||
// Retrieve the value under the given key from the storage and return 0.
|
||||
// If there is no entry under the given key then this function will return 1 and
|
||||
// clear the scratch buffer.
|
||||
//
|
||||
// - key_ptr: pointer into the linear memory where the key
|
||||
// of the requested value is placed.
|
||||
ext_get_storage(ctx, key_ptr: u32) -> u32 => {
|
||||
let mut key: StorageKey = [0; 32];
|
||||
read_sandbox_memory_into_buf(ctx, key_ptr, &mut key)?;
|
||||
if let Some(value) = ctx.ext.get_storage(&key) {
|
||||
ctx.scratch_buf = value;
|
||||
Ok(0)
|
||||
} else {
|
||||
ctx.scratch_buf.clear();
|
||||
Ok(1)
|
||||
}
|
||||
},
|
||||
|
||||
// Make a call to another contract.
|
||||
//
|
||||
// If the called contract runs to completion, then this returns the status code the callee
|
||||
// returns on exit in the bottom 8 bits of the return value. The top 24 bits are 0s. A status
|
||||
// code of 0 indicates success, and any other code indicates a failure. On failure, any state
|
||||
// changes made by the called contract are reverted. The scratch buffer is filled with the
|
||||
// output data returned by the called contract, even in the case of a failure status.
|
||||
//
|
||||
// If the contract traps during execution or otherwise fails to complete successfully, then
|
||||
// this function clears the scratch buffer and returns 0x0100. As with a failure status, any
|
||||
// state changes made by the called contract are reverted.
|
||||
//
|
||||
// - callee_ptr: a pointer to the address of the callee contract.
|
||||
// Should be decodable as an `T::AccountId`. Traps otherwise.
|
||||
// - callee_len: length of the address buffer.
|
||||
// - gas: how much gas to devote to the execution.
|
||||
// - value_ptr: a pointer to the buffer with value, how much value to send.
|
||||
// Should be decodable as a `T::Balance`. Traps otherwise.
|
||||
// - value_len: length of the value buffer.
|
||||
// - input_data_ptr: a pointer to a buffer to be used as input data to the callee.
|
||||
// - input_data_len: length of the input data buffer.
|
||||
ext_call(
|
||||
ctx,
|
||||
callee_ptr: u32,
|
||||
callee_len: u32,
|
||||
gas: u64,
|
||||
value_ptr: u32,
|
||||
value_len: u32,
|
||||
input_data_ptr: u32,
|
||||
input_data_len: u32
|
||||
) -> u32 => {
|
||||
let callee: <<E as Ext>::T as system::Trait>::AccountId =
|
||||
read_sandbox_memory_as(ctx, callee_ptr, callee_len)?;
|
||||
let value: BalanceOf<<E as Ext>::T> =
|
||||
read_sandbox_memory_as(ctx, value_ptr, value_len)?;
|
||||
|
||||
// Read input data into the scratch buffer, then take ownership of it.
|
||||
read_sandbox_memory_into_scratch(ctx, input_data_ptr, input_data_len)?;
|
||||
let input_data = mem::replace(&mut ctx.scratch_buf, Vec::new());
|
||||
|
||||
let nested_gas_limit = if gas == 0 {
|
||||
ctx.gas_meter.gas_left()
|
||||
} else {
|
||||
gas.saturated_into()
|
||||
};
|
||||
let ext = &mut ctx.ext;
|
||||
let call_outcome = ctx.gas_meter.with_nested(nested_gas_limit, |nested_meter| {
|
||||
match nested_meter {
|
||||
Some(nested_meter) => {
|
||||
ext.call(
|
||||
&callee,
|
||||
value,
|
||||
nested_meter,
|
||||
input_data,
|
||||
)
|
||||
.map_err(|err| err.buffer)
|
||||
}
|
||||
// there is not enough gas to allocate for the nested call.
|
||||
None => Err(input_data),
|
||||
}
|
||||
});
|
||||
|
||||
match call_outcome {
|
||||
Ok(output) => {
|
||||
ctx.scratch_buf = output.data;
|
||||
Ok(output.status.into())
|
||||
},
|
||||
Err(buffer) => {
|
||||
ctx.scratch_buf = buffer;
|
||||
ctx.scratch_buf.clear();
|
||||
Ok(TRAP_RETURN_CODE)
|
||||
},
|
||||
}
|
||||
},
|
||||
|
||||
// Instantiate a contract with the specified code hash.
|
||||
//
|
||||
// This function creates an account and executes the constructor defined in the code specified
|
||||
// by the code hash.
|
||||
//
|
||||
// If the constructor runs to completion, then this returns the status code that the newly
|
||||
// instantiated contract returns on exit in the bottom 8 bits of the return value. The top 24
|
||||
// bits are 0s. A status code of 0 indicates success, and any other code indicates a failure.
|
||||
// On failure, any state changes made by the called contract are reverted and the contract is
|
||||
// not instantiated. On a success status, the scratch buffer is filled with the encoded address
|
||||
// of the newly instantiated contract. In the case of a failure status, the scratch buffer is
|
||||
// cleared.
|
||||
//
|
||||
// If the contract traps during execution or otherwise fails to complete successfully, then
|
||||
// this function clears the scratch buffer and returns 0x0100. As with a failure status, any
|
||||
// state changes made by the called contract are reverted.
|
||||
|
||||
// This function creates an account and executes initializer code. After the execution,
|
||||
// the returned buffer is saved as the code of the created account.
|
||||
//
|
||||
// Returns 0 on the successful contract instantiation and puts the address of the instantiated
|
||||
// contract into the scratch buffer. Otherwise, returns non-zero value and clears the scratch
|
||||
// buffer.
|
||||
//
|
||||
// - code_hash_ptr: a pointer to the buffer that contains the initializer code.
|
||||
// - code_hash_len: length of the initializer code buffer.
|
||||
// - gas: how much gas to devote to the execution of the initializer code.
|
||||
// - value_ptr: a pointer to the buffer with value, how much value to send.
|
||||
// Should be decodable as a `T::Balance`. Traps otherwise.
|
||||
// - value_len: length of the value buffer.
|
||||
// - input_data_ptr: a pointer to a buffer to be used as input data to the initializer code.
|
||||
// - input_data_len: length of the input data buffer.
|
||||
ext_instantiate(
|
||||
ctx,
|
||||
code_hash_ptr: u32,
|
||||
code_hash_len: u32,
|
||||
gas: u64,
|
||||
value_ptr: u32,
|
||||
value_len: u32,
|
||||
input_data_ptr: u32,
|
||||
input_data_len: u32
|
||||
) -> u32 => {
|
||||
let code_hash: CodeHash<<E as Ext>::T> =
|
||||
read_sandbox_memory_as(ctx, code_hash_ptr, code_hash_len)?;
|
||||
let value: BalanceOf<<E as Ext>::T> =
|
||||
read_sandbox_memory_as(ctx, value_ptr, value_len)?;
|
||||
|
||||
// Read input data into the scratch buffer, then take ownership of it.
|
||||
read_sandbox_memory_into_scratch(ctx, input_data_ptr, input_data_len)?;
|
||||
let input_data = mem::replace(&mut ctx.scratch_buf, Vec::new());
|
||||
|
||||
let nested_gas_limit = if gas == 0 {
|
||||
ctx.gas_meter.gas_left()
|
||||
} else {
|
||||
gas.saturated_into()
|
||||
};
|
||||
let ext = &mut ctx.ext;
|
||||
let instantiate_outcome = ctx.gas_meter.with_nested(nested_gas_limit, |nested_meter| {
|
||||
match nested_meter {
|
||||
Some(nested_meter) => {
|
||||
ext.instantiate(
|
||||
&code_hash,
|
||||
value,
|
||||
nested_meter,
|
||||
input_data
|
||||
)
|
||||
.map_err(|err| err.buffer)
|
||||
}
|
||||
// there is not enough gas to allocate for the nested call.
|
||||
None => Err(input_data),
|
||||
}
|
||||
});
|
||||
match instantiate_outcome {
|
||||
Ok((address, output)) => {
|
||||
let is_success = output.is_success();
|
||||
ctx.scratch_buf = output.data;
|
||||
ctx.scratch_buf.clear();
|
||||
if is_success {
|
||||
// Write the address to the scratch buffer.
|
||||
address.encode_to(&mut ctx.scratch_buf);
|
||||
}
|
||||
Ok(output.status.into())
|
||||
},
|
||||
Err(buffer) => {
|
||||
ctx.scratch_buf = buffer;
|
||||
ctx.scratch_buf.clear();
|
||||
Ok(TRAP_RETURN_CODE)
|
||||
},
|
||||
}
|
||||
},
|
||||
|
||||
// Save a data buffer as a result of the execution, terminate the execution and return a
|
||||
// successful result to the caller.
|
||||
//
|
||||
// This is the only way to return a data buffer to the caller.
|
||||
ext_return(ctx, data_ptr: u32, data_len: u32) => {
|
||||
charge_gas(ctx.gas_meter, ctx.schedule, RuntimeToken::ReturnData(data_len))?;
|
||||
|
||||
read_sandbox_memory_into_scratch(ctx, data_ptr, data_len)?;
|
||||
let output_buf = mem::replace(&mut ctx.scratch_buf, Vec::new());
|
||||
|
||||
ctx.special_trap = Some(SpecialTrap::Return(output_buf));
|
||||
|
||||
// The trap mechanism is used to immediately terminate the execution.
|
||||
// This trap should be handled appropriately before returning the result
|
||||
// to the user of this crate.
|
||||
Err(sandbox::HostError)
|
||||
},
|
||||
|
||||
// Stores the address of the caller into the scratch buffer.
|
||||
//
|
||||
// If this is a top-level call (i.e. initiated by an extrinsic) the origin address of the
|
||||
// extrinsic will be returned. Otherwise, if this call is initiated by another contract then the
|
||||
// address of the contract will be returned.
|
||||
ext_caller(ctx) => {
|
||||
ctx.scratch_buf.clear();
|
||||
ctx.ext.caller().encode_to(&mut ctx.scratch_buf);
|
||||
Ok(())
|
||||
},
|
||||
|
||||
// Stores the address of the current contract into the scratch buffer.
|
||||
ext_address(ctx) => {
|
||||
ctx.scratch_buf.clear();
|
||||
ctx.ext.address().encode_to(&mut ctx.scratch_buf);
|
||||
Ok(())
|
||||
},
|
||||
|
||||
// Stores the gas price for the current transaction into the scratch buffer.
|
||||
//
|
||||
// The data is encoded as T::Balance. The current contents of the scratch buffer are overwritten.
|
||||
ext_gas_price(ctx) => {
|
||||
ctx.scratch_buf.clear();
|
||||
ctx.gas_meter.gas_price().encode_to(&mut ctx.scratch_buf);
|
||||
Ok(())
|
||||
},
|
||||
|
||||
// Stores the amount of gas left into the scratch buffer.
|
||||
//
|
||||
// The data is encoded as Gas. The current contents of the scratch buffer are overwritten.
|
||||
ext_gas_left(ctx) => {
|
||||
ctx.scratch_buf.clear();
|
||||
ctx.gas_meter.gas_left().encode_to(&mut ctx.scratch_buf);
|
||||
Ok(())
|
||||
},
|
||||
|
||||
// Stores the balance of the current account into the scratch buffer.
|
||||
//
|
||||
// The data is encoded as T::Balance. The current contents of the scratch buffer are overwritten.
|
||||
ext_balance(ctx) => {
|
||||
ctx.scratch_buf.clear();
|
||||
ctx.ext.balance().encode_to(&mut ctx.scratch_buf);
|
||||
Ok(())
|
||||
},
|
||||
|
||||
// Stores the value transferred along with this call or as endowment into the scratch buffer.
|
||||
//
|
||||
// The data is encoded as T::Balance. The current contents of the scratch buffer are overwritten.
|
||||
ext_value_transferred(ctx) => {
|
||||
ctx.scratch_buf.clear();
|
||||
ctx.ext.value_transferred().encode_to(&mut ctx.scratch_buf);
|
||||
Ok(())
|
||||
},
|
||||
|
||||
// Stores the random number for the current block for the given subject into the scratch
|
||||
// buffer.
|
||||
//
|
||||
// The data is encoded as T::Hash. The current contents of the scratch buffer are
|
||||
// overwritten.
|
||||
ext_random(ctx, subject_ptr: u32, subject_len: u32) => {
|
||||
// The length of a subject can't exceed `max_subject_len`.
|
||||
if subject_len > ctx.schedule.max_subject_len {
|
||||
return Err(sandbox::HostError);
|
||||
}
|
||||
|
||||
let subject_buf = read_sandbox_memory(ctx, subject_ptr, subject_len)?;
|
||||
ctx.scratch_buf.clear();
|
||||
ctx.ext.random(&subject_buf).encode_to(&mut ctx.scratch_buf);
|
||||
Ok(())
|
||||
},
|
||||
|
||||
// Load the latest block timestamp into the scratch buffer
|
||||
ext_now(ctx) => {
|
||||
ctx.scratch_buf.clear();
|
||||
ctx.ext.now().encode_to(&mut ctx.scratch_buf);
|
||||
Ok(())
|
||||
},
|
||||
|
||||
// Stores the minimum balance (a.k.a. existential deposit) into the scratch buffer.
|
||||
//
|
||||
// The data is encoded as T::Balance. The current contents of the scratch buffer are
|
||||
// overwritten.
|
||||
ext_minimum_balance(ctx) => {
|
||||
ctx.scratch_buf.clear();
|
||||
ctx.ext.minimum_balance().encode_to(&mut ctx.scratch_buf);
|
||||
Ok(())
|
||||
},
|
||||
|
||||
// Decodes the given buffer as a `T::Call` and adds it to the list
|
||||
// of to-be-dispatched calls.
|
||||
//
|
||||
// All calls made it to the top-level context will be dispatched before
|
||||
// finishing the execution of the calling extrinsic.
|
||||
ext_dispatch_call(ctx, call_ptr: u32, call_len: u32) => {
|
||||
let call: <<E as Ext>::T as Trait>::Call =
|
||||
read_sandbox_memory_as(ctx, call_ptr, call_len)?;
|
||||
|
||||
// Charge gas for dispatching this call.
|
||||
let fee = {
|
||||
let balance_fee = <<E as Ext>::T as Trait>::ComputeDispatchFee::compute_dispatch_fee(&call);
|
||||
approx_gas_for_balance(ctx.gas_meter.gas_price(), balance_fee)
|
||||
};
|
||||
charge_gas(&mut ctx.gas_meter, ctx.schedule, RuntimeToken::ComputedDispatchFee(fee))?;
|
||||
|
||||
ctx.ext.note_dispatch_call(call);
|
||||
|
||||
Ok(())
|
||||
},
|
||||
|
||||
// Record a request to restore the caller contract to the specified contract.
|
||||
//
|
||||
// At the finalization stage, i.e. when all changes from the extrinsic that invoked this
|
||||
// contract are commited, this function will compute a tombstone hash from the caller's
|
||||
// storage and the given code hash and if the hash matches the hash found in the tombstone at
|
||||
// the specified address - kill the caller contract and restore the destination contract and set
|
||||
// the specified `rent_allowance`. All caller's funds are transfered to the destination.
|
||||
//
|
||||
// This function doesn't perform restoration right away but defers it to the end of the
|
||||
// transaction. If there is no tombstone in the destination address or if the hashes don't match
|
||||
// then restoration is cancelled and no changes are made.
|
||||
//
|
||||
// `dest_ptr`, `dest_len` - the pointer and the length of a buffer that encodes `T::AccountId`
|
||||
// with the address of the to be restored contract.
|
||||
// `code_hash_ptr`, `code_hash_len` - the pointer and the length of a buffer that encodes
|
||||
// a code hash of the to be restored contract.
|
||||
// `rent_allowance_ptr`, `rent_allowance_len` - the pointer and the length of a buffer that
|
||||
// encodes the rent allowance that must be set in the case of successful restoration.
|
||||
// `delta_ptr` is the pointer to the start of a buffer that has `delta_count` storage keys
|
||||
// laid out sequentially.
|
||||
ext_restore_to(
|
||||
ctx,
|
||||
dest_ptr: u32,
|
||||
dest_len: u32,
|
||||
code_hash_ptr: u32,
|
||||
code_hash_len: u32,
|
||||
rent_allowance_ptr: u32,
|
||||
rent_allowance_len: u32,
|
||||
delta_ptr: u32,
|
||||
delta_count: u32
|
||||
) => {
|
||||
let dest: <<E as Ext>::T as system::Trait>::AccountId =
|
||||
read_sandbox_memory_as(ctx, dest_ptr, dest_len)?;
|
||||
let code_hash: CodeHash<<E as Ext>::T> =
|
||||
read_sandbox_memory_as(ctx, code_hash_ptr, code_hash_len)?;
|
||||
let rent_allowance: BalanceOf<<E as Ext>::T> =
|
||||
read_sandbox_memory_as(ctx, rent_allowance_ptr, rent_allowance_len)?;
|
||||
let delta = {
|
||||
// We don't use `with_capacity` here to not eagerly allocate the user specified amount
|
||||
// of memory.
|
||||
let mut delta = Vec::new();
|
||||
let mut key_ptr = delta_ptr;
|
||||
|
||||
for _ in 0..delta_count {
|
||||
const KEY_SIZE: usize = 32;
|
||||
|
||||
// Read the delta into the provided buffer and collect it into the buffer.
|
||||
let mut delta_key: StorageKey = [0; KEY_SIZE];
|
||||
read_sandbox_memory_into_buf(ctx, key_ptr, &mut delta_key)?;
|
||||
delta.push(delta_key);
|
||||
|
||||
// Offset key_ptr to the next element.
|
||||
key_ptr = key_ptr.checked_add(KEY_SIZE as u32).ok_or_else(|| sandbox::HostError)?;
|
||||
}
|
||||
|
||||
delta
|
||||
};
|
||||
|
||||
ctx.ext.note_restore_to(
|
||||
dest,
|
||||
code_hash,
|
||||
rent_allowance,
|
||||
delta,
|
||||
);
|
||||
|
||||
Ok(())
|
||||
},
|
||||
|
||||
// Returns the size of the scratch buffer.
|
||||
//
|
||||
// For more details on the scratch buffer see `ext_scratch_read`.
|
||||
ext_scratch_size(ctx) -> u32 => {
|
||||
Ok(ctx.scratch_buf.len() as u32)
|
||||
},
|
||||
|
||||
// Copy data from the scratch buffer starting from `offset` with length `len` into the contract
|
||||
// memory. The region at which the data should be put is specified by `dest_ptr`.
|
||||
//
|
||||
// In order to get size of the scratch buffer use `ext_scratch_size`. At the start of contract
|
||||
// execution, the scratch buffer is filled with the input data. Whenever a contract calls
|
||||
// function that uses the scratch buffer the contents of the scratch buffer are overwritten.
|
||||
ext_scratch_read(ctx, dest_ptr: u32, offset: u32, len: u32) => {
|
||||
let offset = offset as usize;
|
||||
if offset > ctx.scratch_buf.len() {
|
||||
// Offset can't be larger than scratch buffer length.
|
||||
return Err(sandbox::HostError);
|
||||
}
|
||||
|
||||
// This can't panic since `offset <= ctx.scratch_buf.len()`.
|
||||
let src = &ctx.scratch_buf[offset..];
|
||||
if src.len() != len as usize {
|
||||
return Err(sandbox::HostError);
|
||||
}
|
||||
|
||||
// Finally, perform the write.
|
||||
write_sandbox_memory(
|
||||
ctx.schedule,
|
||||
ctx.gas_meter,
|
||||
&ctx.memory,
|
||||
dest_ptr,
|
||||
src,
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
},
|
||||
|
||||
// Copy data from contract memory starting from `src_ptr` with length `len` into the scratch
|
||||
// buffer. This overwrites the entire scratch buffer and resizes to `len`. Specifying a `len`
|
||||
// of zero clears the scratch buffer.
|
||||
//
|
||||
// This should be used before exiting a call or instantiation in order to set the return data.
|
||||
ext_scratch_write(ctx, src_ptr: u32, len: u32) => {
|
||||
read_sandbox_memory_into_scratch(ctx, src_ptr, len)
|
||||
},
|
||||
|
||||
// Deposit a contract event with the data buffer and optional list of topics. There is a limit
|
||||
// on the maximum number of topics specified by `max_event_topics`.
|
||||
//
|
||||
// - topics_ptr - a pointer to the buffer of topics encoded as `Vec<T::Hash>`. The value of this
|
||||
// is ignored if `topics_len` is set to 0. The topics list can't contain duplicates.
|
||||
// - topics_len - the length of the topics buffer. Pass 0 if you want to pass an empty vector.
|
||||
// - data_ptr - a pointer to a raw data buffer which will saved along the event.
|
||||
// - data_len - the length of the data buffer.
|
||||
ext_deposit_event(ctx, topics_ptr: u32, topics_len: u32, data_ptr: u32, data_len: u32) => {
|
||||
let mut topics: Vec::<TopicOf<<E as Ext>::T>> = match topics_len {
|
||||
0 => Vec::new(),
|
||||
_ => read_sandbox_memory_as(ctx, topics_ptr, topics_len)?,
|
||||
};
|
||||
|
||||
// If there are more than `max_event_topics`, then trap.
|
||||
if topics.len() > ctx.schedule.max_event_topics as usize {
|
||||
return Err(sandbox::HostError);
|
||||
}
|
||||
|
||||
// Check for duplicate topics. If there are any, then trap.
|
||||
if has_duplicates(&mut topics) {
|
||||
return Err(sandbox::HostError);
|
||||
}
|
||||
|
||||
let event_data = read_sandbox_memory(ctx, data_ptr, data_len)?;
|
||||
|
||||
charge_gas(
|
||||
ctx.gas_meter,
|
||||
ctx.schedule,
|
||||
RuntimeToken::DepositEvent(topics.len() as u32, data_len)
|
||||
)?;
|
||||
ctx.ext.deposit_event(topics, event_data);
|
||||
|
||||
Ok(())
|
||||
},
|
||||
|
||||
// Set rent allowance of the contract
|
||||
//
|
||||
// - value_ptr: a pointer to the buffer with value, how much to allow for rent
|
||||
// Should be decodable as a `T::Balance`. Traps otherwise.
|
||||
// - value_len: length of the value buffer.
|
||||
ext_set_rent_allowance(ctx, value_ptr: u32, value_len: u32) => {
|
||||
let value: BalanceOf<<E as Ext>::T> =
|
||||
read_sandbox_memory_as(ctx, value_ptr, value_len)?;
|
||||
ctx.ext.set_rent_allowance(value);
|
||||
|
||||
Ok(())
|
||||
},
|
||||
|
||||
// Stores the rent allowance into the scratch buffer.
|
||||
//
|
||||
// The data is encoded as T::Balance. The current contents of the scratch buffer are overwritten.
|
||||
ext_rent_allowance(ctx) => {
|
||||
ctx.scratch_buf.clear();
|
||||
ctx.ext.rent_allowance().encode_to(&mut ctx.scratch_buf);
|
||||
|
||||
Ok(())
|
||||
},
|
||||
|
||||
// Prints utf8 encoded string from the data buffer.
|
||||
// Only available on `--dev` chains.
|
||||
// This function may be removed at any time, superseded by a more general contract debugging feature.
|
||||
ext_println(ctx, str_ptr: u32, str_len: u32) => {
|
||||
let data = read_sandbox_memory(ctx, str_ptr, str_len)?;
|
||||
if let Ok(utf8) = core::str::from_utf8(&data) {
|
||||
sr_primitives::print(utf8);
|
||||
}
|
||||
Ok(())
|
||||
},
|
||||
|
||||
// Stores the current block number of the current contract into the scratch buffer.
|
||||
ext_block_number(ctx) => {
|
||||
ctx.scratch_buf.clear();
|
||||
ctx.ext.block_number().encode_to(&mut ctx.scratch_buf);
|
||||
Ok(())
|
||||
},
|
||||
|
||||
// Retrieve the value under the given key from the **runtime** storage and return 0.
|
||||
// If there is no entry under the given key then this function will return 1 and
|
||||
// clear the scratch buffer.
|
||||
//
|
||||
// - key_ptr: the pointer into the linear memory where the requested value is placed.
|
||||
// - key_len: the length of the key in bytes.
|
||||
ext_get_runtime_storage(ctx, key_ptr: u32, key_len: u32) -> u32 => {
|
||||
// Steal the scratch buffer so that we hopefully save an allocation for the `key_buf`.
|
||||
read_sandbox_memory_into_scratch(ctx, key_ptr, key_len)?;
|
||||
let key_buf = mem::replace(&mut ctx.scratch_buf, Vec::new());
|
||||
|
||||
match ctx.ext.get_runtime_storage(&key_buf) {
|
||||
Some(value_buf) => {
|
||||
// The given value exists.
|
||||
ctx.scratch_buf = value_buf;
|
||||
Ok(0)
|
||||
}
|
||||
None => {
|
||||
// Put back the `key_buf` and allow its allocation to be reused.
|
||||
ctx.scratch_buf = key_buf;
|
||||
ctx.scratch_buf.clear();
|
||||
Ok(1)
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/// Finds duplicates in a given vector.
|
||||
///
|
||||
/// This function has complexity of O(n log n) and no additional memory is required, although
|
||||
/// the order of items is not preserved.
|
||||
fn has_duplicates<T: PartialEq + AsRef<[u8]>>(items: &mut Vec<T>) -> bool {
|
||||
// Sort the vector
|
||||
items.sort_unstable_by(|a, b| {
|
||||
Ord::cmp(a.as_ref(), b.as_ref())
|
||||
});
|
||||
// And then find any two consecutive equal elements.
|
||||
items.windows(2).any(|w| {
|
||||
match w {
|
||||
&[ref a, ref b] => a == b,
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user