-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Integrate Wasmtime for runtime execution #3869
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Gave a brief and local review
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
TY, TY, TY for going the trampoline way ❤️
A general question, why is wasmtime hidden behind a feature flag?
/// Instantiation error. | ||
Instantiation(Error), | ||
/// The compiler does not support the host machine as a target. | ||
#[cfg(feature = "wasmtime")] | ||
MissingCompilerSupport(&'static str), |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Which targets do they support?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A few more comments
|
||
// Check that heap_pages is within the allowed range. | ||
let max_heap_pages = max_memory_size.map(|max| max.saturating_sub(min_memory_size)); | ||
let heap_pages = heap_pages_valid(heap_pages, max_heap_pages) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am not sure if I understand what is happening here... Why do we substrate the initial/minimum from the maximum here?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Because the heap_pages
value is the number of additional pages (to the initial/minimum) that are added. And that can't exceed the maximum. Right?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is it?
If my mental model is correct, it should be the value ultimately coming from the :heap_pages
which is defined like this:
Number of wasm linear memory pages required for execution of the runtime.
It doesn't say that this value is relative to the initial number of pages of :code
, just an absolute number. If it wasn't the case I'd name this variable delta_heap_pages
or additional_heap_pages
or something that emphasizes its relativeness.
But you are right about the maximum. In no cases we should exceed maximum.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just checked the code and yeah, it seems like it's always been additional_heap_pages
. I think this is confusing, but oh well.
As a datapoint, syncing on Kusama CC2 on my machine:
which gives a solid 6x improvement |
Aside from running more trusted runtimes like sprees, there might be places where anyone who must commit early could use wasmi, but any fishing checks could use wasmtime. As an example, parachain validators could all use wasmi, while secondary checks can use wasmtime, but if block validation failed then they recheck in wasmi before submitting any invalid block report. In theory, an adversary who controlled the parachain validators could craft their attack block to pass wasmtime but not wasmi, so maybe some secondary checks still running wasmi makes sense under such a threat model. |
Wasm execution methods.
They were not passing compilation before and criterion seems to be more widely used in Substrate.
The implementation demonstrates the outline of the execution, but does not link against the external host functions.
The SandboxCapabilities::invoke is still left unimplemented.
@pepyakin @gavofyork Ready for merge? |
@bkchr I am also worried about arbitrary code execution vulnerabilities that can be exploited by malicious wasm files. Incorrect block execution is very very very bad, but it can be detected by re-running against wasmi, and (at least in theory) fixed by a hard fork if necessary. Arbitrary code execution, on the other hand, could easily be fatal to the entire system. @kirushik probably has something to say here, and I trust his opinion more than my own. |
As long as it lives in Substrate, we will take over the ownership. If wasmtime releases a new version that exposes this interface, I would strongly vote to use this directly. Do you know if there is any plan to expose this interface from wasmtime? (Coulld we make a pr for this?) |
We do this to ensure that panics do not cross language boundaries.
# Conflicts: # node/cli/Cargo.toml
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am ok to merge this branch as is, as long as we keep the feature flag and given that we are going to keep iterating on in.
@demimarie-parity after chatting with @pepyakin I am not sure if there's anything we can do as a part of this pull-request. Sandboxing the compiled runtime will negate all the potential performance gains of wasmtime — I think your research showed that clearly to us; at the same time, our runtime wasm code should be trusted enough for us to only worry about accidental miscompilations, not deliberate malicious ones. I think the only real protection we can add (other than putting effort into making wasmtime and later lightbeam bulletproof) is writing a decent sandboxing guidelines for the launching substrate-based chains in general. Maybe you are willing to try that, as a separate issue from this one? |
@kirushik 👍, although we never did any actual benchmarks. That said, I do believe that untrusted wasm code (such as third-party smart contracts) should still be interpreted, at least for now. I doubt it is a bottleneck in practice, and the security risks are much more relevant in that case. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Also okay from my side :)
# Conflicts: # node/cli/Cargo.toml
* Make sure im-online reports are high priority. * Bump runtime. base-code edit option environment block num - test metrics fn push and finalized listing best_block_num listing Add translate API for storage values (paritytech#3947) * Add translate item. * fix * doc * fix doc * A test added. * Apply suggestions from code review Co-Authored-By: Bastian Köcher <[email protected]> * address suggestion im-online: account for block authorship (paritytech#3973) * im-online: account for block authorship * im-online: add test for block authorship onlineness * im-online: cleanup * im-online: fix test grandpa: Use storage proofs for Grandpa authorities (paritytech#3734) * grandpa: Write Grandpa authorities to well known key. Instead of requiring execution proofs for Grandpa authorities, this enables much simpler storage proofs. * grandpa: Introduce named AuthorityList type. * grandpa: Storage migration for srml-grandpa module. * Remove no-longer-used GrandpaApi runtime API. * grandpa: Write AuthorityList to storage with encoding version. We expect the AuthorityList type may change (eg. key changes). To make upgrades smoother, include a version in the stored value. * Bump node runtime spec version. * Update srml/grandpa/src/lib.rs Co-Authored-By: André Silva <[email protected]> Add the code for compiling node-cli for WASM-browser (paritytech#3974) * Extract CLI to separate module in node/cli * Make node/cli compile for WASM * More work on node/cli browser * More work on browser node * More work * More work * Purge a bit the CI script * More clean up * Remove substrate-finality-grandpa from the CI Its tests use tokio, which fails to compile. * Address review * Add rocksdb feature to the service * Fix substrate-service WASM CI * Apply suggestions from code review Co-Authored-By: Bastian Köcher <[email protected]> * Don't WASM-compile substrate-service altogether Remove NetworkSpecialization::on_event (paritytech#3976) and backend reference to rpc builder (paritytech#3979) Improve doc for storages in srml-support (paritytech#3982) * improve doc * Apply suggestions from code review Retire `storage_items!` (paritytech#3950) * Retire storage_items * Add storage_items! tests to srml/support/tests * Assimilate genesis config Revert "grandpa: Use storage proofs for Grandpa authorities (paritytech#3734)" (paritytech#3983) This reverts commit c3b1a98. Print warning again if polling network is too long (paritytech#3984) Add events for im_online (paritytech#3991) * Add AllGood event for im_online * Another event just in case. * Bump runtime authority-discovery: futures 03 Future (paritytech#3848) * authority-discovery: futures 03 Future * make ci happy * use futures timer instead of tokio timer * Update core/authority-discovery/src/lib.rs Co-Authored-By: Bastian Köcher <[email protected]> * remove tokio 01 runtime * trigger build * kill futures01 * rename futures Integrate Wasmtime for runtime execution (paritytech#3869) * executor: Use non wasmi-specific execution in tests. * executor: Move all runtime execution tests into tests file. * executor: Use test_case macro to easily execute tests with different Wasm execution methods. * executor: Convert errors to strings with Display, not Debug. * node-executor: Rewrite benchmarks with criterion. They were not passing compilation before and criterion seems to be more widely used in Substrate. * executor: Begin implementation of Wasm runtime. The implementation demonstrates the outline of the execution, but does not link against the external host functions. * executor: Define and implement basic FunctionExecutor. The SandboxCapabilities::invoke is still left unimplemented. * executor: Implement host function trampoline generation. * executor: Instantiate and link runtime module to env module. * executor: Provide input data during wasmtime execution. * executor: Implement SandboxCapabilites::invoke for wasmtime executor. * executor: Integrate and test wasmtime execution method. * executor: Improve FunctionExecution error messages. * Scope the unsafe blocks to be smaller. * Rename TrampolineState to EnvState. * Let EnvState own its own compiler instead of unsafe lifetime cast. * Refactor out some common wasmi/wasmtime logic. * Typos and cosmetic changes. * More trampoline comments. * Cargo.lock update. * cli: CLI option for running Substrate with compiled Wasm execution. * executor: Switch dependency from fork to official wasmtime repo. * Quiet down cranelift logs. * Explicitly catch panics during host calls. We do this to ensure that panics do not cross language boundaries. * Additional checks and clarifications in make_trampoline. * Fixes after merge from master and panic safety for wasmtime instantiation. Implement Debug for some structures (paritytech#3941) * Implement Debug for some structures `NetworkConfiguration`, `TransportConfig`, `NodeKeyConfig` and `Secret`. Needs a new release of the `rust-libp2p` crate. This PR is just a reminder. * Explicitly separate `std` and `core` * Add manual implementation for Secret Possible fix to storage cache (paritytech#3989) * Comment local_cache propagation * Add test * Deny cache when modifications are unknown * Fix indentation Don't panic in Offchain test context, when we are already panicking (paritytech#3996) executor: Move runtime version caching out of WasmRuntime interface. (paritytech#3993) * executor: Move runtime caching out of WasmRuntime interface. The runtime version is now fetched and cached at a higher level, not within the WasmRuntime trait implementations. * executor: Require successful querying of runtime version. Move config path generation into the service config for reusability (paritytech#3978) * Move config path generation into the service config for reusability * Make NoCostum Default and fix tests * Apply suggestions from code review Co-Authored-By: Bastian Köcher <[email protected]> * remove function not used anymore * Make path into an option * remove database_path function and call it directly * remove helper functions, use consts expose offchain worker storage prefix (paritytech#3977) * expose offchain worker storage prefix * add docs * move STORAGE_PREFIX to primitives Optional serde for phragmen support (paritytech#3994) * Add serde to phragmen * Update lock file * and bump a version * and bump a version again * Apply suggestions from code review Co-Authored-By: Bastian Köcher <[email protected]> * revert impl-tarit for tuple update * revert session. * Revert "revert session." This reverts commit 98086c9. * Revert "revert impl-tarit for tuple update" This reverts commit 28a7fdd. doc (paritytech#3995) Implement color output for wasm builder (paritytech#4004) * Implement color output for wasm builder * Fix `Cargo.lock` CI test executor with wasmtime (paritytech#4005) Avoid sending heartbeat if we are already considered online. (paritytech#3981) * Don't send a heartbeat if already online. * Remove env_logger. * Update lock. * Bump runtime. * Merge master Deprecate ValidateUnsigned and prevent duplicate heartbeats (paritytech#3975) * Add pre-dispatch checks for ValidateUnsigned * Deprecate ValidateUnsigned. * Bump specversion. * Fix test. fix formula in comment (paritytech#4006) Substrate EVM (paritytech#3927) * srml-evm: init the basic structures * srml-evm: finish executor implementation * srml-evm: implement balance deposit and withdraw * srml-evm: implement the actuall call/create * srml-evm: use crates.io version of evm * srml-evm: fix no-std compile * Remove dependency patch * Update to evm 0.14 * Use double map for account storage * Add precompiles support * Add some basic docs * Use runtime_io::chain_id() * Update srml/evm/src/lib.rs Co-Authored-By: Xiliang Chen <[email protected]> * Update srml/evm/src/lib.rs Co-Authored-By: Xiliang Chen <[email protected]> * Fix WithdrawReason * Unique saturate balance to u128 * Unique saturate withdraw to u128 * Remove extern crate alloc * Move account code to a separate storage and use ref for convert_account_id * More match cause for error message * Fix potential interger overflow * Use decode_len for fetching code length support crypto primitives for no_std introducing `full_crypto` feature (paritytech#3778) * introduced "with_crypto" feature and applied switches like in substrate-api-client fork * introduced "with_crypto" feature and applied switches like in substraTEE-worker fork * distinguishing core::hash vs std::hash * @bkchr's review requests fulfilled * fixes * revert dependency upgrade ed25519-dalek * added full_crypto features to all crates using app_crypto! macro * fixing CI complaints. * fix again * adding CI test for with_crypto feature * added full_crypto for ecdsa. now builds wit h--no-deafault-features --features with_crypto * remove --release from CI test * @bkchr requested changes. moved full_crypto CI test to build stage * fixing no_std issue * CI fresh copy from srml-staking * gitlab CI with +nightly * solved no-feature-in-macro dilemma * cosmetics * Update core/application-crypto/src/sr25519.rs Co-Authored-By: Bastian Köcher <[email protected]> * Update core/application-crypto/src/ed25519.rs Co-Authored-By: Bastian Köcher <[email protected]> * even more simple * undo line delete * refactoring app_crypto macro. splitting functionalities based on full_crypto feature * whitespace cosmetics refactor code: remove unused import (paritytech#4010) * remove unused import * fix test error Update RPC deps. (paritytech#4012) * Bump rpc deps * Update core/test-runtime/src/genesismap.rs Co-Authored-By: Bastian Köcher <[email protected]> Enable parallel block download (paritytech#4014) Traffic statistics (paritytech#4017) * Network stats * Fixed tests Limit longevity of im-online heartbeats. (paritytech#4011) * Limit longevity of im-online heartbeats. * Unused import. * Use parameter for session duration. Header-only sync for old forks (paritytech#3942) * Header-only sync for old forks * Simplified blocks-count * Update core/consensus/common/src/block_import.rs Co-Authored-By: Marcio Diaz <[email protected]> Revert "Header-only sync for old forks (paritytech#3942)" (paritytech#4022) This reverts commit ac78c90. Don't re-compile on every `cargo run` (paritytech#4019) - Add new crate `substrate-build-script-utils` to unify the code of `node`, `node-template` and `polkadot-node`. - The `node-cli` build script needs to search upwards for the `.git/HEAD` file to find it. fix warnings (paritytech#4024) Less verbose console output (paritytech#4029) Apply breaking changes of new libp2p versions (paritytech#3877) * Apply breaking changes of new libp2p versions * Oops, forgot to update version * Fix tests * Fix imports with WASM * Fix WASM for real * Update core/network/src/debug_info.rs Co-Authored-By: Roman Borschel <[email protected]> * Fix compilation Update `syn`, `proc-macro2` and `quote` to `1.x` (paritytech#4028) Make `TestExternalities` implement `Send` (paritytech#4030) * Make `TestExternalities` implement `Send` + `Sync` * Fixes offchain * Make it just `Send` Treasury rewards should pay the remainder of the 10% (paritytech#4026) * Treasury rewards should pay the remainder of the 10%.. * Event for deposits coming into treasury * Fix tests * Remove OnDilution Also replace paths in [build-dependencies] (paritytech#4039) * Also replace paths in [build-dependencies] * Update scripts/node-template-release/src/main.rs Co-Authored-By: Bastian Köcher <[email protected]> * Slightly reduce memory usage * Update scripts/node-template-release/src/main.rs Co-Authored-By: Bastian Köcher <[email protected]> Decrease peer reputation on bad transactions (paritytech#4035) * Decrease reputation on bad transactions * Don't punish on duplicate transactions Add `ExistenceRequirement` to `Currency` trait (paritytech#4000) * Added a public transfer_some function and a private transfer_inner fn * Move transfer_some to the end of the module impl to fix failing contracts test * Change whitespace * Remove needless change to transfer logic * Fix error * Update srml/balances/src/lib.rs Co-Authored-By: joe petrowski <[email protected]> * Improve documentation and add test * Update srml/balances/src/lib.rs Co-Authored-By: Kian Paimani <[email protected]> * Switch to changing Currency trait instead Ban incoming invalid transactions (paritytech#4037) Improve auto-docs a little. (paritytech#4032) Check polkadot compilation. (paritytech#3980) * Check polkadot compilation. * Fix git grep. * Make sure to update properly. Use commit hash instead. Refactor out MaxPossibleReward, fix staking arithmetic (paritytech#4041) * Refactor out MaxPossibleReward, fix staking arithmetic * Fix rounding error in test grandpa: Use storage proofs for Grandpa authorities (paritytech#3985) Allow import withouth state verification (paritytech#4031) * Allow import without state verification * Explicit None Co-Authored-By: Robert Habermeier <[email protected]> Correctly serialize code in chain spec as hex (paritytech#4025) * Correctly serialize code in chain spec as hex. Due to a bug, the runtime code was previously serialized as a JSON array of numbers, pretty printed one byte per line. * Remove panic in macro and whitelist attribute types for storage genesis config lines. * Use syn::Error to enforce whitelisted attributes on genesis config. * Blacklist genesis extra config line attributes instead of whitelist. clean node/cli/Cargo.toml (paritytech#4046) * clean node/cli/Cargo.toml * minor fix * clean node/runtime/Cargo.toml fix two typos (paritytech#4048) Increase parallel downloads to 5 (paritytech#4045) * Increase parallel downloads to 5 * CLI param Remove dependencies on OpenSSL (paritytech#4036) * Remove dependency on hyper-tls This removes one of the dependencies on native-tls, and thus on OpenSSL. I will remove the other in a separate commit. * Remove the `HttpClient` enum It only had one variant. * Apply suggestions from code review Co-Authored-By: Pierre Krieger <[email protected]> fix inmemory (paritytech#4049) grandpa: progressively increase target gossip peers (paritytech#4050) * grandpa: stricter gossip message filtering * gossip: remove filtered message on send_message * gossip: add test for tracking of broadcast attempts * grandpa: only restrict gossip if we're connected to more than 5 authorities * grandpa: add test for progressive gossip * grandpa: add test for gossip filtering on local non-authority node * grandpa: fix doc * gossip, grandpa: tabify * grandpa: relax filtering logic for global messages Introduce thread pool for transaction validation. (paritytech#4051) Batch gossip messages (paritytech#4055) Fix minor comment typo "do" -> "do not" (paritytech#4054) Fix sync downloading ancient chains (paritytech#4060) * Update best block on announcement * Added a test grandpa: remove the periodic block announcer (paritytech#4062) * grandpa: remove the periodic block announcer * grandpa: remove periodic block announcer test Fix the ui tests (paritytech#4066) Improved cache documentation (paritytech#4067) Additional logging for the transaction pool. (paritytech#4068) * Additional logging for the pool. * Long line. Pass startup_time to telemetry (paritytech#4069) Further fix for common block update (paritytech#4071) Add a --no-private-ipv4 CLI option (paritytech#4042) * Add a --no-private-ipv4 CLI option * Fix tests * Fix tests Change max width to 100. (paritytech#4072) Don't update common block on ancient block import (paritytech#4073) Don't search for authority set change block if delay is zero (paritytech#4076) srml-timestamp: define max timestamp drift in millis (paritytech#4077) * srml-timestamp: define max timestamp drift in millis * srml-timestamp: suffix MAX_TIMESTAMP_DRIFT with unit Substrate runtime interface 2.0 (paritytech#4057) * Adds first version of traits for generating the host functions * First steps of the procedural macro * Implements generation of the host extern functions * Prefix ext host function with snake case trait name * Implement host functions implementation on the host * Change `HostFunctions` interface * Implement `HostFunctions` for tuples * Make `WasmExecutor` generic over the host functions * Begin to add a test and make it compile * Make the test succeed * Add test to ensure that host functions are not found * It's alive! Make the `set_storage` test work * Add test for mutable references * Code cleanup and documentation etc * Add marker trait for types that should be passed as SCALE encoded * Inherit the visibility from the trait and more improvements * More impls and move them into their own file * Code simplification by dropping one trait * Give it a better name * Implement traits for arrays * Refactor code to support pass by codec/inner * Docs * Implement pass by inner for some crypto types and add a test * Implement exchangeable function support * Rewrite sr-io with as runtime interface * Start reworking after master merge * Adds `PassByCodec` derive * Adds `PassByInner` derive * Fix compilation errors * More implementations * Implement runtime interface traits for `str` * Make `sr-io` compile again * Fix more compilation errors * More progress on getting stuff back to compile * More compilation fixes * Fix warnings * Remove le conversions * Add support for `wasm_only` interfaces * Implement `Allocator` interface * Improve error message * Move `WasmAllocator` to `sr-io` and more clean ups * Use correct function signature for wasm functions * Store the host functions with the Wasm runtime * Docs update * Fix compilation after master merge * Remove `sr-io/without_std` * Make `srml-support` tests run again * More compilation error fixes * Use correct doc syntax * Fix test-runtime * Fix compilation * Catch native panics when executing the wasm runtime As with the native runtime, we now catch all native panics when we execute the wasm runtime. The panics inside the wasm runtime were already catched before by the wasm executor automatically, but any panic in the host functions could bring down the node. The recent switch to execute the native counterpart of the host function in `sr-io`, makes this change required. The native `sr-io` functions just `panic` when something is not provided or any other error occured. * Fix compilation * Don't panic in a panic * Move `sr-sandbox` to new runtime interface * Fixes tests after sandbox changes * Make sure we detect invalid utf8 * Fixes after master merge * Adds pass by enum strategy * Fix wasmtime integration * Some macro structure clean up * Rework and test exchangebale host functions * PassBy derive macros documentation * Docs for `runtime_interface` macro * Support wild card argument names * Adds ui tests * Make sure that we are backwards compatible to the old runtime interfaces * Documentation * Fixes after latest master merge * Make `wasmtime` happy * Make `full_crypto` work * Make the new interface versionable * Rename `Sanboxing` to `Sandbox` * Don't finalize in test while importing * Fix Performance regression * Fix test Remove Self vote from phragmen (paritytech#4081) * first draft of everything that works * Some test fixes Allow ancient fork download after ancestry search (paritytech#4080) Typed chain state queries over rpc. (paritytech#4079) * Create typed client helpers for querying chain state storage items declared by 'decl_storage!'. * Update substrate-rpc-custom functions to use async await syntax. * The implementation of substrate-rpc-custom was a bit verbose and repetitive. This commit makes the implementation simpler by intruducing a struct which represents query for a typed value in storage. The new struct is called StorageQuery. A StorageQuery wraps a raw StorageKey but is not directy constructable. To construct a StorageQuery, the user must supply an implementation of a srml_support::storage::generator trait such as StorageValue or StorageMap. A type implementing one of the generator traits can be aquired by: A) marking a storage item as pub within a call to decl_storage (recommended) or B) implementing one of the generator types manually. While option B may sometimes me necessary, it's not recommended because separate manual implementaions may lose sync with the original definition. * drop unused dependency * fmt * Remove unnecessary pub from Authorities field in test-runtime storage declaration. This field was added to support a test in an earlier commit. The test no longer relies on test-runtime so the change can be reverted. * Move it to srml as support extension. * Fix long lines. * Fix. Cleanup filtered messages (paritytech#4082) Don't request old obsolete blocks (paritytech#4084) core/consensus: fix console output for slot duration (paritytech#4085) [WIP] .gitlab-ci.yml: Fix a check for polkadot to work on forked repos v2 (paritytech#4078) * Fix a check for polkadot to work on forked repos. * .gitlab-ci.yml: Add `git diff` for CI debugging * More future proof and less redundant. * .gitlab-ci.yml: Improve comments and refactor sed command * .gitlab-ci.yml: Remove two commas in a row * .gitlab-ci.yml: Ensure to match branch statements at the end * .gitlab-ci.yml: Reference concrete commit When one does not specify the concrete commit, cargo-update tries to checkout 'master' in the Substrate repository. * .gitlab-ci.yml: Remove 'git diff' debug line Fix runtime interface docs and remove accidentally added file (paritytech#4092) EVM should store contracts' balances in an account. (paritytech#4090) update tiny-keccak (paritytech#4093) * update tiny-keccak * fix * Update Cargo.toml * update Cargo.lock * remove keccak-hasher Do nothing for zero imbalances (paritytech#4089) Fix sync stalling on moving head (best block) prior to the tip of the chain sometimes (paritytech#4091) * Work around finalization woes * Fixed check_block * Added a test Weight annotation for block hooks. (paritytech#4058) * Initial version that works with proper tests. * get rid of todos and grumbles and such. * Cleanup and fix line-width * fix test runtime test Sensible limits for known blocks and extrinsics (paritytech#4094) Randomized tests on storage cache (paritytech#4070) * randomized tests * destroy clones * remove commented * fixes * add finalization fork State machine call proof backend (paritytech#3945) * drafting a proof extraction at the hashdb level (to include everything for the 'call' proof case). * use full proof by default (replace previous proof recorder). * fix warnings. * Cache value not found in proof recorder. * Remove need or internal backend struct. * fix type. * doc Translation for linked map (paritytech#4052) * make linked_map generic functions better * implement translation of linked map * proc-macro for linked map updated * test linked map migration * account for instances * address grumbles * cut map short if migration fails Do not download blocks too far ahead (paritytech#4095) Keep tack of best imported block precisely (paritytech#4100) Additional wasm diagnostics (paritytech#4097) * Wasm diagnostics * Pass the error * Make errno optional * Cargo.lock * Log the error Implement Copy, Deref and FromStr to (ed25519|sr25519)::Public (paritytech#3998) *: Refactor authority discovery (key mngmt, runtime API) (paritytech#3955) * {core,srml}/authority-discovery: Move generic to specific session keys * {srml,core}/authority-discovery: Verify signature outside of runtime Given that the `core/authority-discovery` uses concrete authority identifiers and signatures, one can verify a signature with the authority discovery within `core`. Given the above, the `verify` runtime api is obsolete and thus removed. * *: Add authority discovery to the set of session keys * *: Sign authority discovery DHT payload with keystore instead of runtime Instead of calling a runtime function to sign a dht payload, which then invokes the keystore, pass the keystore to the authority discovery module and use it directly. * core/authority-discovery: Give libp2p Kademlia time to start up * core/authority-discovery: Move authorities priority group name to const * node/runtime/src/lib.rs: Bump runtime spec version * *: Fix lints and node/testing test failures * *: Fix formatting * core/authority-discovery: Box dht event channel in unit tests * node/cli/src/service.rs: Fix future import * node/cli/src/service.rs: Replace unwrap by expect with proof * node/cli/src/chain_spec: Remove TODO for testnet key generation * core/authority-discovery/src/lib: Remove scale encoding TODOs * srml/authority-discovery: Make comment a doc comment * core/authority-discovery: Remove unused StreamExt import * node/runtime: Bump impl version to debug CI * Test ci. * Change the line width to 100. * Revert "Change the line width to 100." This reverts commit edff1f8. * Fix a check for polkadot to work on forked repos. * Revert "node/runtime: Bump impl version to debug CI" This reverts commit 1a90903. * Revert "Test ci." This reverts commit a2c9df5. * Cargo.lock: Fix wrong lock file merge * srml/authority-discovery: Keep track of new validator set not upcoming * core/authority-discovery: Document key retrieval functions Reorganising the repository - external renames and moves (paritytech#4074) * Adding first rough ouline of the repository structure * Remove old CI stuff * add title * formatting fixes * move node-exits job's script to scripts dir * Move docs into subdir * move to bin * move maintainence scripts, configs and helpers into its own dir * add .local to ignore * move core->client * start up 'test' area * move test client * move test runtime * make test move compile * Add dependencies rule enforcement. * Fix indexing. * Update docs to reflect latest changes * Moving /srml->/paint * update docs * move client/sr-* -> primitives/ * clean old readme * remove old broken code in rhd * update lock * Step 1. * starting to untangle client * Fix after merge. * start splitting out client interfaces * move children and blockchain interfaces * Move trie and state-machine to primitives. * Fix WASM builds. * fixing broken imports * more interface moves * move backend and light to interfaces * move CallExecutor * move cli off client * moving around more interfaces * re-add consensus crates into the mix * fix subkey path * relieve client from executor * starting to pull out client from grandpa * move is_decendent_of out of client * grandpa still depends on client directly * lemme tests pass * rename srml->paint * Make it compile. * rename interfaces->client-api * Move keyring to primitives. * fixup libp2p dep * fix broken use * allow dependency enforcement to fail * move fork-tree * Moving wasm-builder * make env * move build-script-utils * fixup broken crate depdencies and names * fix imports for authority discovery * fix typo * update cargo.lock * fixing imports * Fix paths and add missing crates * re-add missing crates base-code(rebased) set global/local metric + peers_num add prres_num,best_heght,finallity_heght add TARGET_SYN_NUMBER add README.md add README.md add README.md TARGET_SYN_NUMBER add README.md add README.md fix: justification and newline at EOF PEERS_NUM README.md update README.md update README.md update README.md update README.md README.md README.md translation of introduction feat: add prometheus! in substrate feat: add match for opts options SaturatedConversion remove refactor prometheus/lib.rs chore: make macros for widgets TODO : counter metrics type add->remove chore: add prometheus! to consensus chore: update README chore: refactor README chore: Refactor README chore: Refactor README chore: Refactor README
This implements a new Wasm execution method for the Substrate runtime using wasmtime. Wasmtime is a compiled WebAssembly runtime that executes Wasm code which has been compiled to native.
The code is hidden behind the "wasmtime" feature flag as this has fairly large dependencies. Perhaps we want to remove the feature flag though.
This PR depends on pending changes to
wasmtime
: bytecodealliance/wasmtime#340. Currently, in order to build, this PR uses my personal fork ofwasmtime
as a dependency. This needs to be resolved somehow before merging this PR.The first 5 or so commits are just test and benchmark refactors and could be merged independently.
Design & implementation notes
This uses lots of unsafe Rust. That is unavoidable.
At a high level, the first time a runtime is executed with this method, the Wasm module is compiled and the translated code is cached in memory. When a function is called in the module, the runtime mmaps some new memory for the instance, initializes it, and jumps into the dynamically generated code. In order to make an external call to a host function, the runtime registers a function pointer for each host function. This function pointer is to a dynamically-generated trampoline which embeds the numeric index of the host function inside it and calls a Rust entrypoint (the "stub_fn") with the host function index and a stack pointer with the arguments/return value slots. The stub function then sets up a
FunctionContext
and makes the call into the safe Rust implementation of the host call. On any errors, the error code is returned to the trampoline, which triggers a hardware interrupt. This is caught and handled by the runtime and execution of the module traps.FAQ
node-executor
benchmark to find out, which constructs a Substrate block with 20 simple balance transfers and measures the execution time. On my machine, I'm seeing a ~50% slowdown compared to native and a ~7x speedup compared to Wasmi.